DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    //Please take a look over the following code snippet for Protecting Excel Workbooks

//[C#]
 
//build URI
string strURI = "http://api.aspose.com/v1.1/cells/input.xls/protection"

string signedURI = Sign(strURI);

//serialize the JSON request content
Protection protection = new Protection();
protection.ProtectionType = protectionType;
protection.Password = password;

string strJSON = JsonConvert.SerializeObject(protection);

Stream responseStream = ProcessCommand(signedURI, "POST", strJSON);

StreamReader reader = new StreamReader(responseStream);
string strResponse = reader.ReadToEnd();

//Parse the json string to JObject
JObject pJSON = JObject.Parse(strResponse);

//Here is the Protection Class used above
public class Protection
{
    public Protection()
    {

    }

    public ProtectionType ProtectionType { get; set;}
    public string Password { get; set;}

}

/// <summary>
/// Represents Protection Types
/// </summary>
public enum ProtectionType
{
    All,
    Structure,
    Windows,
    None
}

//[Java Code]
 
AsposeApp.setAppSID("77******-1***-4***-a***-8***********");
AsposeApp.setAppKey("89******************************");

//build URI to Protect Workbook
string strURI = "http://api.aspose.com/v1.1/cells/input.xls/protection";

//sign URI
string signedURI = Sign(strURI);

//serialize the JSON request content
Protection protection = new Protection();
protection.setProtectionType(ProtectionType.All);
protection.setPassword("password");

String strJSON = "";

Gson gson = new Gson();

strJSON = gson.toJson(encryption, Encryption.class);

InputStream responseStream = ProcessCommand(signedURI, "POST", strJSON);

String strResponse = StreamToString(responseStream);

//Following is the Protection Class used above
public class Protection
    {
        public Protection()
        {

        }

        private ProtectionType ProtectionType;
        private String Password;

        public ProtectionType getProtectionType(){return ProtectionType;}
        public String getPassword(){return Password;}

        public void setProtectionType(ProtectionType ProtectionType){ this.ProtectionType=ProtectionType;}
        public void setPassword(String Password ){ this.Password=Password;}


    }

    /// <summary>
    /// Represents Protection Types
    /// </summary>
    public enum ProtectionType
    {
        All,
        Structure,
        Windows,
        None
    }

//[PHP Code]
 
AsposeApp::$appSID = "77******-1***-4***-a***-80**********";
AsposeApp::$appKey = "********************************";

AsposeApp::$outPutLocation = getcwd() . "/Output/";

//build URI to protect workbook
$strURI = 'http://api.aspose.com/v1.1/cells/Sample.xlsx/protection';

//Build JSON to post
$fieldsArray["ProtectionType"] = "all";
$fieldsArray["Password"] = "abc";
$json = json_encode($fieldsArray);

$signedURI = Utils::sign($strURI);

$responseStream = Utils::processCommand($signedURI, "POST", "json", $json);

//Download output file
$strURI = "http://api.aspose.com/v1.1/storage/file/Sample.xlsx";
$signedURI = Utils::sign($strURI);

$responseStream = Utils::processCommand($signedURI, "GET", "", "");
Utils::saveFile($responseStream, AsposeApp::$outPutLocation . "Sample.xlsx");
                
                    package org.gopaldas.readsps;
 
import java.io.IOException;
import java.net.URL;
 
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.ServiceException;
 
public class ReadSpreadsheet {
 
    public static final String GOOGLE_ACCOUNT_USERNAME = "xxxx@gmail.com"; // Fill in google account username
      public static final String GOOGLE_ACCOUNT_PASSWORD = "xxxx"; // Fill in google account password
      public static final String SPREADSHEET_URL = "https://spreadsheets.google.com/feeds/spreadsheets/1L8xtAJfOObsXL-XemliUV10wkDHQNxjn6jKS4XwzYZ8"; //Fill in google spreadsheet URI
 
      public static void main(String[] args) throws IOException, ServiceException
      {
        /** Our view of Google Spreadsheets as an authenticated Google user. */
        SpreadsheetService service = new SpreadsheetService("Print Google Spreadsheet Demo");
 
        // Login and prompt the user to pick a sheet to use.
        service.setUserCredentials(GOOGLE_ACCOUNT_USERNAME, GOOGLE_ACCOUNT_PASSWORD);
 
        // Load sheet
        URL metafeedUrl = new URL(SPREADSHEET_URL);
        SpreadsheetEntry spreadsheet = service.getEntry(metafeedUrl, SpreadsheetEntry.class);
        URL listFeedUrl = ((WorksheetEntry) spreadsheet.getWorksheets().get(0)).getListFeedUrl();
 
        // Print entries
        ListFeed feed = (ListFeed) service.getFeed(listFeedUrl, ListFeed.class);
        for(ListEntry entry : feed.getEntries())
        {
          System.out.println("new row");
          for(String tag : entry.getCustomElements().getTags())
          {
            System.out.println("     "+tag + ": " + entry.getCustomElements().getValue(tag));
          }
        }
      }
}                
                    //The sample code below sends email messages using Exchange Server.

