Friday 23 September 2011

Importing Contacts from .CSV file

ImportCSV.aspx

<asp:FileUpload ID="uploadCSV" runat="server" />&nbsp&nbsp
<asp:Button ID="btnUpload" runat="server" Text="Upload Contacts From CSV File" onclick="btnUpload_Click" />

ImportCSV.aspx.cs

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (uploadCSV.HasFile)
        {
            FileInfo fileInfo = new FileInfo(uploadCSV.PostedFile.FileName);

            if (fileInfo.Name.Contains(".csv"))
            {
                string fileName = fileInfo.Name.Replace(".csv", "").ToString();
                string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name;
                uploadCSV.SaveAs(csvFilePath);
                string filePath = Server.MapPath("UploadedCSVFiles") + "\\";
                string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
                string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";

               System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strSql, strCSVConnString);

               DataTable dtCSV = new DataTable();

               DataTable dtSchema = new DataTable();
               adapter.FillSchema(dtCSV, SchemaType.Mapped);
               adapter.Fill(dtCSV);
               }

        }
    }

Thanks Happy Coding.

Post to friend's wall in facebook

for posting on users wall we have to give publish_stream in scope.for all scope and permission in facebook you can follow the link:
http://developers.facebook.com/docs/reference/api/permissions/


callback.aspx.cs:
--------------------------------------------------
oAuthFacebook oAuth = new oAuthFacebook();
if (Request["code"] != null)
        {
            try
            {
                oAuth.AccessTokenGet(Request["code"]);
                Api api = new Api(oAuth.Token);
                User u = api.GetUser();
                api.PostFeedToTarget(friendFacebookId,"Message", "Picture Path on web", "Link", "Name", "Caption", "Description");
              }
             catch
            {

             }
    }


Saturday 17 September 2011

Playing with Google maps in Asp.net

1. Get a Google Maps API key from here:
http://www.google.com/apis/maps/
2. Download the SubGurim wrapper dll from here:
http://en.googlemaps.subgurim.net/descargar.aspx
3. Unzip it, and put it in your \bin directory
4. Add it to your toolbox by
Tools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OK
GMap will now be in the ‘Standard’ area of your Toolbox.
5. Add a new webpage.
6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′
7. Add the following lines to your web.config file:

<appSettings>
<add key="googlemaps.subgurim.net"
 value = "YourGoogleMapsAPIKeyHere" />
</appSettings>

Default.aspx
<%@ Register Assembly="GMaps" Namespace="Subgurim.Controles" TagPrefix="cc1" %>
<cc1:GMap ID="GMap2" runat="server" />

Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            MapMyLocation(“Hyderabad”,”Ankur Bhatnagar”);

    }

private void MapMyLocation(string address,string name)
    {
        Subgurim.Controles.GeoCode GeoCode;
        GeoCode = GMap2.getGeoCodeRequest(address, ConfigurationManager.AppSettings["googlemaps.subgurim.net"]
.ToString());
        Subgurim.Controles.GLatLng gLatLng = new Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng);

        GMap2.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal);
        Subgurim.Controles.GMarker oMarker = new Subgurim.Controles.GMarker(gLatLng);
        GMap2.addGMarker(oMarker);
        GMap2.ToolTip = name;
        var omarker = new Subgurim.Controles.GMarker(gLatLng);
        GInfoWindow gmapinfo = new GInfoWindow(omarker, "<center><b>"+name+"<br/>"+address+"</b></center>", true);
        GMap2.addInfoWindow(gmapinfo);
    }

This sample will give your location in Google maps. Give your location and name in page load in place of my location and name.

Thanks.

Importing LinkedIn contacts in Asp.net

First you need to download linkedIn developer toolkit which you can download from this link.
changes in web.config.
<appSettings>
        <!-- LinkedIn api and secret key -->
    <add key="LinkedInConsumerKey" value="XXXXXXXX"/>
    <add key="LinkedInConsumerSecret" value="XXXXXXX"/>
  </appSettings>
