Tuesday 28 March 2017

Mail send in C#

=============================================

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Web;

namespace ARC.Utility
{
    public class MailSend
    {
        static string displayName = System.Configuration.ConfigurationManager.AppSettings["DisplayName"];

        #region send mail without attchment
        /// <summary> send mail without attchment
        /// <para>EmailMessageID</para> pass to emailMessage id
        /// <para>MailSubject</para> pass mail subject name
        /// <para>MailBody</para> pass Mail decription
        /// <para>cc</para> pass cc mail id
        /// <para>bc</para> pass bc mail id
        /// <para>FromMail</para> pass Network Credential from emailMessage id (user name)
        /// <para>password</para> pass Network Credential Password (user password)
        /// <para>host</para> pass Network Credential host for send mailMessage
        /// <para>port</para> pass Network Credential port for send mailMessage
        /// <DevelopedBy>Neelkamal bansal</DevelopedBy>
        /// </summary>
        public static void SendMail(string emailMessageId, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port)
        {
            try
            {
                string username = Convert.ToString(ConfigurationManager.AppSettings["Username"]);
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(emailMessageId);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.IsBodyHtml = true;
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
                mailMessage.Subject = mailMessageSubject;                          
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.Body = mailMessageBody;
         

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(username, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void ForgotPassSendMail(string emailMessageId, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port)
        {
            try
            {
                string username = Convert.ToString(ConfigurationManager.AppSettings["FUsername"]);
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(emailMessageId);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.Subject = mailMessageSubject;
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.Body = mailMessageBody;
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(username, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region send mail with single attchment
        /// <summary> send mailMessage with single attchment
        /// <para>EmailMessageID</para> pass to emailMessage id
        /// <para>MailSubject</para> pass mailMessage subject name
        /// <para>MailBody</para> pass Mail decription
        /// <para>cc</para> pass cc mailMessage id
        /// <para>bc</para> pass bc mailMessage id
        /// <para>FromMail</para> pass Network Credential from emailMessage id (user name)
        /// <para>password</para> pass Network Credential Password (user password)
        /// <para>host</para> pass Network Credential host for send mailMessage
        /// <para>port</para> pass Network Credential port for send mailMessage
        /// <para>attachmentfile</para> pass attchment (ex- doc, image, pdf and any other)
        /// <DevelopedBy>Neelkamal bansal</DevelopedBy>
        /// </summary>
        public static void SendMail(string emailMessageId, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port, byte[] attachmentFile, string filename)
        {
            try
            {
                MailMessage mailMessage = new MailMessage();
                string username = Convert.ToString(ConfigurationManager.AppSettings["Username"]);
                mailMessage.To.Add(emailMessageId);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
                mailMessage.Subject = mailMessageSubject;
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.Body = mailMessageBody;

                // Attachment attachment = new Attachment(attachmentFile, MediaTypeNames.Application.Octet);
                Attachment attachment = new Attachment(new MemoryStream(attachmentFile), filename);
                mailMessage.Attachments.Add(attachment);
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
              //  smtpClient.ServicePoint.MaxIdleTime = 1;
                smtpClient.Credentials = new NetworkCredential(username, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region send mail with multiple attchment
        /// <summary> send mailMessage with multiple attchment
        /// <para>EmailMessageID</para> pass to emailMessage id
        /// <para>MailSubject</para> pass mailMessage subject name
        /// <para>MailBody</para> pass Mail decription
        /// <para>cc</para> pass cc mailMessage id
        /// <para>bc</para> pass bc mailMessage id
        /// <para>FromMail</para> pass Network Credential from emailMessage id (user name)
        /// <para>password</para> pass Network Credential Password (user password)
        /// <para>host</para> pass Network Credential host for send mailMessage
        /// <para>port</para> pass Network Credential port for send mailMessage
        /// <para>attachmentfile</para> pass multiple attchment in array (ex- doc, image, pdf and any other)
        /// <DevelopedBy>Neelkamal bansal</DevelopedBy>
        /// </summary>
        public static void SendMail(string emailMessageIDd, string mailMessageSubject, string mailMessageBody, string cC, string bC, string fromMail, string password, string host, int port, string[] attachmentFile)
        {
            try
            {
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(emailMessageIDd);

                if (!string.IsNullOrEmpty(cC))
                {
                    mailMessage.CC.Add(cC);
                }

                if (!string.IsNullOrEmpty(bC))
                {
                    mailMessage.Bcc.Add(bC);
                }

                mailMessage.From = new MailAddress(fromMail, displayName);
                mailMessage.Subject = mailMessageSubject;
                mailMessage.IsBodyHtml = true;
                mailMessage.Body = mailMessageBody;

                if (attachmentFile.Length > 0)
                {
                    for (int i = 0; i < attachmentFile.Length; i++)
                    {
                        Attachment attachment = new Attachment(attachmentFile[i], MediaTypeNames.Application.Octet);
                        ContentDisposition disposition = attachment.ContentDisposition;
                        disposition.CreationDate = File.GetCreationTime(attachmentFile[i]);
                        disposition.ModificationDate = File.GetLastWriteTime(attachmentFile[i]);
                        disposition.ReadDate = File.GetLastAccessTime(attachmentFile[i]);
                        disposition.FileName = Path.GetFileName(attachmentFile[i]);
                        disposition.Size = new FileInfo(attachmentFile[i]).Length;
                        disposition.DispositionType = DispositionTypeNames.Attachment;
                        mailMessage.Attachments.Add(attachment);
                    }
                }

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Port = port;
                smtpClient.Host = host;
                smtpClient.EnableSsl = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(fromMail, password);
                smtpClient.Send(mailMessage);
                smtpClient.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        public static void sendmailnew(string frommail ,string tomail)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(frommail, "Gaurav");
            mailMessage.To.Add(tomail);
            mailMessage.Subject = "This is test mail.";
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = "This is test mail.";

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Send(mailMessage);
            smtpClient.Dispose();
        }
    }
}

=====================================

Webconfig
==================================

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="mail.seologistics.com" enableSsl="false" port="25" userName="test_flexsin@seologistics.com" password="Ybv0B'mJKLIU*%$"/>
      </smtp>
    </mailSettings>
  </system.net>


key:

 <add key="DisplayName" value="تحدي القراءة العربي"/>
    <add key="EmailUname" value="test_flexsin@seologistics.com"/>
    <add key="Username" value="test_flexsin@seologistics.com"/>
    <add key="EmailPassword" value="Ybv0B'mJKLIU*%$"/>
    <add key="Host" value="mail.seologistics.com"/>
    <add key="Port" value="25"/>
    <add key="CC" value=""/>
    <add key="BC" value="neelkamal_bansal@seologistics.com"/>
    <add key="FDisplayName" value="Arab Reading Challenge"/>
    <add key="FEmailUname" value="test_flexsin@seologistics.com"/>
    <add key="FUsername" value="test_flexsin@seologistics.com"/>
    <add key="FEmailPassword" value="Ybv0B'mJKLIU*%$"/>
    <add key="FHost" value="mail.seologistics.com"/>
    <add key="FPort" value="25"/>
    <add key="FCC" value=""/>
    <add key="FBC" value="avdhesh_kumar12@seologistics.com"/>

Application registered by Social media Login.


// <copyright file="CustomAuth.cs" company="Flexsin Technologies">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author>Sr. Programmer Sandeep Singh Tomar</author>
// <date>02/25/2016 11:40:58 AM </date>
//<dependency>It have the dependency on Newtonsoft for the serialization and deserializarion of data </dependency>
// <summary>Custom Auth class this class is the entry point for login which interacts all the classes(Facebook/Twitter/LinkedIn/Google+) directly</summary>

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Libraries
{
    public class CustomAuth
    {
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string AccessToken { get; set; }
        public string CallbackUrl { get; set; }
        public enum eProvider { GooglePlus, Facebook, LinkedIn, Twitter };
        public readonly string AuthState = "";
        public eProvider Provider { get; set; }
        public ProfileData data { get; set; }

        #region EncryptionKey
        public string EncryptionKey { get { return "Flexsinsa@!@#"; } }
        #endregion
        // Note:- All the callback url will containt the query string Provider={Providername} where Providername is GooglePlus/Facebook/LinkedIn/Twitter
        #region Google plus Client Id and Client secret
        private readonly string GooglePlusClientId = ConfigurationManager.AppSettings["GooglePlusClientId"];
        private readonly string GooglePlusClientSecret = ConfigurationManager.AppSettings["GooglePlusClientSecret"];
        private readonly string GooglePlusCallbackUrl = ConfigurationManager.AppSettings["GooglePlusCallbackUrl"];
        #endregion

        #region Facebook Client Id and Client secret
        private readonly string FacebookClientId = ConfigurationManager.AppSettings["FacebookClientId"];
        private readonly string FacebookClientSecret = ConfigurationManager.AppSettings["FacebookClientSecret"];
        private readonly string FacebookCallbackUrl = ConfigurationManager.AppSettings["FacebookCallbackUrl"];
        #endregion

        #region LinkedIn Client Id and Client secret
        private readonly string LinkedInClientId = ConfigurationManager.AppSettings["LinkedInClientId"];
        private readonly string LinkedInClientSecret = ConfigurationManager.AppSettings["LinkedInClientSecret"];
        private readonly string LinkedInCallbackUrl = ConfigurationManager.AppSettings["LinkedInCallbackUrl"];
        #endregion

        #region Twitter Client Id and Client secret
        private readonly string TwitterClientId = ConfigurationManager.AppSettings["TwitterClientId"];
        private readonly string TwitterClientSecret = ConfigurationManager.AppSettings["TwitterClientSecret"];
        private readonly string TwitterCallbackUrl = ConfigurationManager.AppSettings["TwitterCallbackUrl"];
        #endregion

        public CustomAuth()
        {

        }
        public CustomAuth(eProvider provider)
        {
            this.Provider = provider;
            Initialize();
            // Generate the encrypted state to prevent CSRF Attack
            this.AuthState = CalculateSHASIGN();
            if (string.IsNullOrEmpty(ClientId) || string.IsNullOrEmpty(ClientSecret))
            {
                throw new Exception("ClientId and ClientSecret can not be null or empty");
            }
        }
        private void Initialize()
        {
            switch (Provider)
            {
                case eProvider.Facebook:
                    {
                        ClientId = FacebookClientId;
                        ClientSecret = FacebookClientSecret;
                        CallbackUrl = FacebookCallbackUrl;
                        break;
                    }
                case eProvider.GooglePlus:
                    {
                        ClientId = GooglePlusClientId;
                        ClientSecret = GooglePlusClientSecret;
                        CallbackUrl = GooglePlusCallbackUrl;
                        break;
                    }
                case eProvider.LinkedIn:
                    {
                        ClientId = LinkedInClientId;
                        ClientSecret = LinkedInClientSecret;
                        CallbackUrl = LinkedInCallbackUrl;
                        break;
                    }
                case eProvider.Twitter:
                    {
                        ClientId = TwitterClientId;
                        ClientSecret = TwitterClientSecret;
                        CallbackUrl = TwitterCallbackUrl;
                        break;
                    }
                default:
                    {

                        break;
                    }

            }
        }
        public Uri GetAuthenticateUrl()
        {
            Uri url = null;
            switch (Provider)
            {
                case eProvider.Facebook:
                    {
                        url = oAuthFacebook.GetAutenticationURI(this.ClientId, this.CallbackUrl, this.AuthState);
                        break;
                    }
                case eProvider.GooglePlus:
                    {
                        url = oAuthGoogle.GetAutenticationURI(this.ClientId, this.CallbackUrl,this.AuthState);
                        break;
                    }
                case eProvider.LinkedIn:
                    {
                        url = oAuthLinkedIn.GetAutenticationURI(this.ClientId, this.CallbackUrl, this.AuthState);
                        break;
                    }
                case eProvider.Twitter:
                    {
                        oAuthTwitter TwitterAuth = new oAuthTwitter(this.ClientId, this.ClientSecret, this.CallbackUrl);
                        url = new Uri(TwitterAuth.AuthorizationLinkGet());
                        break;
                    }
                default:
                    {
                        break;
                    }
            }

            //CustomAuth obj = new CustomAuth(eProvider.Facebook, "callback");
            return url;
        }
        public ProfileData GetData(HttpRequestBase request)
        {
            // provider must be match with enum eProvider
            string ProviderName = request.QueryString["Provider"];
            ProfileData data = new ProfileData();
            string jsondata = "";
            CustomAuth.eProvider provider = (CustomAuth.eProvider)Enum.Parse(typeof(CustomAuth.eProvider), ProviderName, true);
            switch (provider)
            {
                case eProvider.Facebook:
                    {
                        #region Facebook handling
                        string authCode = request.QueryString["code"];
                        string state = request.QueryString["state"];
                        if (string.Compare(state, this.AuthState, false) == 0)
                        {
                            var access = oAuthFacebook.Exchange(authCode, this.ClientId, this.ClientSecret, this.CallbackUrl);
                            this.AccessToken = access.Access_token;
                            jsondata = oAuthFacebook.GetFinalJson(access.Access_token);
                        }
                        else
                        {
                            throw new Exception("tempered request received");
                        }
                        #endregion
                        break;
                    }
                case eProvider.GooglePlus:
                    {
                        #region google plus handling
                        string authCode = request.QueryString["code"];
                         string state = request.QueryString["state"];
                         if (string.Compare(state, this.AuthState, false) == 0)
                         {
                             var access = oAuthGoogle.Exchange(authCode, this.ClientId, this.ClientSecret, this.CallbackUrl);
                             this.AccessToken = access.Access_token;
                             jsondata = oAuthGoogle.GetFinalJson(access.Access_token);
                         }
                         else
                         {
                             throw new Exception("tempered request received");
                         }
                        #endregion
                        break;
                    }
                case eProvider.LinkedIn:
                    {
                        #region LinkedIn handling
                        string authCode = request.QueryString["code"];
                        string state = request.QueryString["state"];
                        if (string.Compare(state, this.AuthState,false) == 0)
                        {
                            var access = oAuthLinkedIn.Exchange(authCode, this.ClientId, this.ClientSecret, this.CallbackUrl);
                            this.AccessToken = access.Access_token;
                            jsondata = oAuthLinkedIn.GetFinalJson(access.Access_token);
                        }
                        else
                        {
                            throw new Exception("tempered request received");
                        }
                        #endregion
                        break;
                    }
                case eProvider.Twitter:
                    {
                        #region Twitter handling
                        if (request["oauth_token"] != null & request["oauth_verifier"] != null)
                        {
                            var TwitteroAuth = new oAuthTwitter(this.ClientId, this.ClientSecret, this.CallbackUrl);
                            TwitteroAuth.AccessTokenGet(request["oauth_token"], request["oauth_verifier"]);
                            var url = "https://api.twitter.com/1.1/account/verify_credentials.json";
                            jsondata = TwitteroAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty);
                        }
                        #endregion
                        break;
                    }
                default:
                    {
                        throw new Exception("Provider did not match");
                    }
            }
            if (!string.IsNullOrEmpty(jsondata))
            {
                data = this.FilterData(jsondata);
            }

            return data;
        }

        public ProfileData FilterData(string Jsondata)
        {
            ProfileData data = new ProfileData();
            var temp = (JObject)JsonConvert.DeserializeObject(Jsondata);
            switch (this.Provider)
            {
                case eProvider.Facebook:
                    {
                        data.Id = temp.Value<string>("id");
                        data.Gender = temp.Value<string>("gender");
                        data.Email = temp.Value<string>("email");
                        data.Name = temp.Value<string>("name");
                        data.FirstName = temp.Value<string>("first_name");
                        data.LastName = temp.Value<string>("last_name");
                        data.ProfileLink = temp.Value<string>("link");
                        data.Provider = this.Provider.ToString();
                        data.ImageUrl = temp.Value<JObject>("picture").Value<JObject>("data").Value<string>("url");
                        data.Success = true;
                        break;
                    }
                case eProvider.GooglePlus:
                    {
                        data.Id = temp.Value<string>("id");
                        data.Gender = temp.Value<string>("gender");
                        data.Email = temp.Value<string>("email");// email would be available after get the permission from twitter
                        data.Name = temp.Value<string>("name");
                        data.FirstName = temp.Value<string>("given_name");
                        data.LastName = temp.Value<string>("family_name");
                        data.ProfileLink = temp.Value<string>("link");
                        data.Provider = this.Provider.ToString();
                        data.ImageUrl = temp.Value<string>("picture");
                        data.Success = true;
                        break;
                    }
                case eProvider.LinkedIn:
                    {
                        data.Id = temp.Value<string>("id");
                        data.Gender = temp.Value<string>("gender");
                        data.Email = temp.Value<string>("emailAddress");// email would be available after get the permission from twitter
                        data.Name = temp.Value<string>("formattedName");
                        data.FirstName = temp.Value<string>("firstName");
                        data.LastName = temp.Value<string>("lastName");
                        data.ProfileLink = (temp.Value<JObject>("siteStandardProfileRequest")).Value<string>("url");
                        data.Provider = this.Provider.ToString();
                        data.ImageUrl = temp.Value<string>("pictureUrl");
                        data.Success = true;
                        break;
                    }
                case eProvider.Twitter:
                    {
                        data.Id = temp.Value<string>("id");
                        data.Gender = temp.Value<string>("gender");
                        // for email twitter account needs special permissions
                        data.Email = temp.Value<string>("email");
                        data.Name = temp.Value<string>("name");
                        data.FirstName = temp.Value<string>("name");
                        data.ProfileLink = temp.Value<string>("url");
                        data.Provider = this.Provider.ToString();
                        data.ImageUrl = temp.Value<string>("profile_image_url");
                        data.Success = true;
                        break;
                    }
                default:
                    {
                        break;
                    }

            }
            return data;

        }

        #region Calculate Hash
        public static string Hash(string input)
        {
            using (SHA1Managed sha1 = new SHA1Managed())
            {
                var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
                var sb = new StringBuilder(hash.Length * 2);

                foreach (byte b in hash)
                {
                    // can be "x2" if you want lowercase
                    sb.Append(b.ToString("X2"));
                }

                return sb.ToString();
            }
        }
        #endregion

        #region Calculate SHASIGN To prevent the CSRF Attack
        public string CalculateSHASIGN()
        {
            return Hash(this.ClientId + "=" + this.ClientSecret + "=" + this.CallbackUrl + "=" + this.Provider + "=" + this.EncryptionKey + "=" + DateTime.Now.ToString("dd-MM-yyyy hh tt"));
        }
        #endregion
    }

    public class ProfileData
    {
        public bool Success { get; set; }
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Name { get; set; }
        public string Provider { get; set; }
        public string Email { get; set; }
        public string ImageUrl { get; set; }
        public string Gender { get; set; }
        public string ProfileLink { get; set; }
        public ProfileData()
        {
            Success = false;
        }
    }
}

=============================================


// <copyright file="Facebook.cs" company="Flexsin Technologies">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author>Sr. Programmer Sandeep Singh Tomar</author>
// <date>02/25/2016 11:40:58 AM </date>
// <summary>Facebook class</summary>

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Libraries
{
    public class oAuthFacebook
    {
        private string access_token;
        public string Access_token
        {
            get
            {
                // Access token lasts an hour if its expired we get a new one.
                if (DateTime.Now.Subtract(created).Hours > 1)
                {
                    refreshToken();
                }
                return access_token;
            }
            set { access_token = value; }
        }
        public string refresh_token { get; set; }
        private string _clientId;
        private string _secret;
        public string clientId
        {
            get { return _clientId; }
            set { _clientId = value; }
        }
        public string secret
        {

            get { return _secret; }
            set { _secret = value; }

        }
        public string expires_in { get; set; }

        public DateTime created { get; set; }

        public oAuthFacebook(string ClientId, string ClientSecret)
        {
            this.clientId = ClientId;
            this.secret = ClientSecret;
        }
        ///

        /// Parse the json response
        /// //  "{\n  \"access_token\" : \"ya29.kwFUj-la2lATSkrqFlJXBqQjCIZiTg51GYpKt8Me8AJO5JWf0Sx6-0ZWmTpxJjrBrxNS_JzVw969LA\",\n  \"token_type\" : \"Bearer\",\n  \"expires_in\" : 3600,\n  \"refresh_token\" : \"1/ejoPJIyBAhPHRXQ7pHLxJX2VfDBRz29hqS_i5DuC1cQ\"\n}"
        ///

        ///
        ///
        public static oAuthFacebook get(string response)
        {
            oAuthFacebook result = JsonConvert.DeserializeObject<oAuthFacebook>(response);
            result.created = DateTime.Now; // DateTime.Now.Add(new TimeSpan(-2, 0, 0)); //For testing force refresh.
            return result;
        }
        public void refreshToken()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
            string postData = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token", this.clientId, this.secret, this.refresh_token);
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            var refreshResponse = oAuthFacebook.get(responseString);
            this.access_token = refreshResponse.access_token;
            this.created = DateTime.Now;
        }

        public static oAuthFacebook Exchange(string authCode, string clientid, string secret, string redirectURI)
        {

            var request = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/v2.3/oauth/access_token?");

            string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", authCode, clientid, secret, redirectURI);
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            var x = oAuthFacebook.get(responseString);

            x.clientId = clientid;
            x.secret = secret;


            return x;

        }
        public static Uri GetAutenticationURI(string clientId, string redirectUri, string state)
        {
            string scopes = "email,public_profile";

            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = "urn:ietf:wg:oauth:2.0:oob";
            }
            string oauth = string.Format("https://www.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&scope={2}&response_type=code&state={3}", clientId, redirectUri, scopes, state);
            return new Uri(oauth);
        }

        public static string GetFinalJson(string Token)
        {
            string fields = "id,name,email,birthday,age_range,first_name,last_name,gender,link,picture";
            String URI = string.Format("https://graph.facebook.com/v2.5/me?access_token={0}&fields={1}", Token,fields);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
            request.Method = "GET";
            HttpWebResponse hwrWebResponse = (HttpWebResponse)request.GetResponse();
            StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());

            //and read the response
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();
            return responseData;
        }

    }
}

=================================================


// <copyright file="Google.cs" company="Flexsin Technologies">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author>Sr. Programmer Sandeep Singh Tomar</author>
// <date>02/25/2016 11:40:58 AM </date>
// <summary>Google class</summary>

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Libraries
{
    public class oAuthGoogle
    {
        private string access_token;
        public string Access_token
        {
            get
            {
                // Access token lasts an hour if its expired we get a new one.
                if (DateTime.Now.Subtract(created).Hours > 1)
                {
                    refreshToken();
                }
                return access_token;
            }
            set { access_token = value; }
        }
        public string refresh_token { get; set; }
        private string _clientId;
        private string _secret;
        public string clientId
        {
            get { return _clientId; }
            set { _clientId = value; }
        }
        public string secret
        {

            get { return _secret; }
            set { _secret = value; }

        }
        public string expires_in { get; set; }

        public DateTime created { get; set; }

        public oAuthGoogle(string ClientId, string ClientSecret)
        {
            this.clientId = ClientId;
            this.secret = ClientSecret;
        }
        ///

        /// Parse the json response
        /// //  "{\n  \"access_token\" : \"ya29.kwFUj-la2lATSkrqFlJXBqQjCIZiTg51GYpKt8Me8AJO5JWf0Sx6-0ZWmTpxJjrBrxNS_JzVw969LA\",\n  \"token_type\" : \"Bearer\",\n  \"expires_in\" : 3600,\n  \"refresh_token\" : \"1/ejoPJIyBAhPHRXQ7pHLxJX2VfDBRz29hqS_i5DuC1cQ\"\n}"
        ///

        ///
        ///
        public static oAuthGoogle get(string response)
        {
            oAuthGoogle result = JsonConvert.DeserializeObject<oAuthGoogle>(response);
            result.created = DateTime.Now; // DateTime.Now.Add(new TimeSpan(-2, 0, 0)); //For testing force refresh.
            return result;
        }
        public void refreshToken()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
            string postData = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token", this.clientId, this.secret, this.refresh_token);
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            var refreshResponse = oAuthGoogle.get(responseString);
            this.access_token = refreshResponse.access_token;
            this.created = DateTime.Now;
        }

        public static oAuthGoogle Exchange(string authCode, string clientid, string secret, string redirectURI)
        {

            var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");

            string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", authCode, clientid, secret, redirectURI);
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            var x = oAuthGoogle.get(responseString);

            x.clientId = clientid;
            x.secret = secret;


            return x;

        }
        public static Uri GetAutenticationURI(string clientId, string redirectUri, string state)
        {
            string scopes = "https://www.googleapis.com/auth/plus.login email";

            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = "urn:ietf:wg:oauth:2.0:oob";
            }
            string oauth = string.Format("https://accounts.google.com/o/oauth2/auth?client_id={0}&redirect_uri={1}&scope={2}&response_type=code&state={3}", clientId, redirectUri, scopes, state);
            return new Uri(oauth);
        }

        public static string GetFinalJson(string Token)
        {
            String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Token;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
            request.Method = "GET";
            HttpWebResponse hwrWebResponse = (HttpWebResponse)request.GetResponse();
            StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());

            //and read the response
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();
            return responseData;
        }

    }
}



=========================================

// <copyright file="LinkedIn.cs" company="Flexsin Technologies">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author>Sr. Programmer Sandeep Singh Tomar</author>
// <date>02/25/2016 11:40:58 AM </date>
// <summary>LinkedIn class</summary>

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
namespace Libraries
{
    public class oAuthLinkedIn
    {
        private string access_token;
        public string Access_token
        {
            get
            {
                // Access token lasts an hour if its expired we get a new one.
                if (DateTime.Now.Subtract(created).Hours > 1)
                {
                    refreshToken();
                }
                return access_token;
            }
            set { access_token = value; }
        }
        public string refresh_token { get; set; }
        private string _clientId;
        private string _secret;
        public string clientId
        {
            get { return _clientId; }
            set { _clientId = value; }
        }
        public string secret
        {

            get { return _secret; }
            set { _secret = value; }

        }
        public string expires_in { get; set; }

        public DateTime created { get; set; }

        public oAuthLinkedIn(string ClientId, string ClientSecret)
        {
            this.clientId = ClientId;
            this.secret = ClientSecret;
        }
        ///

        /// Parse the json response
        /// //  "{\n  \"access_token\" : \"ya29.kwFUj-la2lATSkrqFlJXBqQjCIZiTg51GYpKt8Me8AJO5JWf0Sx6-0ZWmTpxJjrBrxNS_JzVw969LA\",\n  \"token_type\" : \"Bearer\",\n  \"expires_in\" : 3600,\n  \"refresh_token\" : \"1/ejoPJIyBAhPHRXQ7pHLxJX2VfDBRz29hqS_i5DuC1cQ\"\n}"
        ///

        ///
        ///
        public static oAuthLinkedIn get(string response)
        {
            oAuthLinkedIn result = JsonConvert.DeserializeObject<oAuthLinkedIn>(response);
            result.created = DateTime.Now;   // DateTime.Now.Add(new TimeSpan(-2, 0, 0)); //For testing force refresh.
            return result;
        }
        public void refreshToken()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://www.linkedin.com/uas/oauth2/accessToken");
            string postData = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token", this.clientId, this.secret, this.refresh_token);
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            var refreshResponse = oAuthLinkedIn.get(responseString);
            this.access_token = refreshResponse.access_token;
            this.created = DateTime.Now;
        }
        public static oAuthLinkedIn Exchange(string authCode, string clientid, string secret, string redirectURI)
        {

            var request = (HttpWebRequest)WebRequest.Create("https://www.linkedin.com/uas/oauth2/accessToken");

            string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", authCode, clientid, secret, redirectURI);
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            var x = oAuthLinkedIn.get(responseString);

            x.clientId = clientid;
            x.secret = secret;


            return x;

        }
        public static Uri GetAutenticationURI(string clientId, string redirectUri,string state)
        {
            // state will be generated by encryption to prevent the CSRF attack
            string scope = "r_basicprofile,r_emailaddress"; // use r_fullprofile for full profile r_basicprofile for basic profile
            string oauth = string.Format("https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id={0}&redirect_uri={1}&state={2}&scope={3}", clientId, redirectUri, state, scope);
            return new Uri(oauth);
        }
        public static string GetFinalJson(string Token)
        {
            string fields = ":(id";
                fields+=",firstName";
                fields+=",lastName";
                fields+=",picture-url";
                fields+=",email-address";
                fields+=",formatted-name";
                fields+=",picture-urls::(original)";
                fields+=",positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,industry,ticker))";
                fields+=",phone-numbers";
                fields+=",location";
                fields+=",siteStandardProfileRequest";
                fields += ")";
            String URI = string.Format("https://api.linkedin.com/v1/people/~{0}?oauth2_access_token={1}&format=json", fields,Token);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
            request.Method = "GET";
            HttpWebResponse hwrWebResponse = (HttpWebResponse)request.GetResponse();
            StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());

            //and read the response
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();
            return responseData;
        }

     
    }
}

==========================================


// <copyright file="OAuth.cs" company="Flexsin Technologies">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author>Sr. Programmer Sandeep Singh Tomar</author>
// <date>02/25/2016 11:40:58 AM </date>
// <summary>OAuth class</summary>


using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Libraries
{
    public class OAuthBase
    {
        #region SignatureTypes enum

        /// <summary>
        /// Provides a predefined set of algorithms that are supported officially by the protocol
        /// </summary>
        public enum SignatureTypes
        {
            HMACSHA1,
            PLAINTEXT,
            RSASHA1
        }

        #endregion

        protected const string OAuthVersion = "1.0";
        protected const string OAuthParameterPrefix = "oauth_";

        //
        // List of know and used oauth parameters' names
        //      
        protected const string OAuthConsumerKeyKey = "oauth_consumer_key";
        protected const string OAuthCallbackKey = "oauth_callback";
        protected const string OAuthVersionKey = "oauth_version";
        protected const string OAuthSignatureMethodKey = "oauth_signature_method";
        protected const string OAuthSignatureKey = "oauth_signature";
        protected const string OAuthTimestampKey = "oauth_timestamp";
        protected const string OAuthNonceKey = "oauth_nonce";
        protected const string OAuthTokenKey = "oauth_token";
        protected const string OAuthTokenSecretKey = "oauth_token_secret";
        protected const string OAuthVerifierKey = "oauth_verifier";

        protected const string HMACSHA1SignatureType = "HMAC-SHA1";
        protected const string PlainTextSignatureType = "PLAINTEXT";
        protected const string RSASHA1SignatureType = "RSA-SHA1";
        protected const string IncludeEmail = "include_email";

        protected Random random = new Random();

        protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

        /// <summary>
        /// Helper function to compute a hash value
        /// </summary>
        /// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
        /// <param name="data">The data to hash</param>
        /// <returns>a Base64 string of the hash value</returns>
        private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
        {
            if (hashAlgorithm == null)
            {
                throw new ArgumentNullException("hashAlgorithm");
            }

            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException("data");
            }

            byte[] dataBuffer = Encoding.ASCII.GetBytes(data);
            byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);

            return Convert.ToBase64String(hashBytes);
        }