//[C# Code Sample]

/ Create instance of ExchangeClient class by giving credentials
ExchangeClient client = new ExchangeClient("http://MachineName/exchange/username",
    "username", "password", "domain");

// Create instance of type MailMessage
MailMessage msg = new MailMessage();
msg.From = "sender@domain.com";
msg.To = "recipient@ domain.com ";
msg.Subject = "Sending message from exchange server";
msg.HtmlBody = "<h3>sending message from exchange server</h3>";

// Send the message
client.Send(msg);
 
//[VB.NET Code Sample]

‘Create instance of ExchangeClient class by giving credentials
Dim client As ExchangeClient = New ExchangeClient("http://MachineName/exchange/username", "username", "password", "domain")

' Create instance of type MailMessage
Dim msg As MailMessage = New MailMessage()
msg.From = "sender@domain.com"
msg.To = "recipient@ domain.com "
msg.Subject = "Sending message from exchange server"
msg.HtmlBody = "<h3>sending message from exchange server</h3>"

' Send the message
client.Send(msg)

///Send Email using Exchange Web Services

//[C# Code Sample]

// Create instance of IEWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");

// Create instance of type MailMessage
MailMessage msg = new MailMessage();
msg.From = "sender@domain.com";
msg.To = "recipient@ domain.com ";
msg.Subject = "Sending message from exchange server";
msg.HtmlBody = "<h3>sending message from exchange server</h3>";

// Send the message
client.Send(msg);
 
//[VB.NET Code Sample]

' Create instance of EWSClient class by giving credentials
Dim client As IEWSClient = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain")

' Create instance of type MailMessage
Dim msg As MailMessage = New MailMessage()
msg.From = "sender@domain.com"
msg.To = "recipient@ domain.com "
msg.Subject = "Sending message from exchange server"
msg.HtmlBody = "<h3>sending message from exchange server</h3>"

' Send the message
client.Send(msg)
                
                    //Sample Code for Adding and Retrieving Attachments from Calendar Items

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2012, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2012, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();

MailAddressCollection attendees = new MailAddressCollection();
attendees.add(new MailAddress("attendee_address@domain.com", "Attendee"));
WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);

Appointment app = new Appointment("Appointment Location", "Appointment Summary", "Appointment Description",
									startDate, endDate,
									new MailAddress("organizer_address@domain.com", "Organizer"), attendees, expected);

//Attach a file from disc to this appointment
File file = new File("OutputXLS.xls");
FileInputStream fis = new FileInputStream(file);

Attachment att = new Attachment(fis, file.getName());
app.getAttachments().add(att);
fis.close();
String savedFile = "appWithAttachments.ics";
app.save(savedFile, AppointmentSaveFormat.Ics);

Appointment app2 = Appointment.load(savedFile);
System.out.println("Total Attachments: "  + app2.getAttachments().size());
for (int i=0; i< app2.getAttachments().size();i++)
{
	att = app2.getAttachments().get(i);
	System.out.println(att.getName());

        //Save the attachment to disc
        att.save(att.getName());
}
 
                
                    private void btnRun_Click(object sender, EventArgs e)
        {
            //create PPT document
            Presentation presentation = new Presentation();

            //load PPT file from disk
            presentation.LoadFromFile(@"..\..\..\..\..\..\Data\sample2.pptx");

            //save PPT document to images
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                String fileName = String.Format("result-img-{0}.png", i);
                Image image = presentation.Slides[i].SaveAsImage();
                image.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                System.Diagnostics.Process.Start(fileName);
            }

        }                
                    import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
public class FindItemFromMap
{
public static void main(String args[])
{
Map<String,List<String>> map = new HashMap<>();
		List<String> fruits = Arrays.asList("apple","orange","banana");
		List<String> juice=   Arrays.asList("pepsi","fanta","sprite");
		map.put("fruits",fruits);
		map.put("juice", juice);
		String result = Iterables.find(Iterables.concat(map.values()), new Predicate<String>()
		{
		@Override
		public boolean apply(@Nullable String input) {
			return "banana".equals(input);
		}
	}) ;
	System.out.println("Found "+result);
}
}                
                    function prime($n){
 
      //all numbers that will be evaluated as prime       
     for($i=1;$i<=$n;$i++){     
               $counter = 0; 
              //all probability of divisible factors
              for($j=1;$j<=$i;$j++){                   
                    //$i is divisible by $j, increament the counter
                     if($i % $j==0){                       
                          $counter++;
                    }
              }          
           /*how many greens? they have to be 2 
            ( each prime number has exactly 2 (two) divisors)*/
             if($counter==2){
                 print $i." is Prime <br/>";
             }
      }
} 


prime(20);  //find the Prime for 1-20 range                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'linkedin' # gem install linkedin
require 'json'

