Import MSN/Windows Live Contacts In Asp.net Using C#

Posted: July 26, 2012 in ASP.net, C#, Uncategorized
Tags: ,
To Get The Contacts first of all we have to create an application on windows live which you can create from Here   press create application button by which you can get API key and secret.

Now You Can Put This Tag Into Your aspx Page ..

<a href=”https://oauth.live.com/authorize?client_id=YOURCLIENTID&scope=wl.basic&client_secret=YOURCLIENTSECRET&response_type=code&redirect_uri=”Your aspx Page url” > Click To Get Msn Contacts </a>

Then You Have To Make One More Class..  You Can Say MsnImport.cs

public class MsnImport
{
private const string wlCookie = “wl_auth”;
private const string clientId = “YOURCLIENTID”;
private string Callback = “URL Of Your Page Where You Want To Redirect From Msn”;
private const string clientSecret = “YOURCLIENTSECRET”;
private const string oauthUrl = “https://oauth.live.com/token&#8221;;
private List<string> emaillist = new List<string>();
public MsnImport(int agentid)
{
}
public List<string> GetMsnContacts(string code)
{

try
{
HttpContext context = HttpContext.Current;
string verifier = code;
OAuthToken token;
OAuthError error;

if (!string.IsNullOrEmpty(verifier))
{
RequestAccessTokenByVerifier(verifier, out token, out error);
}
}
catch (Exception ex) { }
return emaillist;
}
private 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 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);
}
}
}
catch (Exception ex)
{

}

}
private void RequestContacts(string AccessToken)
{
string content = String.Format(“access_token={0}”, HttpUtility.UrlEncode(AccessToken));
string url = “https://apis.live.net/v5.0/me/contacts?&#8221; + content;
//string url = “https://apis.live.net/v5.0/me/contacts?access_token=&#8221; + 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);
}
public bool DisplayDictionary(Dictionary<string, object> dict)
{
bool bSuccess = false;
string abc = string.Empty;
foreach (string strKey in dict.Keys)
{
string strOutput = “”;// “”.PadLeft(indentLevel * 8) + strKey + “:”;
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);
}
else if (oChild is Dictionary<string, object>)
{
DisplayDictionary((Dictionary<string, object>)oChild);
}
}
}
else
{
if (o != null)
{
strOutput = o.ToString();
if (strKey == “name”)
{
if (strOutput.Contains(“@”))
emaillist.Add(strOutput);
}
}
}
}
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
{
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”;
}
[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; }
}

_______________________________________________________________________________________

In Your .aspx Page You Have To Write This Code in Page_Load()

if (Request.QueryString[“code”] != null)
{
GetMsnContacts(Request.QueryString[“code”].ToString());
}

You Can Call This Method In Method In Your .aspx Page

private void GetMsnContacts(string code)
{
MsnImport msnImport = new MsnImport();
List<string> emaillist = new List<string>();
emaillist = msnImport.GetMsnContacts(code);
}

_______________________________________________________________________________________

By Implementing The Above Code You Can Easily Import Msn Contacts ..

Hope This Post Will Help you Somehow . . :) . Feel Free To Ask Anything You Need.

Waiting For Your Valuable Feedback.