        /// <summary>
        /// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
        /// </summary>
        /// <param name="parameters">The query string part of the Url</param>
        /// <returns>A list of QueryParameter each containing the parameter name and value</returns>
        private List<QueryParameter> GetQueryParameters(string parameters)
        {
            if (parameters.StartsWith("?"))
            {
                parameters = parameters.Remove(0, 1);
            }

            var result = new List<QueryParameter>();

            if (!string.IsNullOrEmpty(parameters))
            {
                string[] p = parameters.Split('&');
                foreach (string s in p)
                {
                    if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix))
                    {
                        if (s.IndexOf('=') > -1)
                        {
                            string[] temp = s.Split('=');
                            result.Add(new QueryParameter(temp[0], temp[1]));
                        }
                        else
                        {
                            result.Add(new QueryParameter(s, string.Empty));
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
        /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
        /// </summary>
        /// <param name="value">The value to Url encode</param>
        /// <returns>Returns a Url encoded string</returns>
        public string UrlEncode(string value)
        {
            var result = new StringBuilder();

            foreach (char symbol in value)
            {
                if (unreservedChars.IndexOf(symbol) != -1)
                {
                    result.Append(symbol);
                }
                else
                {
                    result.Append('%' + String.Format("{0:X2}", (int)symbol));
                }
            }

            return result.ToString();
        }

        /// <summary>
        /// Normalizes the request parameters according to the spec
        /// </summary>
        /// <param name="parameters">The list of parameters already sorted</param>
        /// <returns>a string representing the normalized parameters</returns>
        protected string NormalizeRequestParameters(IList<QueryParameter> parameters)
        {
            var sb = new StringBuilder();
            QueryParameter p = null;
            for (int i = 0; i < parameters.Count; i++)
            {
                p = parameters[i];
                sb.AppendFormat("{0}={1}", p.Name, p.Value);

                if (i < parameters.Count - 1)
                {
                    sb.Append("&");
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// Generate the signature base that is used to produce the signature
        /// </summary>
        /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
        /// <param name="consumerKey">The consumer key</param>      
        /// <param name="token">The token, if available. If not available pass null or an empty string</param>
        /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
        /// <param name="callBackUrl">The callback URL (for OAuth 1.0a).If your client cannot accept callbacks, the value MUST be 'oob' </param>
        /// <param name="oauthVerifier">This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string</param>
        /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
        /// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
        /// <returns>The signature base</returns>
        public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret,
                                            string callBackUrl, string oauthVerifier, string httpMethod,
                                            string timeStamp, string nonce, string signatureType,
                                            out string normalizedUrl, out string normalizedRequestParameters)
        {
            if (token == null)
            {
                token = string.Empty;
            }

            if (tokenSecret == null)
            {
                tokenSecret = string.Empty;
            }

            if (string.IsNullOrEmpty(consumerKey))
            {
                throw new ArgumentNullException("consumerKey");
            }

            if (string.IsNullOrEmpty(httpMethod))
            {
                throw new ArgumentNullException("httpMethod");
            }

            if (string.IsNullOrEmpty(signatureType))
            {
                throw new ArgumentNullException("signatureType");
            }

            normalizedUrl = null;
            normalizedRequestParameters = null;

            List<QueryParameter> parameters = GetQueryParameters(url.Query);
            parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
            parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
            parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
            parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
            parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
            parameters.Add(new QueryParameter(IncludeEmail, "true"));
            if (!string.IsNullOrEmpty(callBackUrl))
            {
                parameters.Add(new QueryParameter(OAuthCallbackKey, UrlEncode(callBackUrl)));
            }


            if (!string.IsNullOrEmpty(oauthVerifier))
            {
                parameters.Add(new QueryParameter(OAuthVerifierKey, oauthVerifier));
            }

            if (!string.IsNullOrEmpty(token))
            {
                parameters.Add(new QueryParameter(OAuthTokenKey, token));
            }

            parameters.Sort(new QueryParameterComparer());

            normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
            if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
            {
                normalizedUrl += ":" + url.Port;
            }
            normalizedUrl += url.AbsolutePath;
            normalizedRequestParameters = NormalizeRequestParameters(parameters);

            var signatureBase = new StringBuilder();
            signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
            signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
            signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));

            return signatureBase.ToString();
        }

        /// <summary>
        /// Generate the signature value based on the given signature base and hash algorithm
        /// </summary>
        /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
        /// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
        /// <returns>A base64 string of the hash value</returns>
        public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
        {
            return ComputeHash(hash, signatureBase);
        }

        /// <summary>
        /// Generates a signature using the HMAC-SHA1 algorithm
        /// </summary>
        /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
        /// <param name="consumerKey">The consumer key</param>
        /// <param name="consumerSecret">The consumer seceret</param>
        /// <param name="token">The token, if available. If not available pass null or an empty string</param>
        /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
        /// <param name="callBackUrl">The callback URL (for OAuth 1.0a).If your client cannot accept callbacks, the value MUST be 'oob' </param>
        /// <param name="oauthVerifier">This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string</param>
        /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
        /// <returns>A base64 string of the hash value</returns>
        public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token,
                                        string tokenSecret, string callBackUrl, string oauthVerifier, string httpMethod,
                                        string timeStamp, string nonce, out string normalizedUrl,
                                        out string normalizedRequestParameters)
        {
            return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, callBackUrl, oauthVerifier,
                                     httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, out normalizedUrl,
                                     out normalizedRequestParameters);
        }

        /// <summary>
        /// Generates a signature using the specified signatureType
        /// </summary>
        /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
        /// <param name="consumerKey">The consumer key</param>
        /// <param name="consumerSecret">The consumer seceret</param>
        /// <param name="token">The token, if available. If not available pass null or an empty string</param>
        /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
        /// <param name="callBackUrl">The callback URL (for OAuth 1.0a).If your client cannot accept callbacks, the value MUST be 'oob' </param>
        /// <param name="oauthVerifier">This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string</param>
        /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
        /// <param name="signatureType">The type of signature to use</param>
        /// <returns>A base64 string of the hash value</returns>
        public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token,
                                        string tokenSecret, string callBackUrl, string oauthVerifier, string httpMethod,
                                        string timeStamp, string nonce, SignatureTypes signatureType,
                                        out string normalizedUrl, out string normalizedRequestParameters)
        {
            normalizedUrl = null;
            normalizedRequestParameters = null;

            switch (signatureType)
            {
                case SignatureTypes.PLAINTEXT:
                    return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
                case SignatureTypes.HMACSHA1:
                    string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, callBackUrl,
                                                                 oauthVerifier, httpMethod, timeStamp, nonce,
                                                                 HMACSHA1SignatureType, out normalizedUrl,
                                                                 out normalizedRequestParameters);

                    var hmacsha1 = new HMACSHA1();
                    hmacsha1.Key =
                        Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret),
                                                              string.IsNullOrEmpty(tokenSecret)
                                                                  ? ""
                                                                  : UrlEncode(tokenSecret)));

                    return GenerateSignatureUsingHash(signatureBase, hmacsha1);
                case SignatureTypes.RSASHA1:
                    throw new NotImplementedException();
                default:
                    throw new ArgumentException("Unknown signature type", "signatureType");
            }
        }

        /// <summary>
        /// Generate the timestamp for the signature      
        /// </summary>
        /// <returns></returns>
        public virtual string GenerateTimeStamp()
        {
            // Default implementation of UNIX time of the current UTC time
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /// <summary>
        /// Generate a nonce
        /// </summary>
        /// <returns></returns>
        public virtual string GenerateNonce()
        {
            // Just a simple implementation of a random number between 123400 and 9999999
            return random.Next(123400, 9999999).ToString();
        }

        #region Nested type: QueryParameter

        /// <summary>
        /// Provides an internal structure to sort the query parameter
        /// </summary>
        protected class QueryParameter
        {
            private readonly string name;
            private readonly string value;

            public QueryParameter(string name, string value)
            {
                this.name = name;
                this.value = value;
            }

            public string Name
            {
                get { return name; }
            }

            public string Value
            {
                get { return value; }
            }
        }

        #endregion

        #region Nested type: QueryParameterComparer

        /// <summary>
        /// Comparer class used to perform the sorting of the query parameters
        /// </summary>
        protected class QueryParameterComparer : IComparer<QueryParameter>
        {
            #region IComparer<QueryParameter> Members

            public int Compare(QueryParameter x, QueryParameter y)
            {
                if (x.Name == y.Name)
                {
                    return string.Compare(x.Value, y.Value);
                }
                else
                {
                    return string.Compare(x.Name, y.Name);
                }
            }

            #endregion
        }

        #endregion
    }
}