LinkedInBase.cs
//-----------------------------------------------------------------------
// <copyright file="LinkedInBasePage.cs" company="Beemway">
//     Copyright (c) Beemway. All rights reserved.
// </copyright>
// <license>
//     Microsoft Public License (Ms-PL http://opensource.org/licenses/ms-pl.html).
//     Contributors may add their own copyright notice above.
// </license>
//-----------------------------------------------------------------------
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using LinkedIn;
/// <summary>
/// Summary description for BasePage
/// </summary>
public class LinkedInBasePage : System.Web.UI.Page
{
  private string AccessToken
  {
    get { return (string)Session["AccessToken"]; }
    set { Session["AccessToken"] = value; }
  }
  private InMemoryTokenManager TokenManager
  {
    get
    {
      var tokenManager = (InMemoryTokenManager)Application["TokenManager"];
      if (tokenManager == null)
      {
        string consumerKey = ConfigurationManager.AppSettings["LinkedInConsumerKey"];
        string consumerSecret = ConfigurationManager.AppSettings["LinkedInConsumerSecret"];
        if (string.IsNullOrEmpty(consumerKey) == false)
        {
          tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
          Application["TokenManager"] = tokenManager;
        }
      }
      return tokenManager;
    }
  }
  protected WebOAuthAuthorization Authorization
  {
    get;
    private set;
  }
  protected override void OnLoad(EventArgs e)
  {
    this.Authorization = new WebOAuthAuthorization(this.TokenManager, this.AccessToken);
    if (!IsPostBack)
    {
      string accessToken = this.Authorization.CompleteAuthorize();
      if (accessToken != null)
      {
        this.AccessToken = accessToken;
        Response.Redirect(Request.Path);
      }
      if (AccessToken == null)
      {
        this.Authorization.BeginAuthorize();
      }
    }
    base.OnLoad(e);
  }
}
LinkedIn.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LinkedIn.aspx.cs" Inherits="MyLinkedIn" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblUserInfo" runat="server" Font-Bold="True"
            Font-Names="Verdana" Font-Size="12pt" ForeColor="Green"></asp:Label><br /><br /><br />
        <asp:GridView ID="gvContacts" runat="server" BackColor="White"
            BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
            ForeColor="Black" GridLines="Vertical">
            <AlternatingRowStyle BackColor="White" />
            <FooterStyle BackColor="#CCCC99" />
            <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#F7F7DE" />
            <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FBFBF2" />
            <SortedAscendingHeaderStyle BackColor="#848384" />
            <SortedDescendingCellStyle BackColor="#EAEAD3" />
            <SortedDescendingHeaderStyle BackColor="#575357" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>
LinkedIn.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LinkedIn;
using LinkedIn.ServiceEntities;
using System.Data;
public partial class MyLinkedIn : LinkedInBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        getLinkedInUserInfo();
        getLinkedInContacts();
    }
    private void getLinkedInUserInfo()
    {
        LinkedInService service = new LinkedInService(base.Authorization);
        List<ProfileField> fields = new List<ProfileField>();
        fields.Add(ProfileField.PersonId);
        fields.Add(ProfileField.FirstName);
        fields.Add(ProfileField.LastName);
        fields.Add(ProfileField.Headline);
        fields.Add(ProfileField.CurrentStatus);
        fields.Add(ProfileField.PositionId);
        fields.Add(ProfileField.PositionTitle);
        fields.Add(ProfileField.PositionSummary);
        fields.Add(ProfileField.PositionStartDate);
        fields.Add(ProfileField.PositionEndDate);
        fields.Add(ProfileField.PositionIsCurrent);
        fields.Add(ProfileField.PositionCompanyName);
        fields.Add(ProfileField.PictureUrl);
        fields.Add(ProfileField.DateOfBirth);
        DisplayProfile(service.GetCurrentUser(ProfileType.Standard, fields));
    }
    private void DisplayProfile(Person person)
    {
        if (person != null)
        {
            if (person.DateOfBirth != null)
                lblUserInfo.Text = "Welcome " + person.Name + " Your LinkedIn ID is " + person.Id + " Your DOB is " + person.DateOfBirth.Day + "/" + person.DateOfBirth.Month + "/" + person.DateOfBirth.Year;
            else
                lblUserInfo.Text = "Welcome " + person.Name + " Your ID is " + person.Id + " Your DOB is NA";
        }
    }
    private string DisplayContactBirthDate(Person person)
    {
        if (person != null)
        {
            if (person.DateOfBirth != null)
                return person.DateOfBirth.Day + "/" + person.DateOfBirth.Month + "/" + person.DateOfBirth.Year;
            else
                return "NA";
        }
        else
        {
            return "NA";
        }
    }
    private void getLinkedInContacts()
    {
        DataTable dtContacts = new DataTable();
        DataColumn dcNO = new DataColumn("SerialNo", System.Type.GetType("System.Int32"));
        DataColumn dcID = new DataColumn("LinkedInID", System.Type.GetType("System.String"));
        DataColumn dcName = new DataColumn("Friends Name", System.Type.GetType("System.String"));
        DataColumn dcDOB = new DataColumn("Friends DOB", System.Type.GetType("System.String"));
        dtContacts.Columns.Add(dcNO);
        dtContacts.Columns.Add(dcID);
        dtContacts.Columns.Add(dcName);
        dtContacts.Columns.Add(dcDOB);
        LinkedInService service = new LinkedInService(base.Authorization);
        var v = service.GetConnectionsForCurrentUser().Items;
        int k = 0;
        foreach (LinkedIn.ServiceEntities.Person contact in v)
        {
            DataRow dr = dtContacts.NewRow();
            k++;
            dr[0] = k;
            dr[1] = contact.Id;
            dr[2] = contact.Name;
            List<ProfileField> fields = new List<ProfileField>();
            fields.Add(ProfileField.DateOfBirth);
            dr[3] = DisplayContactBirthDate(service.GetProfileByMemberId(contact.Id, fields));
            dtContacts.Rows.Add(dr);
        }
        gvContacts.DataSource = dtContacts;
        gvContacts.DataBind();
    }
}