# create an appliation then
# get your api keys at https://www.linkedin.com/secure/developer
config = {
	your_consumer_key: 		'xxxxxxxxxxxxxxxx',
	your_consumer_secret: 	'xxxxxxxxxxxxxxxx',
	oauth_user_token: 		'xxxxxxxxxxxxxxxx',
	oauth_user_secret: 		'xxxxxxxxxxxxxxxx'
}
client = LinkedIn::Client.new(
						config[:your_consumer_key], 
						config[:your_consumer_secret] 
					)

client.authorize_from_access(
		config[:oauth_user_token],
		config[:oauth_user_secret]
	)

client.add_share(
	comment: 'Good Morning', 
	content: {'submitted-url' => 'http://www.github.com/blazeeboy' }
)                
                    //The programming sample below shows how to DXF Drawings to PDF file using default settings.

 [C# Code Sample]

using Aspose.Imaging.FileFormats.Cad;
using Aspose.Imaging.ImageOptions;

namespace DxfExamples
{
    /// <summary>
    /// Represents test examples for DXF -> PDF export
    /// </summary>
    public class DxfExamples
    {
        /// <summary>
        /// Default export.
        /// </summary>
        public void DefaultExport()
        {
            // Name of the file
            string filename = "Drawing1.dxf";

            // Load an image
            using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(filename))
            {
                // Create options
                PdfOptions pdfOptions = new PdfOptions();

                // Set output file size
                pdfOptions.PageWidth = 800;
                pdfOptions.PageHeight = 600;

                // Export
                image.Save(filename + ".pdf", pdfOptions);
            }
        }
    }
}

//[VB.NET Code Sample]

Imports Aspose.Imaging.FileFormats.Cad
Imports Aspose.Imaging.ImageOptions

Namespace DxfExamples
        ''' <summary>
        ''' Represents test examples for DXF -> PDF export
        ''' </summary>
        Public Class DxfExamples
            ''' <summary>
            ''' Default export.
            ''' </summary>
            Public Sub DefaultExport()
                ' Name of the file
                Dim filename As String = "Drawing1.dxf"

                ' Load an image
                Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load(filename)
                    ' Create options
                    Dim pdfOptions As New PdfOptions()

                    ' Set output file size
                    pdfOptions.PageWidth = 800
                    pdfOptions.PageHeight = 600

                    ' Export
                    image.Save(filename & Convert.ToString(".pdf"), pdfOptions)
                End Using
            End Sub
        End Class
    End Namespace

//Setting the Image Size

//[C# Code Sample]

//The code sample below shows the auto-scaling option in use.
using Aspose.Imaging.FileFormats.Cad;
using Aspose.Imaging.ImageOptions;

namespace DxfExamples
{
    /// <summary>
    /// Represents test examples for DXF -> PDF export
    /// </summary>
    public class DxfExamples
    {
/// <summary>
        /// Export with automatical up-scaling.
        /// </summary>
        public void ExportAutoUpScale()
        {
            // Name of the file
            string filename = "Drawing2.dxf";

            // Load an image
            using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(filename))
            {
                // Create options
                PdfOptions pdfOptions = new PdfOptions();

                // Set output file size
                pdfOptions.PageWidth = 850;
                pdfOptions.PageHeight = 600;

                // Allow upscaling
                pdfOptions.ScaleMethod = ScaleType.GrowToFit;

                // Export
                image.Save(filename + "_UpScale.pdf", pdfOptions);
            }
        }
    }
}

//[VB.NET Code Sample]

Imports Aspose.Imaging.FileFormats.Cad
Imports Aspose.Imaging.ImageOptions

Namespace DxfExamples
	''' <summary>
	''' Represents test examples for DXF -> PDF export
	''' </summary>
	Public Class DxfExamples
		''' <summary>
		''' Export with automatical up-scaling.
		''' </summary>
		Public Sub ExportAutoUpScale()
			' Name of the file
			Dim filename As String = "Drawing2.dxf"

			' Load an image
			Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load(filename)
				' Create options
				Dim pdfOptions As New PdfOptions()

				' Set output file size
				pdfOptions.PageWidth = 850
				pdfOptions.PageHeight = 600

				' Allow upscaling
				pdfOptions.ScaleMethod = ScaleType.GrowToFit

				' Export
				image.Save(filename & Convert.ToString("_UpScale.pdf"), pdfOptions)
			End Using
		End Sub
	End Class
End Namespace

                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'koala' # gem install koala --no-document
# create a facebook app and get access token from here
# https://developers.facebook.com/tools/explorer
# select "user_status", "friends_status", "user_checkins" when authenticating
oauth_access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
graph = Koala::Facebook::API.new(oauth_access_token)

places = []
page = graph.get_connections('me', 'checkins')
begin
	places += page.map {|p| p['place']}
end while page = page.next_page

places.each do |place|
	unless place['location'].is_a? String
		puts "#{place['name']} lat:#{place['location']['latitude']} long:#{place['location']['longitude']}"
	else
		puts "#{place['name']} location:#{place['location']}"
	end
end