Saturday, 17 September 2011

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

4 comments:

  1. will you please tell me which dll files are required for using linked in Namespace??

    ReplyDelete
  2. hi,its not working..
    i want the contacts from linkedin..pls. kindly send me the code..its urgent

    my mail id call2sushant@gmail.com

    ReplyDelete
  3. please any one have an idea importing linkedin contacts into skype code on C#.plz

    ReplyDelete
  4. without proper explanation just by posting code does't help

    ReplyDelete