======================================

// <copyright file="Twitter.cs" company="Flexsin Technologies">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author>Sr. Programmer Sandeep Singh Tomar</author>
// <date>02/25/2016 11:40:58 AM </date>
// <summary>Twitter class</summary>

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;

namespace Libraries
{
    public class oAuthTwitter : OAuthBase
    {
        #region Method enum

        public enum Method
        {
            GET,
            POST,
            DELETE
        } ;

        #endregion

        public const string REQUEST_TOKEN = "https://api.twitter.com/oauth/request_token";
        public const string AUTHORIZE = "https://api.twitter.com/oauth/authorize";
        public const string ACCESS_TOKEN = "https://api.twitter.com/oauth/access_token";
        private string _callBackUrl = "oob";

        private string _consumerKey = "";
        private string _consumerSecret = "";
        private string _oauthVerifier = "";
        private string _token = "";
        private string _tokenSecret = "";

        #region Properties

        public string ConsumerKey
        {
            get
            {
                if (_consumerKey.Length == 0)
                {
                    return _consumerKey;
                }
                return _consumerKey;
            }
            set { _consumerKey = value; }
        }

        public string ConsumerSecret
        {
            get
            {
                if (_consumerSecret.Length == 0)
                {
                    return _consumerSecret;
                }
                return _consumerSecret;
            }
            set { _consumerSecret = value; }
        }

