working on it ...

Filters

Explore Public Snippets

Sort by

Found 306 snippets matching: oauth2

    public by cghersi @ MailUp API DEV  206844  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 cghersi @ MailUp API DEV  113003  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 cghersi @ MailUp API DEV  84180  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  69240  7  5  0

    How to Add a recipient to a group of recipients 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 AddRecipientToGroup(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:
        int idGroup = 1;
        ConsoleRecipientItem recipient = new ConsoleRecipientItem()
        {
            Email = "testGroup@mailup.com",
            Name = "Group - New Recipient" + DateTime.Now.ToFileTimeUtc(),
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "NameGroup" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastNameGroup" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
    
        // 3) Invoke the web method:
        int result = 0;
        try
        {
            result = client.AddRecipientToGroup(idGroup, recipient);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result > 0)
            Console.WriteLine("Recipient Added!");
        else
            Console.WriteLine("An error occurred while adding the recipient.");
    }
    

    public by cghersi @ MailUp API DEV  60009  8  5  0

    How to Retrieve a group of recipients given its ID 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 GetGroupByID(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:
        int idList = 1;
        int idGroup = 1;
    
        // 3) Invoke the web method:
        ConsoleGroupItem result = null;
        try
        {
            result = client.GetGroup(idList, idGroup);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result != null)
            Console.WriteLine("Group retrieved with name:" + result.Name);
        else
            Console.WriteLine("An error occurred while retrieving the group.");
    }
    

    public by cghersi  5824  1  8  3

    How to retrieve GMail contacts via API, using OAuth2 token and not username/password credentials

    This class takes charge of the interaction with Google Contacts API, authenticating with an AccessToken authorization flow. In this way the final user should type the credentials in the Google form and not in your form. The "token" parameter of GetContacts() method is the one sent by Google to the callback url specified in the static constant "s_
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Google.Contacts;
    using Google.GData.Contacts;
    using Google.GData.Client;
    using Google.GData.Extensions;
    
    namespace Contact.Utils
    {
      /// <summary>
      /// Summary description for GmailHelper
      /// </summary>
      public class GmailHelper
      {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
        private static fastJSON.JSON jsonUtils = EntityUtils.InitJSONUtils();
    
        private static readonly string APP_NAME = "my app name";
        private static readonly string s_ClientId = "client id given by Google";
        private static readonly string s_ClientSecret = "secret given by Google;
        private static readonly string s_accessTokenUrl = "https://accounts.google.com/o/oauth2/token";
        private static readonly string s_redirUri = WebConfig.Current.PublicPath + "User/GmailCallback";
    
        #region PUBLIC API
        //////////////////////////////////////////////////////////////////////////////////////////////////////
    
        public static string GetRedirUriForContacts()
        {
          return string.Format("https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri={0}&response_type=code&client_id={1}",
            s_redirUri, s_ClientId);
        }
    
        public static List<SimpleContact> GetContacts(string token)
        {
          List<SimpleContact> results = new List<SimpleContact>();
    
          //exchange the code for a token:
          string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
            token, s_ClientId, s_ClientSecret, s_redirUri);
          string accessTokenResp = Utilities.SendHttpRequest(s_accessTokenUrl, postData, true);
          if (string.IsNullOrEmpty(accessTokenResp))
            return results;
    
          AccessTokenStruct parsedJson = null;
          try
          {
            parsedJson = jsonUtils.ToObject<AccessTokenStruct>(accessTokenResp); 
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot deserialize access token response: '{0}' due to {1}", accessTokenResp, e.Message);
            return results;
          }
          if (parsedJson == null)
            return results;
    
          //ask for contacts:
          RequestSettings settings = new RequestSettings(APP_NAME, parsedJson.access_token); 
          settings.AutoPaging = true;
          ContactsRequest cr = new ContactsRequest(settings);
          Feed<Contact> contactsFeed = cr.GetContacts();
          IEnumerable<Contact> contacts = null;
          if (contactsFeed != null)
            contacts = contactsFeed.Entries;
          if (contacts == null)
            return results;
    
          try
          {
            foreach (SimpleContact c in contacts)
            {
              if (c.PrimaryEmail == null)
                continue;
              string preferredEmail = c.PrimaryEmail.Address;
              if (string.IsNullOrEmpty(preferredEmail))
                continue;
              string[] otherEmails = null;
              if (c.Emails != null)
                otherEmails = c.Emails.Select(e => e.Address).ToArray();
              S2CContact contact = new S2CContact((c.Name == null ? "" : c.Name.FullName), 
                                                  preferredEmail, otherEmails);
              results.Add(contact);
            }
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot retrieve contacts due to {0}", e.Message);
            return results;
          }
    
          return results;
        }
    
        #endregion
        //////////////////////////////////////////////////////////////////////////////////////////////////////
      }
    
      public class AccessTokenStruct
      {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
    
        public AccessTokenStruct() { }
      }
    
      public class SimpleContact
      {
        public string PreferredEmail { get; set; }
        public string Name { get; set; }
        public string[] Emails { get; set; }
    
        public SimpleContact(string name, string preferredEmail, string[] emails = null)
        {
          Name = name;
          PreferredEmail = preferredEmail;
          if (emails == null)
            Emails = new string[] { preferredEmail };
          else
          {
            List<string> allEmails = new List<string>(emails);
            allEmails.Add(preferredEmail);
            Emails = allEmails.Distinct().ToArray();
          }
        }
    
        public override string ToString()
        {
          if (string.IsNullOrEmpty(Name))
            return PreferredEmail;
          else
            return string.Format("{0} [{1}]", Name, PreferredEmail);
        }
      }
    
    }            

    public by cghersi @ MailUp API DEV  1974  30  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 by cghersi @ MailUp API DEV  1397  30  5  0

    How to Retrieve and filter some lists of recipients 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 GetLists(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:
        string filter = "Format.Trim().Equals('html')";
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleListItem> result = null;
        try
        {
            result = client.GetLists(filter);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if ((result != null) && (result.Count > 0))
            Console.WriteLine("Retrieved Lists:" + result.Count + "; first one with name:" + result[0].Name);
        else
            Console.WriteLine("An error occurred while retrieving the lists.");
    }
    

    public by cghersi @ MailUp API DEV  1983  20  5  0

    MailUp REST API - How to authenticate with 3 leg process flow

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 3 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 MailUpC
    @using MailUp.Sdk.Base
    @using MailUp.Framework.Contracts.API.Base
    @using MailUp.Framework.Contracts.API.DataContracts.Console
    
    @{  
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Welcome to the sample client to interact with MailUp REST API";
        
        MailUpClient mailUp = Session["MailUpClient"] as MailUpClient;
        string receivedCode = Request["code"];
        string redirUri = string.Empty;
        string accessTokenRetrieval = "Your application has been granted. You are now able to consume MailUp API!";
        if (string.IsNullOrEmpty(receivedCode))
        {
            // Phase 1: the authorization flow should be started with the redirection towards MailUp login form
            redirUri = mailUp.GetLogOnUri(Request.Url.AbsoluteUri);
        }
        else
        {
            // Phase 2: the MailUp login form redirected the user back to this page, with the code to be exchanged
            // with access token to securely consume REST API:
            try
            {
                mailUp.RetrieveAccessToken(receivedCode);
                
                //invoke a sample API:
                CollectionOf<ConsoleListItem> lists = mailUp.GetLists("", "idList ASC", 1);
                if ((lists != null) && (lists.Count > 0))
                {
                    accessTokenRetrieval += " E.g. your first list is named '" + lists[0].Name + "'";
                }
            }
            catch (MailUpException ex)
            {
                accessTokenRetrieval = "Unable to access the service due to " + ex.Message;
            }
        }
    }
    <p>
        Click here to start the authorization process. <br />
        The MailUp login page will be displayed and you will be able to enter your username and password. <br />
        Then, you will be redirected back here, with a valid access token that can be used to perform all the REST calls. <br />
        <br />
        @if (string.IsNullOrEmpty(receivedCode))
        {
            <input id="authFlowBtn" type="button" value="Login" onclick="javascript:document.location='@redirUri';" />
        }
        else
        {
            <text>@accessTokenRetrieval</text>
        }
    </p>            

    public by cghersi @ MailUp API DEV  2042  19  6  0

    MailUp REST API - How to create and send an SMS 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 CreateAndSendSMS(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 Sms";
        ConsoleSmsMessageDetailItem message = new ConsoleSmsMessageDetailItem()
        {
            Content = "Test Content",
            idList = idList,
            IsUnicode = false,
            Notes = "Bunch of test notes",
            Sender = "+390123456789",
            Subject = subject
        };
        ConsoleMessageItem createMsgResult = null;
        try
        {
            createMsgResult = client.CreateSmsMessage(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:
        SmsSendToRecipientRequest request = new SmsSendToRecipientRequest()
        {
            Number = "3331234567",
            Prefix = 39,
            idMessage = createMsgResult.idMessage.Value
        };
        SmsMessageSendResponse result = null;
        try
        {
            result = client.SendSmsMessage(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