Advertisements
Comments
  1. Usually I don’t read post on blogs, but I wish to say that this write-up very pressured me to check out and do so! Your writing taste has been amazed me. Thank you, very great article.

  2. helpful blog, bookmarked the website with hopes to read more, this is the way a blog should be! thanks! lista de emails lista de emails lista de emails lista de emails lista de emails

  3. sanwar says:

    Hello sir can you please tell me how to use in local machine , Because i have no domain name as like http://www.contoso.com. , I have only local machine but when i am registered my application on Hotmail.com or live.com then require a Redirect domain like http://www.contoso.com . so please help me how to do it.

    Thanks

  4. Naresh Gohil says:

    How can I get client id and client secret for particular user?
    I want to import contacts by providing user id and password.
    Can you please help me in this?

  5. Naresh Gohil says:

    How can I get client id and client secret for particular user?
    I want to import contacts by providing user id and password.
    Can you please help me in this?

  6. dead says:

    did implemented this steps in my application, but the code:

    private void GetMsnContacts(string code)
    {
    MsnImport msnImport = new MsnImport();
    List emaillist = new List();
    emaillist = msnImport.GetMsnContacts(code);

    }

    don’t return nothing, can u help me?

    i’m not sure if the list emaillist get any valor after callback of login on hotmail page.

    the request code is comming normally like default.aspx?code=ajdfasdhf1431jfh

  7. Константин says:

    Добрый день!
    Предлагаем Вам широкий спектр услуг по лазерной гравировке, лазерной маркировке, изготовлению сувенирной и наградной продукции, изготовлению табличек, номерков и др., фигурную лазерную резку различных листовых материалов на таких как: металл, дерево, стекло, кожа, пластик, пленочных материалов (наклеек).
    Также готовы предложить помощь в профессиональной подготовке макетов.
    Надеемся, что наше предложение Вас заинтересует.
    Готовы ответить на все интересующие вопросы.
    С уважением, Константин
    e-mail: gravirovka2009@yandex.ru

  8. Константин says:

    Добрый день!
    Предлагаем Вам широкий спектр услуг по лазерной гравировке, лазерной маркировке, изготовлению сувенирной и наградной продукции, изготовлению табличек, номерков и др., фигурную лазерную резку различных листовых материалов на таких как: металл, дерево, стекло, кожа, пластик, пленочных материалов (наклеек).
    Также готовы предложить помощь в профессиональной подготовке макетов.
    Надеемся, что наше предложение Вас заинтересует.
    Готовы ответить на все интересующие вопросы.
    С уважением, Константин
    e-mail: gravirovka2009@gmail.com

  9. Hi,
    I can see some links which seems are not correct like:

    “https://oauth.live.com/token”;
    string url = “https://apis.live.net/v5.0/me/contacts?” + content;

    there has no ending ” (quotes).

    When I am changing and trying with my url it is getting error. I can see my website is trying to access url like:

    http://emailcontacts.blooddonornetwork.com/%E2%80%9Dhttps://oauth.live.com/authorize?client_id=00000000400EA798&scope=wl.basic&client_secret=lgz8wEZMAccWbXCBIujk6tvCtUIT08id&response_type=code&redirect_uri=%22msn.aspx%22

    and throwing error :

    *************************************************************************************** :
    Server Error in ‘/’ Application.
    Runtime Error
    Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

    Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a “web.config” configuration file located in the root directory of the current web application. This tag should then have its “mode” attribute set to “Off”.

    Notes: The current error page you are seeing can be replaced by a custom error page by modifying the “defaultRedirect” attribute of the application’s configuration tag to point to a custom error page URL.

    I am using correct Key and ID. Please suggest me which may be the problem

    Thanks
    Suman

    • Hi,
      I have solved previous problem and now can go to MSN for password verification and it is also returning to my website. But after that nothing happening. I have checked with Response.write and it is showing total emailList array length is 0, but already I have multiple contact at my Hotmail contacts ( have exported CSV file).

      My test link as http://emailcontacts.blooddonornetwork.com/default.aspx

      Will be very helpful if you can solve the problem.

      Thanks
      Suman

      • Hi, i am not able to open this link . just check if your contacts contains “@” because we are checking this . See our code . ” if (strOutput.Contains(“@”))
        emaillist.Add(strOutput); “

  10. Hi,
    Sorry I forgot about this link and changed URL. Code is on below link

    http://test.blooddonornetwork.com/default.aspx

    Here I have commented this line from code and has added few Response line for trace code.

    Please help to solve the issue.

    Thanks
    Suman

  11. krishna says:

    hai can you please provide the sample code plese send it to krishnakanth99999@gmail.com

    • krishna says:

      hey this code is not working i tried..

      • Hi Krishna
        Are you using same code as provided above or any other code because it was not working for me. Can you share your code if this is different?
        If you have any code for google or facebook to get contacts can you please share it.

        Thanks
        Suman

  12. CHAARI says:

    Hello,
    I have this error message on one of exceptions : “There was an error deserializing the object of type OAuthToken. Encountered unexpected character ‘<'"
    Can you please help me to solve this problem?
    Thanks,
    Mohamed

    • CHAARI says:

      The error is in this line :
      token = serializer.ReadObject(response.GetResponseStream()) as OAuthToken;

      Can you please help me?

      Thanks.

    • CHAARI says:

      Hello,
      I understand the problem is that the response sent by Windows Life is the error page indicating that “Windows Life Is not available”.
      I would like to know if, in this code, I just must change these 3 lines?

      private const string clientId = “YOURCLIENTID”;
      private string Callback = “URL Of Your Page Where You Want To Redirect From Msn”;
      private const string clientSecret = “YOURCLIENTSECRET”;

      Thanks.

      • Hi CHAARI,

        can u please explain how u fixed that error . i m also getting same error

        “There was an error deserializing the object of type OAuthToken. Encountered unexpected character ‘<' "

        Thanks.

  13. Hi Friends
    Any one can able to retrieve contacts from the above code, I never can. If any one can do it please help me to solve this problem.

    I can see two things in code and for that getting error while compile.

    See class constructor has defined by below way

    “public MsnImport(int agentid)”

    However there has no use of parameter and while creating MsnImport class’ object not proving any values. I have just deleted parameter from constructor but finally no return from MSN.

    MsnImport msnImport = new MsnImport();

    Please help me to solve the issue. I have hosted my code at below url:

    http://alap.me/msn.aspx

    Thanks
    Suman

    • parvez ahmed says:

      Yes friend.
      I am facing the same problem in my app.
      u got any solution ..
      please help

    • parvez ahmed says:

      There was an error deserializing the object of type OAuthToken. Encountered unexpected character ‘<'….
      please help…

  14. saul says:

    Can you write for Import Facebook Contacts in C#

  15. shah faisal says:

    Hi,
    I used this code but its not works for me.

    When i Show email list it displays nothing, so i count contacts email list it also displays zero.
    I have contacts in account and contains @ also …
    So can u please help me why this is happen.

  16. parvez ahmed says:

    hi..
    this is simple and good code bt return null value for me.
    please help me urgently.

  17. Kaushik says:

    hi can you please send me the sample code for this example.my id is kaushik.jsh@gmail.com
    thanks

  18. Kaushik says:

    here was an error deserializing the object of type OAuthToken. Encountered unexpected character ‘<'….
    I am not getting accesstoken
    please help…

  19. srikanth says:

    Hiii plzzzz i need it urgent can u send me the complete working source code to my email id: srikanthtumkunta@gmail.com… Thanks in advance..

  20. Vidushi says:

    hiee..i am getting d same error :There was an error deserializing the object of type OAuthToken. Encountered unexpected character ‘<'.

    plz solve it..its really urgent

  21. Molly says:

    hi!,I like your writing very so much! share we be in contact extra approximately your post on AOL?

    I need a specialist in this house to solve my problem.

    Maybe that’s you! Taking a look forward to see you.

  22. Eileen says:

    I have been exploring for a little bit for
    any high quality articles or weblog posts on this kind
    of house . Exploring in Yahoo I ultimately stumbled upon this web site.
    Studying this info So i am satisfied to exhibit
    that I’ve a very good uncanny feeling I discovered exactly what I needed.
    I most indisputably will make certain to do not fail to remember this site
    and give it a glance on a continuing basis.

  23. i m getting nothing after login hotmail
    callback url returns normal Default.aspx?code=2e1a7ad9-5401-739e-5723-46105bd580de

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s