        public string Token
        {
            get { return _token; }
            set { _token = value; }
        }

        public string TokenSecret
        {
            get { return _tokenSecret; }
            set { _tokenSecret = value; }
        }

        public string CallBackUrl
        {
            get { return _callBackUrl; }
            set { _callBackUrl = value; }
        }

        public string OAuthVerifier
        {
            get { return _oauthVerifier; }
            set { _oauthVerifier = value; }
        }

        public oAuthTwitter(string ConsumerKey, string ConsumerSecret,string CallbackUrl)
        {
            this._consumerKey = ConsumerKey;
            this._consumerSecret = ConsumerSecret;
            this._callBackUrl = CallbackUrl;
        }

        #endregion

        /// <summary>
        /// Get the link to Twitter's authorization page for this application.
        /// </summary>
        /// <returns>The url with a valid request token, or a null string.</returns>
        public string AuthorizationLinkGet()
        {
            string ret = null;

            string response = oAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty);
            if (response.Length > 0)
            {
                //response contains token and token secret.  We only need the token.
                NameValueCollection qs = HttpUtility.ParseQueryString(response);

                if (qs["oauth_callback_confirmed"] != null)
                {
                    if (qs["oauth_callback_confirmed"] != "true")
                    {
                        throw new Exception("OAuth callback not confirmed.");
                    }
                }

                if (qs["oauth_token"] != null)
                {
                    ret = AUTHORIZE + "?oauth_token=" + qs["oauth_token"];
                }
            }
            return ret;
        }

