working on it ...

Filters

Explore Public Snippets

Sort by

Found 19k snippets matching: rest

    public by johansonkatherine modified May 8, 2014  219636  1  6  2

    C# Code Sample to Replace Multiple Texts inside PDF File Using Cloud API

    The following code sample shows how developers can replace multiple texts in a single API call in a PDF file using Aspose.Pdf for Cloud API in their applications. Developers can use Aspose REST API with any language: .NET, Java, PHP, Ruby, Rails, Python, jQuery and many more.
    AsposeApp.AppSID  = "77***********************************";
    AsposeApp.AppKey = "9a*******************************";
    
    //build URI
    stringstrURI = "http://api.aspose.com/v1.1/pdf/test.pdf/replaceTextList";
    
    //sign URI
    stringsignedURI = Utils.Sign(strURI);
    
    //build JSON to post
    TextReplace textReplace1 = new TextReplace();
    textReplace1.OldValue = "[!firm!]";
    textReplace1.NewValue = "Aspose";
    textReplace1.Regex = "false";
    
    //build JSON to post
    TextReplace textReplace2 = new TextReplace();
    textReplace2.OldValue = "[!client!]";
    textReplace2.NewValue = "Mark";
    textReplace2.Regex = "false";
    
    MultipleTextReplacestextReplaces = new MultipleTextReplaces();
    textReplaces.TextReplaces = new TextReplace[] { textReplace1, textReplace2 };
    stringstrJSON = JsonConvert.SerializeObject(textReplaces);
    Console.Write(strJSON);
    Utils.ProcessCommand(signedURI, "POST", strJSON);
    
    //build URI
    strURI = "http://api.aspose.com/v1.1/storage/file/test.pdf";
    
    //sign URI
    signedURI = Utils.Sign(strURI);
    
    Stream responseStream = Utils.ProcessCommand(signedURI, "GET");
    using (Stream fileStream = System.IO.File.OpenWrite(@"test.pdf"))
    {
    Utils.CopyStream(responseStream, fileStream);
    }
    responseStream.Close();
    
    //Following are required classes
    public class MultipleTextReplaces
        {
    publicTextReplace[] TextReplaces { get; set; }
        }
    public class TextReplace
        {
    publicTextReplace() { }
    
    public string OldValue { get; set; }
    public string NewValue { get; set; }
    public string Regex { get; set; }
    
        }
    

    public by cghersi @ MailUp API DEV modified Jan 20, 2015  206772  8  6  1

    MailUp REST API - How to subscribe to a particular list several contacts with the "Confirmed Optin" Procedure

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void SubcribeRecipientsWithDoubleOptin(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Subscribe recipients:
        int idList = 1;
        List<ConsoleRecipientItem> recipients = new List<ConsoleRecipientItem>();
        ConsoleRecipientItem recipient1 = new ConsoleRecipientItem()
        {
            Email = "test1@mailup.com",
            Name = "First New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3331234567",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name1_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName1_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        ConsoleRecipientItem recipient2 = new ConsoleRecipientItem()
        {
            Email = "test2@mailup.com",
            Name = "Second New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3337654321",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name2_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName2_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        recipients.Add(recipient1);
        recipients.Add(recipient2);
        int subscriptionResult = 0;
        try
        {
            subscriptionResult = client.AddRecipientsToList(idList, recipients, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 2.1) wait for the end of import task:
        if (subscriptionResult > 0)
        {
            Console.WriteLine("Recipients Import started; import ID:" + subscriptionResult);
    
            //optionally we can check the import status:
            bool completed = false;
            do
            {
                ConsoleImportStatus importStatus = client.CheckImportStatus(subscriptionResult);
                if (importStatus == null)
                {
                    Console.WriteLine("Cannot check the import status for import task #" + subscriptionResult);
                    return;
                }
                completed = importStatus.Completed;
            } while (!completed);
            Console.WriteLine("Recipients Added!");
        }
        else
        {
            Console.WriteLine("An error occurred while adding the recipients.");
            return;
        }
    
        // 3) Retrieve the sendingID of the confirmation email related to the previous task:
        int sendingID = -1;
        try
        {
            sendingID = client.GetSendingIDForImport(subscriptionResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot retrieve sending ID due to " + ex.Message);
            return;
        }
        if (sendingID <= 0)
        {
            Console.WriteLine("Cannot retrieve sending ID.");
            return;
        }
    
        // 4) Send the confirmation email:
        EmailSendingItem sendingResult = null;
        try
        {
            sendingResult = client.SendEmailMessage(sendingID);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot send email due to " + ex.Message);
            return;
        }
        if (sendingResult == null)
            Console.WriteLine("Cannot send confirmation email.");
        else
            Console.WriteLine("Confirmation email sent!");
    }
                

    public by lbottaro modified Mar 26, 2015  172467  10  6  0

    curl to send a GET HTTP request with query parameters

    Try to perform a GET HTTP to snip2code server, to list the public snippets in Channels. URL example to get: https://www.snip2code.com/Explore/InChannel?q=test&sort=0&direction=1 Options: -d: list all query parameters -G: perform GET verb
    curl -v -L -G -d "q=test&sort=0&direction=1" https://www.snip2code.com/Explore/InChannel                               

    public by christopher modified Dec 31, 2013  169609  0  4  0

    Copied from my local repo (Not pushed fully to a branch on github itself.) For preview purpose for a friend. Just a standard BlockStateUtil that is going to be used to compare block states for restoration.. This is very basic. To remove the bk...

    Copied from my local repo (Not pushed fully to a branch on github itself.) For preview purpose for a friend. Just a standard BlockStateUtil that is going to be used to compare block states for restoration.. This is very basic. To remove the bkcommonlib dependency remove the blockStatesMatch function.. The Pair is nothing but a class wit
    package com.noxpvp.core.utils;
    
    import java.util.logging.Level;
    
    import org.bukkit.block.Beacon;
    import org.bukkit.block.BlockState;
    import org.bukkit.block.BrewingStand;
    import org.bukkit.block.Chest;
    import org.bukkit.block.CommandBlock;
    import org.bukkit.block.CreatureSpawner;
    import org.bukkit.block.Dispenser;
    import org.bukkit.block.Dropper;
    import org.bukkit.block.Furnace;
    import org.bukkit.block.Hopper;
    import org.bukkit.block.Jukebox;
    import org.bukkit.block.NoteBlock;
    import org.bukkit.block.Sign;
    import org.bukkit.block.Skull;
    import org.bukkit.inventory.BeaconInventory;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.InventoryHolder;
    
    import com.bergerkiller.bukkit.common.filtering.Filter;
    import com.noxpvp.core.NoxCore;
    import com.noxpvp.core.data.Pair;
    
    public class BlockStateUtils {
    	
    	public static boolean blockStatesMatch(BlockState state1, BlockState state2, Filter<Pair<BlockState>>... filters)
    	{
    		Pair<BlockState> states = new Pair<BlockState>(state1, state2);
    		
    		for (Filter<Pair<BlockState>> filter : filters)
    			if (!filter.isFiltered(states))
    				return false;
    		return true;
    	}
    	
    	public static boolean blockStatesPerfectMatch(BlockState state1, BlockState state2)
    	{
    		if (!state1.getBlock().equals(state2.getBlock()))
    			return false;
    		
    		if (!state1.getType().equals(state2.getType()))
    			return false;
    		
    		if (state1 instanceof Chest) { // No need to check other state for instance since they both match types!
    			if (!isChestMatch((Chest)state1, (Chest)state2))
    				return false;
    		} else if (state1 instanceof Beacon) {
    			if (!isBeaconMatch((Beacon)state1, (Beacon)state2))
    				return false;
    		} else if (state1 instanceof BrewingStand) {
    			if (!isBrewingStandMatch((BrewingStand)state1, (BrewingStand)state2))
    				return false;
    //		} else if (state1 instanceof Dispenser) {
    //			if (!isInventoryHolderMatch((InventoryHolder)state1, (InventoryHolder) state2))
    //				return false;
    //		} else if (state1 instanceof Dropper) {
    //			if (!isDropperMatch((Dropper)state1, (Dropper) state2))
    //				return false;
    //		} else if (state1 instanceof Hopper) {
    //			if (!isHopperMatch((Hopper)state1, (Hopper)state2))
    //				return false;
    		} else if (state1 instanceof Furnace) {
    			if (!isFurnaceMatch((Furnace)state1, (Furnace)state2))
    				return false;
    		} else if (state1 instanceof InventoryHolder) { ///Must come after Furnace (As its also an inventory holder!)
    			if (!isInventoryHolderMatch((InventoryHolder)state1, (InventoryHolder)state2))
    				return false;
    		} else if (state1 instanceof CommandBlock) {
    			if (!isCommandBlockMatch((CommandBlock)state1, (CommandBlock)state2))
    				return false;
    		} else if (state1 instanceof CreatureSpawner) {
    			if (!isSpawnerMatch((CreatureSpawner)state1, (CreatureSpawner)state2))
    				return false;
    		} else if (state1 instanceof Jukebox) {
    			if (!isJukeboxMatch((Jukebox)state1, (Jukebox)state2))
    				return false;
    		} else if (state1 instanceof NoteBlock) {
    			if (!isNoteBlockMatch((NoteBlock)state1, (NoteBlock)state2))
    				return false;
    		} else if (state1 instanceof Sign) {
    			if (!isSignMatch((Sign)state1, (Sign)state2))
    				return false;
    		} else if (state1 instanceof Skull) {
    			if (!isSkullMatch((Skull)state1, (Skull)state2))
    				return false;
    		}
    		
    		return true;
    	}
    	
    	private static boolean isSkullMatch(Skull state1, Skull state2) {
    		if (!state1.getSkullType().equals(state2.getSkullType()))
    			return false;
    		
    		if (!state1.getRotation().equals(state2.getRotation()))
    			return false;
    		
    		if (!state1.getOwner().equals(state2.getOwner()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isSignMatch(Sign state1, Sign state2) {
    		for (int i = 0; i < 3; i++)
    			if (!state1.getLine(i).equals(state2.getLine(i)))
    				return false;
    		
    		return true;
    	}
    
    	private static boolean isNoteBlockMatch(NoteBlock state1, NoteBlock state2) {
    		if (!state1.getNote().equals(state2.getNote()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isJukeboxMatch(Jukebox state1, Jukebox state2) {
    		if (!state1.getPlaying().equals(state2.getPlaying()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isHopperMatch(Hopper state1, Hopper state2) {
    		return isInventoryHolderMatch(state1, state2);
    	}
    	
    	private static boolean isDropperMatch(Dropper state1, Dropper state2) {
    		return isInventoryHolderMatch(state1, state2);
    	}
    
    	private static boolean isFurnaceMatch(Furnace state1, Furnace state2) {
    		if (state1.getBurnTime() != state2.getBurnTime())
    			return false;
    		if (state1.getCookTime() != state2.getCookTime())
    			return false;
    		
    		return isInventoryHolderMatch(state1, state2);
    	}
    
    	private static boolean isInventoryHolderMatch(InventoryHolder state1, InventoryHolder state2) {
    		Inventory inv1 = state1.getInventory(), inv2 = state2.getInventory();
    		
    		if (inv1.getSize() != inv2.getSize())
    			return false;
    		
    		if (!inv1.getName().equals(inv2.getName()))
    			return false;
    		
    		if (!inv1.getTitle().equals(inv2.getTitle()))
    			return false;
    		
    		for (int i = 0; i < inv1.getSize(); i++)
    			if (!inv1.getItem(i).equals(inv2.getItem(i)))
    				return false;
    		
    		return true;
    	}
    
    	private static boolean isSpawnerMatch(CreatureSpawner state1, CreatureSpawner state2) {
    		if (!state1.getSpawnedType().equals(state2.getSpawnedType()))
    			return false;
    		
    		if (!state1.getCreatureTypeName().equals(state2.getCreatureTypeName()))
    			return false;
    		
    		if (state1.getDelay() != state2.getDelay())
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isCommandBlockMatch(CommandBlock state1, CommandBlock state2) {
    		if (!state1.getName().equals(state2.getName()))
    			return false;
    		
    		if (!state1.getCommand().equals(state2.getCommand()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isBrewingStandMatch(BrewingStand stand1, BrewingStand stand2)
    	{
    		//TODO: Determine if we wanna match items brewing and such
    		return true;
    	}
    	
    	private static boolean isBeaconMatch(Beacon beacon1, Beacon beacon2)
    	{
    		Inventory rInv1 = beacon1.getInventory(), rInv2 = beacon2.getInventory();
    		
    		try {
    			BeaconInventory inv1 = (BeaconInventory)rInv1, inv2 = (BeaconInventory)rInv2;
    			
    			if (!inv1.getItem().equals(inv2.getItem()))
    				return false;
    				
    		} catch (ClassCastException e) {
    			NoxCore.getInstance().log(Level.SEVERE, "Bukkit is not using their own api for beacons! SUBMIT BUT REPORT TO THEM! \n Defaulting to Plain inventory Code!");
    			return isInventoryHolderMatch(beacon1, beacon2);
    		}
    		return true;
    	}
    	
    	private static boolean isChestMatch(Chest state1, Chest state2)
    	{
    		return isInventoryHolderMatch(state1, state2);
    	}
    }
    
    
    

    public by cghersi @ MailUp API DEV modified Sep 23, 2014  84130  21  6  0

    Base class to setup the secure communication towards MailUp REST API

    This is how to setup a secure connection towards MailUP RESTful API. This base class can be extended with methods that directly call those web methods
    public class BaseAPIInvoker
    { 
        #region App Credentials
    
        protected static String ClientId = "take from your console";
        protected static String ClientSecret = "take from your console"; 
        protected static String UserName = "mxxx@number"; 
    	protected static String Password = "pswsupersecret"; 
        protected static String bypassToken = String.Empty;
    
        #endregion
    
        #region Endpoints
    
        protected static String OAuthAuthorization = "https://services.mailup.com/Authorization/OAuth/Authorization";
        protected static String OAuthToken = "https://services.mailup.com/Authorization/OAuth/Token";
        protected static String BaseEndpoint = "https://services.mailup.com/API/v1/Rest/ConsoleService.svc";
    
        #endregion
    
        public OAuth2Client client;
    
        public BaseAPIInvoker()
        {
            client = new OAuth2Client(OAuthToken, OAuthAuthorization);
            
            client.ClientId = ClientId;
            client.ClientSecret = ClientSecret;
            client.Username = UserName;
            client.Password = Password;
    
            client.ForceToken = bypassToken;
            
            client.GetToken();
        }
    }

    public by cghersi @ MailUp API DEV modified Nov 19, 2014  112946  11  5  0

    How to Retrieve your personal information with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetPersonalDataFields(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        //nothing to do here...
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleDynamicFieldItem> result = null;
        try
        {
            result = client.GetPersonalDataFields();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
    
        if (result != null)
            Console.WriteLine("Personal Data Fields Retrieved: " + result.Count);
        else
            Console.WriteLine("Cannot retrieve Personal Data Fields.");
    }
    

    public by lbottaro modified May 28, 2015  2526  8  6  0

    How to use curl to send HTTP POST using file

    Using curl you can send POST request, putting the content of your request in a separated file. Usage options: -d: where some contents to post --header : specify the content type of your request (eg json/xml/text)
    For a RESTful HTTP POST containing XML:
    
    curl -X POST -d @filename.txt http://example.com/path/to/resource --header "Content-Type:text/xml"
    or for JSON, use this:
    
    curl -X POST -d @filename.txt http://example.com/path/to/resource --header "Content-Type:application/json"
    This will read the contents of the file named filename.txt and send it as the post request.

    public by azazqadir modified Oct 9, 2017  314  0  3  0

    Laravel REST API Authentication with Passport: https://www.cloudways.com/blog/rest-api-laravel-passport-authentication/

    Laravel REST API Authentication with Passport: https://www.cloudways.com/blog/rest-api-laravel-passport-authentication/: auth.php
    'guards' => [
    
       'web' => [
    
           'driver' => 'session',
    
           'provider' => 'users',
    
       ],
    
    
    
       'api' => [
    
           'driver' => 'passport',
    
           'provider' => 'users',
    
       ],
    
    ],
    
    

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  1675  46  5  0

    MailUp REST API - How to send a transactional email message

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. Explore the MessageDTO object in order to understand how you can customize the message you want to send.
    public static void SendMessage()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) prepare the input:
      MessageDTO msg = new MessageDTO()
      {
        Html = new HtmlDTO()
        {
          Body = "<div>Hello Mr. [firstname][lastname] !!!</div><br><img width='600' height='397' src='cid:img001'>",
          BodyTag = "<body>"
        },
        Text = "Hello world!!!",
        Subject = "Hello friend!",
        From = new EmailAddressDTO() { Name = "Test User", Email = "test@mailup.it" },
        To = new List<EmailAddressDTO>() { new EmailAddressDTO() { Name = "Massimo", Email = "info@mailup.it" } },
        Cc = new List<EmailAddressDTO>(),
        Bcc = new List<EmailAddressDTO>(),
        ReplyTo = null,
        CharSet = "utf-8",
        ExtendedHeaders = null,
        Attachments = null,
        EmbeddedImages = new List<MessagePartDTO>() {
          new MessagePartDTO() {
            Filename = "Image.jpg",
            ContentId = "img001",
            Body = new byte[] { 0x01, 0x02, 0x03, 0x04 }
          }
        },
        XSmtpAPI = new XSmtpAPIDTO()
        {
          CampaignName = "Test Campaign",
          CampaignCode = "1001",
          Header = null,
          Footer = null,
          ClickTracking = null,
          ViewTracking = null,
          Priority = null,
          Schedule = null,
          DynamicFields = new List<NameValueDTO>() {
            new NameValueDTO() { N = "firstname", V = "Mario"},
            new NameValueDTO() { N = "lastname", V = "Rossi"}
          },
          CampaignReport = null,
          SkipDynamicFields = null
        },
        User = new SmtpUserDTO() { Username = smtpplus_username, Secret = smtpplus_password }
      };
    
      // 4) Invoke the web method:
      SendResponseDTO result = null;
      try
      {
        result = client.SendMessage(msg);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 5) Print results:
      if (result != null)
        Console.WriteLine("Result of sending task:" + result.Message);
      else
        Console.WriteLine("An error occurred while sending message.");
    }
    						

    public by cghersi @ MailUp API DEV modified Jan 15, 2015  1865  27  6  1

    MailUp REST API - How to create and send an email to a specific recipient.

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void CreateAndSendEmail(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Create the message:
        int idList = 1;
        string subject = "Test Creation Email";
        ConsoleMessageDetailItem message = new ConsoleMessageDetailItem()
        {
            Content = "Test Content",
            Embed = false,
            idList = idList,
            IsConfirmation = false,
            Notes = "Bunch of test notes",
            Subject = subject,
            TrackingInfo = new ConsoleEmailTrackingInfo() { Enabled = true, Protocols = new List<string>() { "http" } }
        };
        ConsoleMessageItem createMsgResult = null;
        try
        {
            createMsgResult = client.CreateMessage(idList, message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unable to create the message due to " + ex.Message);
            return;
        }
        if (createMsgResult == null)
        {
            Console.WriteLine("Unable to create the message");
            return;
        }
    
        // 3) Send the just created message:
        EmailSendToRecipientRequest request = new EmailSendToRecipientRequest()
        {
            Email = "recipient@mailup.com",
            idMessage = createMsgResult.idMessage.Value
        };
        MailMessageSendResponse result = null;
        try
        {
            result = client.SendEmailMessage(request);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result != null)
            Console.WriteLine("Message sent to " + result.Sent + " recipient(s).");
        else
            Console.WriteLine("An error occurred while sending the message.");
    }
    
    • Public Snippets
    • Channels Snippets