This post will definitely help you
Thanks

Importing MSN/Windows Live contacts in asp.net

I am using windows live sdk to import Windows live contacts. Windows live contacts can be imported by using JavaScript, REST api but i am using server side scenario to retrieve contacts.
First of all we have to create an application on windows live which you can create from this link. press create application button by which you can get API key and secret.
Login.aspx
<script type="text/javascript">
function GoToMSN() {
            top.location.href = "https://oauth.live.com/authorize?client_id
=YOURCLIENTID
&scope=REQUIREDSCOPRES
&response_type=code&
redirect_uri=http://contacts.YOURSITEURL.com/
callback.aspx";
}</script>
<img alt="" title="Login to your msn account
and import your contacts." src="msn.jpg" onclick="javascript:GoToMSN();"/>
Callback.aspx.cs
namespace OAuthTest
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Xml;
    using System.Web.Script.Serialization;
    using System.Collections;
    using System.Data;
    public partial class Callback : System.Web.UI.Page
    {
        private const string wlCookie = "wl_auth";
        private const string clientId = "XXXXXXXXXXXXXX";
        private const string callback = "http://yoursite.com/callback1.aspx";
        private const string clientSecret = "XXXXXXXXXXXXXXXXXX";
        private const string oauthUrl = "https://oauth.live.com/token";
       
        public static int k = 0;
        public static DataTable dtMSNContacts = new DataTable();
        DataColumn dcNO = new DataColumn("SerialNo",           System.Type.GetType("System.String"));
        DataColumn dcId = new DataColumn("MSNId", System.Type.GetType("System.String"));
        DataColumn dcName = new DataColumn("Friends Name", System.Type.GetType("System.String"));
        DataColumn dcDOB = new DataColumn("Friends DOB", System.Type.GetType("System.String"));

        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            string verifier = Request.QueryString["Code"];
            OAuthToken token;
            OAuthError error;
            if (!string.IsNullOrEmpty(verifier))
            {
                RequestAccessTokenByVerifier(verifier, out token, out error);
                gvContacts.DataSource = dtMSNContacts;
                gvContacts.DataBind();
                return;
            }
        }
        private static void RequestAccessTokenByVerifier(string verifier, out OAuthToken token, out OAuthError error)
        {
            string content = String.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code",
                HttpUtility.UrlEncode(clientId),
                HttpUtility.UrlEncode(callback),
                HttpUtility.UrlEncode(clientSecret),
                HttpUtility.UrlEncode(verifier));
            RequestAccessToken(content, out token, out error);
        }
        private static void RequestAccessToken(string postContent, out OAuthToken token, out OAuthError error)
        {
            token = null;
            error = null;
            HttpWebRequest request = WebRequest.Create(oauthUrl) as HttpWebRequest;
            request.Method = "POST";
            try
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(postContent);
                }
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OAuthToken));
                    token = serializer.ReadObject(response.GetResponseStream()) as OAuthToken;
                    if (token != null)
                    {
                        RequestContacts(token.AccessToken);
                        //return;
                    }
                }
            }
            catch (WebException e)
            {
                HttpWebResponse response = e.Response as HttpWebResponse;
                if (response != null)
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OAuthError));
                    error = serializer.ReadObject(response.GetResponseStream()) as OAuthError;
                }
            }
            catch (IOException)
            {
            }
            if (error == null)
            {
                error = new OAuthError("request_failed", "Failed to retrieve user access token.");
            }
        }
        private static void RequestContacts(string AccessToken)
        {
            string content = String.Format("access_token={0}", HttpUtility.UrlEncode(AccessToken));
            string url = "https://apis.live.net/v5.0/me/contacts?" + content;
            //string url = "https://apis.live.net/v5.0/me/contacts?access_token=" + AccessToken;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //request.Method = "POST";
            request.Method = WebRequestMethods.Http.Get;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string tmp = reader.ReadToEnd();
            JavaScriptSerializer ser = new JavaScriptSerializer();
            Dictionary<string, object> dictionary = ser.Deserialize<Dictionary<string, object>>(tmp);
            DisplayDictionary(dictionary);
            response.Close();
        }
    private static bool DisplayDictionary(Dictionary<string, object> dict)
        {
            bool bSuccess = false;
            //indentLevel++;
            DataRow dr = dtMSNContacts.NewRow();
            string dob = "";
            foreach (string strKey in dict.Keys)
            {
                string strOutput = "";// "".PadLeft(indentLevel * 8) + strKey + ":";
                //tbOutput.AppendText("\r\n" + strOutput);
                object o = dict[strKey];
                if (o is Dictionary<string, object>)
                {
                    DisplayDictionary((Dictionary<string, object>)o);
                }
                else if (o is ArrayList)
                {
                    foreach (object oChild in ((ArrayList)o))
                    {
                        if (oChild is string)
                        {
                            strOutput = ((string)oChild);
                            //tbOutput.AppendText(strOutput + ",");
                        }
                        else if (oChild is Dictionary<string, object>)
                        {
                            DisplayDictionary((Dictionary<string, object>)oChild);
                            //tbOutput.AppendText("\r\n");
                        }
                    }
                }
                else
                {
                    if (o != null)
                    {
                        strOutput = o.ToString();
                        if (strKey == "id")
                        {
                            k++;
                            dr[0] = k;
                            dr[1] = strOutput;
                        }
                        else if (strKey == "name")
                        {
                            dr[2] = strOutput;
                        }
                        else if (strKey == "birth_day")
                        {
                            dob = strOutput;
                        }
                        else if (strKey == "birth_month")
                        {
                            dob += "/" + strOutput;
                        }
                        dr[3] = dob;
                    }
                }
            }


            if (dr[0].ToString() != "")
            {
                dtMSNContacts.Rows.Add(dr);
                
            }
            return bSuccess;
        }
    }
    [DataContract]
    public class OAuthToken
    {
        [DataMember(Name = OAuthConstants.AccessToken)]
        public string AccessToken { get; set; }
        [DataMember(Name = OAuthConstants.RefreshToken)]
        public string RefreshToken { get; set; }
        [DataMember(Name = OAuthConstants.ExpiresIn)]
        public string ExpiresIn { get; set; }
        [DataMember(Name = OAuthConstants.Scope)]
        public string Scope { get; set; }
    }
    public static class OAuthConstants
    {
        #region OAuth 2.0 standard parameters
        public const string ClientID = "client_id";
        public const string ClientSecret = "client_secret";
        public const string Callback = "redirect_uri";
        public const string ClientState = "state";
        public const string Scope = "scope";
        public const string Code = "code";
        public const string AccessToken = "access_token";
        public const string ExpiresIn = "expires_in";
        public const string RefreshToken = "refresh_token";
        public const string ResponseType = "response_type";
        public const string GrantType = "grant_type";
        public const string Error = "error";
        public const string ErrorDescription = "error_description";
        public const string Display = "display";
        #endregion
    }
    [DataContract]
    public class OAuthError
    {
        public OAuthError(string code, string desc)
        {
            this.Code = code;
            this.Description = desc;
        }
        [DataMember(Name = OAuthConstants.Error)]
        public string Code { get; private set; }
        [DataMember(Name = OAuthConstants.ErrorDescription)]
        public string Description { get; private set; }
    }
}
I think that this post will help you.
Thanks.