        /// <summary>
        /// Exchange the request token for an access token.
        /// </summary>
        /// <param name="authToken">The oauth_token is supplied by Twitter's authorization page following the callback.</param>
        /// <param name="oauthVerifier">An oauth_verifier parameter is provided to the client either in the pre-configured callback URL</param>
        public void AccessTokenGet(string authToken, string oauthVerifier)
        {
            Token = authToken;
            OAuthVerifier = oauthVerifier;

            string response = oAuthWebRequest(Method.GET, ACCESS_TOKEN, String.Empty);

            if (response.Length > 0)
            {
                //Store the Token and Token Secret
                NameValueCollection qs = HttpUtility.ParseQueryString(response);
                if (qs["oauth_token"] != null)
                {
                    Token = qs["oauth_token"];
                }
                if (qs["oauth_token_secret"] != null)
                {
                    TokenSecret = qs["oauth_token_secret"];
                }
            }
        }

        /// <summary>
        /// Submit a web request using oAuth.
        /// </summary>
        /// <param name="method">GET or POST</param>
        /// <param name="url">The full url, including the querystring.</param>
        /// <param name="postData">Data to post (querystring format)</param>
        /// <returns>The web server response.</returns>
        public string oAuthWebRequest(Method method, string url, string postData)
        {
            string outUrl = "";
            string querystring = "";
            string ret = "";


            //Setup postData for signing.
            //Add the postData to the querystring.
            if (method == Method.POST || method == Method.DELETE)
            {
                if (postData.Length > 0)
                {
                    //Decode the parameters and re-encode using the oAuth UrlEncode method.
                    NameValueCollection qs = HttpUtility.ParseQueryString(postData);
                    postData = "";
                    foreach (string key in qs.AllKeys)
                    {
                        if (postData.Length > 0)
                        {
                            postData += "&";
                        }
                        qs[key] = HttpUtility.UrlDecode(qs[key]);
                        qs[key] = UrlEncode(qs[key]);
                        postData += key + "=" + qs[key];
                    }
                    if (url.IndexOf("?") > 0)
                    {
                        url += "&";
                    }
                    else
                    {
                        url += "?";
                    }
                    url += postData;
                }
            }

            var uri = new Uri(url);

            string nonce = GenerateNonce();
            string timeStamp = GenerateTimeStamp();

            //Generate Signature
            string sig = GenerateSignature(uri,
                                           ConsumerKey,
                                           ConsumerSecret,
                                           Token,
                                           TokenSecret,
                                           CallBackUrl,
                                           OAuthVerifier,
                                           method.ToString(),
                                           timeStamp,
                                           nonce,
                                           out outUrl,
                                           out querystring);

            querystring += "&oauth_signature=" + UrlEncode(sig);

            //Convert the querystring to postData
            if (method == Method.POST || method == Method.DELETE)
            {
                postData = querystring;
                querystring = "";
            }

            if (querystring.Length > 0)
            {
                outUrl += "?";
            }

            ret = WebRequest(method, outUrl + querystring, postData);

            return ret;
        }

        /// <summary>
        /// Web Request Wrapper
        /// </summary>
        /// <param name="method">Http Method</param>
        /// <param name="url">Full url to the web resource</param>
        /// <param name="postData">Data to post in querystring format</param>
        /// <returns>The web server response.</returns>
        public string WebRequest(Method method, string url, string postData)
        {
            HttpWebRequest webRequest = null;
            StreamWriter requestWriter = null;
            string responseData = "";

            webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
            webRequest.Method = method.ToString();
            //webRequest.ServicePoint.Expect100Continue = false;
            //webRequest.UserAgent  = "Identify your application please.";
            //webRequest.Timeout = 20000;

            if (method == Method.POST || method == Method.DELETE)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //POST the data.
                requestWriter = new StreamWriter(webRequest.GetRequestStream());
                try
                {
                    requestWriter.Write(postData);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                    requestWriter = null;
                }
            }

            responseData = WebResponseGet(webRequest);

            webRequest = null;

            return responseData;
        }

        /// <summary>
        /// Process the web response.
        /// </summary>
        /// <param name="webRequest">The request object.</param>
        /// <returns>The response data.</returns>
        public string WebResponseGet(HttpWebRequest webRequest)
        {
            StreamReader responseReader = null;
            string responseData = "";

            try
            {
                responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
                responseData = responseReader.ReadToEnd();
            }
            catch
            {
                throw;
            }
            finally
            {
                webRequest.GetResponse().GetResponseStream().Close();
                responseReader.Close();
                responseReader = null;
            }

            return responseData;
        }
    }
}
========================================