Importing Yahoo contacts In ASP.NET

I am using OAuth to retrieve Yahoo Contacts. First lets see how oauth works:
Untitled4
You can request for an API key by navigating this this link.. You have to fill up the web form before you request for a key. There are 2 steps. The first step is filling out app specific information and request for an API key and the second step is to specify what services can be accessible by the API key. You can choose to access all public resources or alternatively, you can specify which services you are particularly interested in.
Step 1: Setting up App Information & Get API Key
account-setup
Configuration Notes
  • Application URL: This is the URL where your application resides.You can point out the root of the application here. For my app, I mentioned http:www.imgalib.com/ as app URL.
  • Choose an appropriate application name (my application name is qcontactreader).
  • Specify app kind, my sample app is web based.
  • Provide a small description about your application.
  • Access scope: Choose "This app requires access to private user data." option as my sample app is going to access the user contact list.
  • Hit Get API key and you are ready to roll.
Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="oauth-test.aspx.cs" Inherits="test_oauth_test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Connect to Yahoo!" OnClick="Button1_Click" />
        <asp:Label runat="server" ID="ResponseMessage1"></asp:Label>
        <asp:GridView ID="grvMyFriends" runat="server" AutoGenerateColumns="false" CellPadding="5"
            GridLines="None">
       <Columns>
                <asp:TemplateField HeaderText="Email">
                    <ItemTemplate>
                        <%# Container.DataItem %>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EmptyDataTemplate>
                No Friend List Found
            </EmptyDataTemplate>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