How to use all abov class
========================================
1. Create a folder and all class create in this folder.

After that Apply these all below code:

======================================

            Web config Code
==========================================
    <!-- Custom Auth Keys Start here -->
    <!--<add key="FacebookAPIKey" value="279024355781724" />-->
    <add key="FacebookClientId" value="1663889550577825" />
    <add key="FacebookClientSecret" value="79a70c5d7e230180b5d8c6b2b493d047" />
    <add key="FacebookCallbackUrl" value="http://localhost:57085/customer/CustomerAccount/Callback?Provider=Facebook" />

    <!--<add key="GooglePlusClientId" value="115698481113-3ckjd8qg6ue8u7uigcdpf1h424edrnet.apps.googleusercontent.com"/>
    <add key="GooglePlusClientSecret" value="EWu3UBExbaeNBcUqgoTBBHE4"/>-->
    <add key="GooglePlusClientId" value="354569799592-l6esuq9lhgosnitd4njkh3mc2uvae09b.apps.googleusercontent.com" />
    <add key="GooglePlusClientSecret" value="jRoi9LFCvXnevTF4yD5-szZA" />
    <add key="GooglePlusCallbackUrl" value="http://localhost:57085/customer/CustomerAccount/Callback?Provider=GooglePlus" />

    <add key="LinkedInClientId" value="" />
    <add key="LinkedInClientSecret" value="" />
    <add key="LinkedInCallbackUrl" value="" />


    <add key="TwitterClientId" value="" />
    <add key="TwitterClientSecret" value="" />
    <add key="TwitterCallbackUrl" value="" />

    <!-- Custom Auth Keys Ends here -->