Login.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net;
using System.IO;
using OAuth.Net.Common;
using OAuth.Net.Components;
using OAuth.Net.Consumer;
using OAuth;
using System.Text;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text.RegularExpressions;
public partial class test_oauth_test : System.Web.UI.Page
{
    public string ConsumerKey
    {
        get
        {
            return "YOUR_CONSUMER_KEY";
        }
    }
    public string ConsumerSecret
    {
        get
        {
            return "YOUR_CUSTOMER_SECRET_KEY";
        }
    }
    public string OauthVerifier
    {
        get
        {
            try
            {
                if (!string.IsNullOrEmpty(Session["Oauth_Verifier"].ToString()))
                    return Session["Oauth_Verifier"].ToString();
                else
                    return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }
        set
        {
            Session["Oauth_Verifier"] = value;
        }
    }
    public string OauthToken
    {
        get
        {
            if (!string.IsNullOrEmpty(Session["Oauth_Token"].ToString()))
                return Session["Oauth_Token"].ToString();
            else
                return string.Empty;
        }
        set
        {
            Session["Oauth_Token"] = value;
        }
    }
    public string OauthTokenSecret
    {
        get
        {
            if (!string.IsNullOrEmpty(Session["Oauth_Token_Secret"].ToString()))
                return Session["Oauth_Token_Secret"].ToString();
            else
                return string.Empty;
        }
        set
        {
            Session["Oauth_Token_Secret"] = value;
        }
    }
    public string OauthSessionHandle
    {
        get
        {
            if (!string.IsNullOrEmpty(Session["Oauth_Session_Handle"]
.ToString()))
                return Session["Oauth_Session_Handle"].ToString();
            else
                return string.Empty;
        }
        set
        {
            Session["Oauth_Session_Handle"] = value;
        }
    }
    public string OauthYahooGuid
    {
        get
        {
            try
            {
                if (!string.IsNullOrEmpty(Session["Oauth_Yahoo_Guid"].ToString()))
                    return Session["Oauth_Yahoo_Guid"].ToString();
                else
                    return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }
        set
        {
            Session["Oauth_Yahoo_Guid"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string oauth_token = Request["oauth_token"];
            string oauth_verifier = Request["oauth_verifier"];
            if (!string.IsNullOrEmpty(oauth_verifier) && oauth_verifier != "")
            {
                Button1.Visible = false;
                OauthToken = oauth_token;
                OauthVerifier = oauth_verifier;
                RegisterStartupScript("refresh", "<script type='text/javascript'>
window.opener.location = 'oauth-test.aspx'; self.close();</script>");
            }
            else if (!string.IsNullOrEmpty(OauthVerifier))
            {
                Button1.Visible = false;
                if (string.IsNullOrEmpty(OauthYahooGuid))
                    GetAccessToken(OauthToken, OauthVerifier);
                //RefreshToken();
                RetriveContacts();
            }
        }
    }
    private string GetRequestToken()
    {
        string authorizationUrl = string.Empty;
        OAuthBase oauth = new OAuthBase();
        Uri uri = new Uri("
https://api.login.yahoo.com/oauth/v2/get_request_token");
        string nonce = oauth.GenerateNonce();
        string timeStamp = oauth.GenerateTimeStamp();
        string normalizedUrl;
        string normalizedRequestParameters;
        string sig = oauth.GenerateSignature(uri, ConsumerKey,
ConsumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, out normalizedUrl, out normalizedRequestParameters); //OAuthBase.SignatureTypes.HMACSHA1
        StringBuilder sbRequestToken = new StringBuilder(uri.ToString());
        sbRequestToken.AppendFormat("?oauth_nonce={0}&", nonce);
        sbRequestToken.AppendFormat("oauth_timestamp={0}&", timeStamp);
        sbRequestToken.AppendFormat("oauth_consumer_key={0}&", ConsumerKey);
        sbRequestToken.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT");
//HMAC-SHA1
        sbRequestToken.AppendFormat("oauth_signature={0}&", sig);
        sbRequestToken.AppendFormat("oauth_version={0}&", "1.0");
        sbRequestToken.AppendFormat("oauth_callback={0}", HttpUtility.UrlEncode("http://www.yoursite.com/yahoo-oauth/default.aspx"));
        //Response.Write(sbRequestToken.ToString());
        //Response.End();
        try
        {
            string returnStr = string.Empty;
            string[] returnData;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbRequestToken.ToString());
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader streamReader = new StreamReader(res.GetResponseStream());
            returnStr = streamReader.ReadToEnd();
            returnData = returnStr.Split(new Char[] { '&' });
            //Response.Write(returnStr);
            int index;
            if (returnData.Length > 0)
            {
                //index = returnData[0].IndexOf("=");
                //string oauth_token = returnData[0].Substring(index + 1);
                //Session["Oauth_Token"] = oauth_token;
                index = returnData[1].IndexOf("=");
                string oauth_token_secret = returnData[1].Substring(index + 1);
                OauthTokenSecret = oauth_token_secret;
                //index = returnData[2].IndexOf("=");
                //int oauth_expires_in;
                //Int32.TryParse(returnData[2].Substring(index + 1), out oauth_expires_in);
                //Session["Oauth_Expires_In"] = oauth_expires_in;
                index = returnData[3].IndexOf("=");
                string oauth_request_auth_url = returnData[3].Substring(index + 1);
                authorizationUrl = HttpUtility.UrlDecode(oauth_request_auth_url);
            }
        }
        catch (WebException ex)
        {
            Response.Write(ex.Message);
        }
        return authorizationUrl;
    }
    private void RedirectUserForAuthorization(string authorizationUrl)
    {
        //Response.Redirect(authorizationUrl);
        RegisterStartupScript("openwin", "<script type='text/javascript'>window.open('" + authorizationUrl + "','mywindow', 'left=250,top=50,menubar=0,resizable=0,
location=1,toolbar=0,status=1,scrollbars=0,
width=500,height=455');</script>");
    }
    private void GetAccessToken(string oauth_token, string oauth_verifier)
    {
        OAuthBase oauth = new OAuthBase();
        Uri uri = new Uri("https://api.login.yahoo.com/oauth/v2/get_token");
        string nonce = oauth.GenerateNonce();
        string timeStamp = oauth.GenerateTimeStamp();
        string sig = ConsumerSecret + "%26" + OauthTokenSecret;
        StringBuilder sbAccessToken = new StringBuilder(uri.ToString());
        sbAccessToken.AppendFormat("?oauth_consumer_key={0}&", ConsumerKey);
        sbAccessToken.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT");
//HMAC-SHA1
        sbAccessToken.AppendFormat("oauth_signature={0}&", sig);
        sbAccessToken.AppendFormat("oauth_timestamp={0}&", timeStamp);
        sbAccessToken.AppendFormat("oauth_version={0}&", "1.0");
        sbAccessToken.AppendFormat("oauth_token={0}&", oauth_token);
        sbAccessToken.AppendFormat("oauth_nonce={0}&", nonce);
        sbAccessToken.AppendFormat("oauth_verifier={0}", oauth_verifier);
        //Response.Write(sbAccessToken.ToString());
        //Response.End();
        try
        {
            string returnStr = string.Empty;
            string[] returnData;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbAccessToken.ToString());
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader streamReader = new StreamReader(res.GetResponseStream());
            returnStr = streamReader.ReadToEnd();
            returnData = returnStr.Split(new Char[] { '&' });
            //Response.Write(returnStr);
            //Response.End();
            int index;
            if (returnData.Length > 0)
            {
                index = returnData[0].IndexOf("=");
                OauthToken = returnData[0].Substring(index + 1);
                index = returnData[1].IndexOf("=");
                string oauth_token_secret = returnData[1].Substring(index + 1);
                OauthTokenSecret = oauth_token_secret;
                //index = returnData[2].IndexOf("=");
                //int oauth_expires_in;
                //Int32.TryParse(returnData[2].Substring(index + 1), out oauth_expires_in);
                index = returnData[3].IndexOf("=");
                string oauth_session_handle = returnData[3].Substring(index + 1);
                OauthSessionHandle = oauth_session_handle;
                //index = returnData[4].IndexOf("=");
                //int oauth_authorization_expires_in;
                //Int32.TryParse(returnData[4].Substring(index + 1), out oauth_authorization_expires_in);
                index = returnData[5].IndexOf("=");
                string xoauth_yahoo_guid = returnData[5].Substring(index + 1);
                OauthYahooGuid = xoauth_yahoo_guid;
            }
        }
        catch (WebException ex)
        {
            Response.Write(ex.Message);
        }
    }
    private void RefreshToken()
    {
        OAuthBase oauth = new OAuthBase();
        Uri uri = new Uri("https://api.login.yahoo.com/oauth/v2/get_token");
        string nonce = oauth.GenerateNonce();
        string timeStamp = oauth.GenerateTimeStamp();
        string sig = ConsumerSecret + "%26" + OauthTokenSecret;
        StringBuilder sbrefreshToken = new StringBuilder(uri.ToString());
        sbrefreshToken.AppendFormat("?oauth_consumer_key={0}&", ConsumerKey);
        sbrefreshToken.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT");
//HMAC-SHA1
        sbrefreshToken.AppendFormat("oauth_signature={0}&", sig);
        sbrefreshToken.AppendFormat("oauth_timestamp={0}&", timeStamp);
        sbrefreshToken.AppendFormat("oauth_version={0}&", "1.0");
        sbrefreshToken.AppendFormat("oauth_token={0}&", OauthToken);
        sbrefreshToken.AppendFormat("oauth_session_handle={0}&", OauthSessionHandle);
        sbrefreshToken.AppendFormat("oauth_nonce={0}", nonce);
        try
        {
            string returnStr = string.Empty;
            string[] returnData;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbrefreshToken.ToString());
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader streamReader = new StreamReader(res.GetResponseStream());
            returnStr = streamReader.ReadToEnd();
            returnData = returnStr.Split(new Char[] { '&' });
            //Response.Write(returnStr);
            int index;
            if (returnData.Length > 0)
            {
                index = returnData[0].IndexOf("=");
                string oauth_token = returnData[0].Substring(index + 1);
                OauthToken = oauth_token;
                index = returnData[1].IndexOf("=");
                string oauth_token_secret = returnData[1].Substring(index + 1);
                OauthTokenSecret = oauth_token_secret;
                //index = returnData[2].IndexOf("=");
                //int oauth_expires_in;
                //Int32.TryParse(returnData[2].Substring(index + 1), out oauth_expires_in);
                index = returnData[3].IndexOf("=");
                string oauth_session_handle = returnData[3].Substring(index + 1);
                OauthSessionHandle = oauth_session_handle;
                //index = returnData[4].IndexOf("=");
                //int oauth_authorization_expires_in;
                //Int32.TryParse(returnData[4].Substring(index + 1), out oauth_authorization_expires_in);
                index = returnData[5].IndexOf("=");
                string xoauth_yahoo_guid = returnData[5].Substring(index + 1);
                OauthYahooGuid = xoauth_yahoo_guid;
            }
        }
        catch (WebException ex)
        {
            Response.Write(ex.Message);
        }
    }
    private void RetriveContacts()
    {
        OAuthBase oauth = new OAuthBase();
        Uri uri = new Uri("http://social.yahooapis.com/v1/user/" + OauthYahooGuid + "/contacts?format=XML");
        string nonce = oauth.GenerateNonce();
        string timeStamp = oauth.GenerateTimeStamp();
        string normalizedUrl;
        string normalizedRequestParameters;
        string sig = oauth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, OauthToken, OauthTokenSecret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
        StringBuilder sbGetContacts = new StringBuilder(uri.ToString());
        //Response.Write("URL: " + sbGetContacts.ToString());
        //Response.End();
        try
        {
            string returnStr = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbGetContacts.ToString());
            req.Method = "GET";
            string authHeader = "Authorization: OAuth " +
            "realm=\"yahooapis.com\"" +
            ",oauth_consumer_key=\"" + ConsumerKey + "\"" +
            ",oauth_nonce=\"" + nonce + "\"" +
            ",oauth_signature_method=\"HMAC-SHA1\"" +
            ",oauth_timestamp=\"" + timeStamp + "\"" +
            ",oauth_token=\"" + OauthToken + "\"" +
            ",oauth_version=\"1.0\"" +
            ",oauth_signature=\"" + HttpUtility.UrlEncode(sig) + "\"";
            //Response.Write("</br>Headers: " + authHeader);
            req.Headers.Add(authHeader);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader streamReader = new StreamReader(res.GetResponseStream());
            returnStr = streamReader.ReadToEnd();
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(returnStr);
            XmlNodeList elemList = xmldoc.DocumentElement.GetElementsByTagName("fields");
            ArrayList emails = new ArrayList();
            for (int i = 0; i < elemList.Count; i++)
            {
                if (elemList[i].ChildNodes[1].InnerText == "email")
                    emails.Add(elemList[i].ChildNodes[2].InnerText);
                //Response.Write(elemList[i].ChildNodes[2].InnerText + "<br/>");
            }
            grvMyFriends.DataSource = emails;
            grvMyFriends.DataBind();
        }
        #region error
        catch (WebException ex)
        {
            //Response.Write(ex.Message);
            Response.Write("<br/>" + ex.Message + "</br>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            Response.Write("<br/>length: " + ex.Source.Length.ToString());
            Response.Write("<br/>stack trace: " + ex.StackTrace);
            Response.Write("<br/>status: " + ex.Status.ToString());
            HttpWebResponse res = (HttpWebResponse)ex.Response;
            int code = Convert.ToInt32(res.StatusCode);
            Response.Write("<br/>Status Code: (" + code.ToString() + ") " + res.StatusCode.ToString());
            Response.Write("<br/>Status Description: " + res.StatusDescription);
            if (ex.InnerException != null)
            {
                Response.Write("<br/>innerexception: " + ex.InnerException.Message);
            }
            if (ex.Source.Length > 0)
                Response.Write("<br/>source: " + ex.Source.ToString());
            if (res != null)
            {
                for (int i = 0; i < res.Headers.Count; i++)
                {
                    Response.Write("<br/>headers: " + i.ToString() + ": " + res.Headers[i]);
                }
            }
        }
        #endregion error
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string authorizationUrl = string.Empty;
        authorizationUrl = GetRequestToken();
        RedirectUserForAuthorization(authorizationUrl);
    }
}
OAuthBase.cs
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Text;
using System.Web;
public class OAuthBase
{
    /// <summary>
    /// Provides a predefined set of algorithms that are supported
officially by the protocol
    /// </summary>
    public enum SignatureTypes
    {
        HMACSHA1,
        PLAINTEXT,
        RSASHA1
    }
    /// <summary>
    /// Provides an internal structure to sort the query parameter
    /// </summary>
    protected class QueryParameter
    {
        private string name = null;
        private string value = null;
        public QueryParameter(string name, string value)
        {
            this.name = name;
            this.value = value;
        }
        public string Name
        {
            get { return name; }
        }
        public string Value
        {
            get { return value; }
        }
    }
    /// <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
    }
    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 HMACSHA1SignatureType = "HMAC-SHA1";
    protected const string PlainTextSignatureType = "PLAINTEXT";
    protected const string RSASHA1SignatureType = "RSA-SHA1";
    protected Random random = new Random();
    protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST
UVWXYZ0123456789-_.~";
    /// <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 = System.Text.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);
        }
        List<QueryParameter> 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>
    protected string UrlEncode(string value)
    {
        StringBuilder 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)
    {
        StringBuilder 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="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 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));
        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);
        StringBuilder 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="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 httpMethod, string timeStamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters)
    {
        return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, 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="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 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, httpMethod, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters);
                HMACSHA1 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);
        string timeStamp = ts.TotalSeconds.ToString();
        timeStamp = timeStamp.Substring(0, timeStamp.IndexOf("."));
        return timeStamp;
    }
    /// <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();
    }
}
I think this post will help you. Thanks. Happy Coding.