============================================
Controller and C# Code.
============================================

        [HttpGet]
        public ActionResult ExternalLogin(string Provider)
        {
            //mode signup to signup and signin to signin
            string redirectUrl = "";// Utility.GetBaseUrl() + GetProfileLink(ProfileType).ToString();
            CustomAuth.eProvider provider = (CustomAuth.eProvider)Enum.Parse(typeof(CustomAuth.eProvider), Provider, true);
            CustomAuth auth = new CustomAuth(provider);
            string CallUrl = auth.GetAuthenticateUrl().AbsoluteUri;
            return new RedirectResult(CallUrl);
        }
=============================================
        public ActionResult Callback()
        {
           // ActionResult actionresult = RedirectToAction("Index", "CustomerProfile");
            ActionResult actionResult = View();
            string ProviderName = Convert.ToString(Request["Provider"]);
            // use Provider name Facebook,LinkedIn,Twitter,GooglePlus for corresponding login
            CustomAuth.eProvider provider = (CustomAuth.eProvider)Enum.Parse(typeof(CustomAuth.eProvider), ProviderName, true);
            string redirectUrl = "";
            string profiletype = "";
            string state = Request["state"];
            string extradata = "";
            string mode = "";
            if (!string.IsNullOrEmpty(state))
            {
                // Initialize CustomAouth class by provider
                CustomAuth auth = new CustomAuth(provider);
                // Get data
                ProfileData data = auth.GetData(Request);
                if (data.Success)
                {
                   
                    Customer objCustomer = new Customer();
                    Status objStatus = new Status();
                    objCustomer.EmailAddress = data.Email;
                    objCustomer.CustomerName = data.FirstName;
                    objCustomer.SurName = data.LastName;
                    objCustomer.Password = GenerateRandom.RandomPassword(4);
                    objCustomer.IsActive = true;
                    objCustomer.Gender = data.Gender == "male" ? 1 : 2;
                    objCustomer.IsFromSocal = true;
                    objCustomer.SocelId = data.Id;
                    objCustomer.SocelType = data.Provider == "Facebook" ? (int)SocialType.Facebook : (int)SocialType.GooglePlus;    
                    objCustomer.ProfileMapImage=data.ImageUrl;
                    Registration(objCustomer); // Insert data
                }
             
            }
            return URL//Where you want to redirect.
}
        ================================