LinkedIn Authentication in ASP.Net

For LinkedIn Authentication I have utilized LinkedIn Rest API which use oAuth 1.0 to authorize users and begin making REST API calls using any programming language. Complete understanding tutorials are placed at https://developer.linkedin.com/documents/oauth-overview

Following are the steps to implement LinkedIn Authentication in ASP.Net

Step 1 Installations

  1. Install Hammock Library from CodePlex.com, Hammock is a REST library for .Net that greatly simplifies consuming Restful services.
  2. Configure NuGet (optional to ease referencing code plex libraries directly in Visual Studio project). You can also get the NuGet from http://nuget.codeplex.com/

Step 2 Create LinkedIn Application in LinkedIn developer platform

  1. Go to https://www.linkedin.com/secure/developer
  2. Sign in with your LinkedIn credentials.
  3. Click on Add New Application and fill in the form.
  4. Once your application is created note the API Key and Secret Key that we will use to implement LinkedIn authentication in our application.

Step 3 Create ASP.Net Application

  1. Open Visual Studio and create a new Web Application project.
  2. Add references to Hammock library either by manually referencing from folder or just referencing through NuGet in Visual Studio Directly as shown below.

    Following are the Hammock assemblies we will utilize in the project.

  3. In the Default.aspx page add a button to login with LinkedIn and in that button’s click event call RequestTokenAndAuthorize method which is shown below.
  4. In the Default.aspx page create a new Method named RequestTokenAndAuthorize and place following code.

    public
    void RequestTokenAndAuthorize()

    {


    var credentials = new Hammock.Authentication.OAuth.OAuthCredentials

    {

     CallbackUrl = http://localhost/LinkedInAuthWebSite/Callback.aspx”,

     ConsumerKey = “API Key”,

     ConsumerSecret = “Secret Key”,

    Type = Hammock.Authentication.OAuth.OAuthType.RequestToken

    };


    var client = new Hammock.RestClient

    {

    Authority = https://api.linkedin.com/uas/oauth”, Credentials = credentials };


    var request = new Hammock.RestRequest { Path = “requestToken” };

    Hammock.RestResponse response = client.Request(request);


    String[] strResponseAttributes = response.Content.Split(‘&’);


    string token = strResponseAttributes[0].Substring(strResponseAttributes[0].LastIndexOf(‘=’) + 1);


    string authToken = strResponseAttributes[1].Substring(strResponseAttributes[1].LastIndexOf(‘=’) + 1);

    Session[“Token”] = token;

    Session[“TokenSecret”] = authToken;

    Response.Redirect(https://www.linkedin.com/uas/oauth/authorize?oauth_token=” + token);

}

CallBack URL will be called when the authorization is successfully done by LinkedIn.

  1. Now Create a CallBack page where the callback takes place when the authorization is done after successful login. In my case I have created a Callback.aspx.
  2. In the Callback page place following code in the Page_Load method.

protected
void Page_Load(object sender, EventArgs e)

{


String verifier = Request.QueryString[“oauth_verifier”].ToString();

Session[“Verifier”] = verifier;


var credentials = new Hammock.Authentication.OAuth.OAuthCredentials

{

 ConsumerKey = “API Key”,

 ConsumerSecret = “Secret Key”,

Token = Session[“Token”].ToString(),

 TokenSecret = Session[“TokenSecret”].ToString(),

Verifier = verifier,

Type = Hammock.Authentication.OAuth.OAuthType.AccessToken,

 ParameterHandling = Hammock.Authentication.OAuth.OAuthParameterHandling.HttpAuthorizationHeader,

 SignatureMethod = Hammock.Authentication.OAuth.OAuthSignatureMethod.HmacSha1,

Version = “1.0”

};


var client = new
RestClient { Authority = https://api.linkedin.com/uas/oauth”, Credentials = credentials, Method = WebMethod.Post };


var request = new
RestRequest { Path = “accessToken” };


RestResponse response = client.Request(request);


String[] strResponseAttributes = response.Content.Split(‘&’);


string token = strResponseAttributes[0].Substring(strResponseAttributes[0].LastIndexOf(‘=’) + 1);


string authToken = strResponseAttributes[1].Substring(strResponseAttributes[1].LastIndexOf(‘=’) + 1);

Session[“AccessToken”] = token;

Session[“AccessSecretToken”] = authToken;

 GetUserProfile();

}

  1. GetUserProfile method is used to get the Logged in User First Name and Last name to display on Callback page.

public
void GetUserProfile()

{


var request = new
RestRequest

{

Path = “~”

};


var credentials = new Hammock.Authentication.OAuth.OAuthCredentials

{

Type = Hammock.Authentication.OAuth.OAuthType.AccessToken,

 SignatureMethod = Hammock.Authentication.OAuth.OAuthSignatureMethod.HmacSha1,

 ParameterHandling = Hammock.Authentication.OAuth.OAuthParameterHandling.HttpAuthorizationHeader,

 ConsumerKey = “API Key”,

 ConsumerSecret = “Secret Key”,

Token = Session[“AccessToken”].ToString(),

 TokenSecret = Session[“AccessSecretToken”].ToString(),

Verifier = Session[“Verifier”].ToString()

};


var client = new
RestClient()

{

Authority = http://api.linkedin.com/v1/people”, Credentials = credentials, Method = WebMethod.Get

};


var MyInfo = client.Request(request);


String content = MyInfo.Content.ToString();


var person = from c in
XElement.Parse(content).Elements()


select c;


String fullName=String.Empty;


foreach (var element in person)

{


if((element.Name == “first-name”) || (element.Name==“last-name”))

 fullName += element.Value.ToString();

}

lblName.Text = fullName;

}

Step 4 Run the Application

  1. Run your ASP.Net web application.
  2. Click on the Login via Linked In button to authenticate through linked in. (This button was manually added in the default.aspx page above).

  3. Application requests the RequestToken based on the API key and Secret key and displays the LinkedIn login form as below

  4. Enter your Linked In Credentials and press “Ok, I’ll Allow It”
  5. It will fetch the Access Token and get the User profile and displayed it in the Callback.aspx page.

Publishing Workflow as WCF Service

This post covers the basic step to publish worklfow as a WCF Service.

1. Open Visual Studio, create new project and select Sequential Workflow Service Library template. Specify name as WFSequentialServiceLibrary and press Ok.

2. It will automatically adds IWorkflow1.cs (Service Contract) and Workflow1.cs (Workflow). Rename the IWorkflow1.cs to IDemoWorkflow.cs and DemoWorkflow.cs. It also adds ReceiveActivity which is used to call WCF methods (Operation contracts). You can easily configure the ReceiveActivity from the designer and map the Interface and Method which will be called from the Workflow.

3. Now expand the property section and specify “DemoWorkflow” in the “value” and “return value” properties of an activity.

4.  Now add a WCF Service Application project.

5.  In WCFServiceApp project add reference to the WFSequentialServiceLibrary project.

6. Open Service markup and specify the DemoWorkflow in the Service attribute and add Factory attribute as shown below.

<%@ ServiceHost Language=”C#” Debug=”true” Service=”WFSequentialServiceLibrary.DemoWorkflow” Factory=”System.ServiceModel.Activation.WorkflowServiceHostFactory”  %>

Factory attribute is necessary to specify here when publishing workflow as WCF service.

7. Open web.config file of WCFSeviceApplication and define basicHttpContextBinding rather than basicHttpBinding

 <services>
      <service name="WFSequentialServiceLibrary.DemoWorkflow" behaviorConfiguration="WcfServiceApp.Service1Behavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="basicHttpContextBinding" contract="WFSequentialServiceLibrary.IDemoWorkflow">
          <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>

8.  Now add another windows project from where we will call the WCF method and it executes the workflow.

9. Now add Service reference to the WCF Service Library.

10. Now add a button and add a code snippet in that event.

WcfServices.DemoWorkflow.DemoWorkflowClient client = new WcfServices.DemoWorkflow.DemoWorkflowClient();
MessageBox.Show(client.GetData(5));

11. Now when run the application system will display the empty message box. This is because we have not specified any value in the Return property getter in workflow.

12. Now go to the Workflow project and soecify the return value.

13. Let’s run now, it will show you the entered no. in a message box.

Inspecting Messages in WCF

In WCF (Windows Communication foundation)  you can inpect the messages before sending reply and recieves client request through IDispatchMessageInspector interface. This helps the developer to investigate the message and log somewhere when needed.

In this post i will show the way of implementing IDispatchMessageInspector interface and how it can be applied in the custom behavior extension and configured for that Service behavior.

First of all you have to create a Message inspector class and implement the interface i.e. IDispatchMessageInspector. IDispatchMessageInspector interface provides two methods namely AfterReceiveRequest and BeforeSendReply which you can implement in the implementor class and inspect the messages. As the method named AfterRecieveRequest is called when the request came from the client and BeforeSendReply is called before the service sends the message back to client.

Below code snippet shows the class that implements IDispatchMessageInspector interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.Diagnostics.Eventing;
namespace WCFMain
{
    public class MessageInspector :  IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, 
          System.ServiceModel.IClientChannel channel, 
          System.ServiceModel.InstanceContext instanceContext)
        {
            Logger.WriteLogEntry("Inside the AfterRecieveRequest");
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            Logger.WriteLogEntry("Inside Before Send Reply");
        }
    }
}

Inorder to add this Message Inpector we have to create a custom behavior extension class that derived from BehaviorExtensionElement and implements either IServiceBehavior or IEndpointBehavior. In WCF you can either add behavior at Service level or Endpoint level. In this example i will implement IServiceBehavior.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
namespace WCFMain
{
    public class MessageBehaviourExtension : BehaviorExtensionElement, IServiceBehavior
    {

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            Logger.WriteLogEntry("Inside the ApplyClientBehavior");
        }

        public override Type BehaviorType
        {
            get { return typeof(MessageBehaviourExtension); }
        }

        protected override object CreateBehavior()
        {
            return this;
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, 
         System.ServiceModel.ServiceHostBase serviceHostBase, 
         System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
         BindingParameterCollection bindingParameters)
        {
            Logger.WriteLogEntry("Inside the AddBindingParameters");
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, 
         System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            Logger.WriteLogEntry("Inside Apply Dispatch Behavior");
            for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++)
            {
                ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher;
                if (channelDispatcher != null)
                {
                    foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
                    {
                        MessageInspector inspector = new MessageInspector();
                        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
                    }
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, 
          System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }
    }
}

In the above snippet if you see that i have add the custom message inspector object for each endpoints defined for the service. So when the WCF engine calls this method it will add the message inspector for all endpoints defined in the service configuration.

Now, in the web.config file at server side you have to add following entries to configure this custom behavior extension and specify in the service behavior.

WPF Data Binding Options

In this post i will show the different ways of binding WPF control elements with the different sources. WPF provides binding both declarative and imperatively through code. It provides greater flexibility to the developer to bind the target value to source value in the XAML file.

The term data binding describes the process of creating a dependence for the value of one property i.e. the target property to the source property. The target property takes on the value of the source property. In some cases, changes to the source property are transmitted to the target immediately, but in some cases, they are not.

Following are the types of bindings that are the part of this post and mostly used in WPF applications.

1. Binding target value to WPF element.
2. Binding to an Object
3. Binding to Ancestor properties through RelativeSource property.
4. Binding to Data Sources
5. Binding to an Object with ObjectDataProvider

1. Binding Target value to WPF Element:
This type of binding used when you want to bind the target property to any WPF element (control) property. For e.g. you want to bind the Textbox text to the label Content property. When the user write in the textbox it should reflect the change in the label control. In this case, you add a textbox and a label controls in the WPF form. And specify the binding as follows.

Above code snippet shows the binding of Label Content target property with the Textbox Text source property. Now when you run the application and write something on textbox it will directly reflect the changes on the Label.

2. Binding to an Object
When binding to an Object we use Source property to specify the source object. For binding with object, in the Window.Resources tag user has to specify the Resource object. Below code snippet shows the way of binding an Object property with the resource object.

The above code snippet binds the StaticResource to the personObj which was defined in the Window.Resources tag and Path specified the property which holds the value. Now when run the application it will bind the TextBlock text value with the property value. When the form loads it initialize an object and fill the value obtained from that object property. If you want to pull data from some other datasource at runtime then you don’t need to specify the Binding Source property and only have to specify the Path property and in the code behind bind the TextBlock text source to that object value.

You can also specify the StaticResource binding property over Grid level or at container level. So you don’t need to specify the static resource property on every control bindings. All the controls that come under that container will use that datasource. But you need to specify the path which maps the property to that object property. Following snippet shows the way of binding through DataContext property at Container level.

3. Binding to Ancestor properties through RelativeSource property
Using the RelativeSource attribute in the binding you can bind the source to the ancestor property value. For example you have specified the Tag attribute in the Grid container. And you want to bind the Tag property in the Textbox control that comes under grid container. You can do that by using RelativeSource property. Following code snippet shows the way of binding to ancestor properites through RelativeSource property.

4. Binding to Data Sources

This is when you want to bind the Collection controls like Listbox etc. with different datasources.ListBox in WPF contains an ItemSource property which helps to bind the datasource. Normally in business application collection retrieves from database. So you dont need to specify the Source property in the Listbox ItemsSource property and just specify the Binding keyword followed with the DisplayMemberPath which is used to map the object property retrieved from the Collection to the control display item property.

Following code snippet shows the binding.

5. Binding to an Object with ObjectDataProvider

Using ObjectDataProvider class you can bind a WPF element to a method called on an object. You can specify an object type and a method on that type. WPF also provides an option to bind methods that have parameters in its signature and  user can define the method parameters declaratively in XAML with their default values.

Below code snippet shows the way of binding method that contains no parameters in its signature.

In the code above first i created a method named GetText which return some string. And then I have specified the ObjectDataProvider tag and reference it in the TextBlock.

Below code snippet shows the way of binding method that contains two parameters in its signature.

Define method.

Specify ObjectDataProvider in the XAML.

When run the Application and enter the data in two textboxes, the Concat method takes the values from those textboxes and bind the returned concatenated string with the TextBlock as shown below.

Using Facebook SDK in Desktop Application C#.Net

This post shows the basic way of using Facebook SDK C#.Net in Desktop/Windows based application to authenticate user and enable developers to access the complete data of the logged in user.

First of all developer has to create an application in http://www.facebook.com/developers. This is very simple and can be done in seconds. Following are some basic steps.

1. Login http://www.facebook.com/developers

2. Click on a link named as “Set Up New App”.

3. Specify Application Name, in my case its “Test”. Click on ‘Create App”.

4. Once the application is created select the “Website” tab and note the “Application Key”. This Application Key will be used to connect to the Application using Facebook SDK.

Now we have configured and created an application and perform different operations from our desktop application. Following are the steps to develop a basic desktop application that authenticate user and populates his full name and gender in the text fields.

First of all download the provided at CodePlex forum.

1. Open Visual Studio

2. Create Windows Application

3. Download the Facebook Developer SDK from Facebook Developer SDK and add References to the Facebook Developer Kit, through NuGet (gives you an option to reference third party library packages) or add Facebook.dll and Facebook.WinForms.dll manually.

4. Open Visual Studio and Create a new tab in Toolbox section e.g. “Facebook Control” and click on “Choose Items” and browse the “Facebook.Winforms.dll” file.

5. On selection, It will show the list of controls embedded in that assembly, just click on Ok to add it in your IDE toolbox section.

6. Now drag and drop the FacebookService as shown below.

7. Add a button that performs Authentication first, and then get the User details. Also place two text boxes.

8. Now set the Application Key in the Application Key property of FacebookService control as shown below.

9. Now in the button click event place following snippet that connects to facebook and displays the username and email address on the form.

facebookService1.ConnectToFacebook();
txtUserName.Text = facebookService1.Users.GetInfo().first_name + " " + facebookService1.Users.GetInfo().last_name ;
txtGender.Text = facebookService1.Users.GetInfo().sex;

10. Now when run the application and click on the “Connect to Facebook” button it will show the Facebook login screen, enter valid username and password.

11. On Authentication, it will prompt to allow/don’t allow to use Facebook from Test application. Click Allow.

12. Then it will display the user name and gender of the logged in user.

You can also get friend list, update status, retrieve photos, and bunch of more operation that are provided in the SDK.

C# 4.0 New Features: Optional Parameters in Methods

Microsoft has provided several new features in .Net 4.0 and among them one which i found a very useful and handy is that now instead of making overloaded methods developer can just make a single method and make the parameters as optional.

Following OOPs people used to write overloaded methods for handling multiple parameters in different way. Lets suppose you have a method named Execute() and following are the overloaded methods.


void Execute(int a){}
void Execute(int a, int b){}
void Execute(int a, int b, int c){}

Using .Net framework 4.0 you dont need to create multiple overloaded methods and you just have to create one as follows.


void Execute(int a, int optionalB = 0, int optionalC = 0)
{

}

And it can be called as follows.


Execute(1);
Execute(1,2);
Execute(1,2,3);

We can also pass the parameters in different orders considering the same method as follows.


Execute(optionalB: 2, optionalC: 3, a:1);

You only need to denote the parameter name followed with a colon and the framework automatically sets the value to that order parameter have in the method signature.

Utilizing LINQ to SQL in Multi Tier Architecture

Normally LINQ to SQL seems to be designed for 2 -tier program, especially when we use Visual Studio to visually create entities and DataContexts. No doubt, this is a very rapid way of developing a data access layer and using its classes for data operations. But when developing an enterprise application which is divided into multiple layers i.e. Data Access Layer, Business Layer, Service Layer and Presentation layer, etc. then developer gets confused in separating the business objects with the data access layer and to make them loosely coupled.

However, in order to utilize the LINQ to SQL for enterprise architecture I did some R & D and came to know that there are some methods supported by LINQ to SQL which helps to design a data access layer that is independent with the business objects. This helps the developer to use the same business objects even they are data contracts (specifically when talking in terms of WCF framework) or any other common business types.

Below procedure shows the way you can utilize the LINQ to SQL in multi tier architecture.

1. Create a Data Types layer which contains all types of business objects.
2. Create an empty BaseEntity class by which all the business objects will be inherited from. You can also put common properties under BaseEntity class like CreatedOn, CreatedBy, UpdatedOn, UpdatedBy usually common in all business objects.

public class BaseEntity
{

}

3. Now create a business object in our example its “Condition” class. [Note the property name should be equal to the result set column names of the procedure being called].

public class Condition :BaseEntity
{
Int32 conditionId;
public Int32 ConditionId
{
get { return conditionId; }
set { conditionId = value; }
}

String conditionName;
public String ConditionName
{
get { return conditionName; }
set { conditionName = value; }
}

String conditionDescription;
public String ConditionDescription
{
get { return conditionDescription; }
set { conditionDescription = value; }
}
}

4. Now create a Data Access Layer. Create a class Library Project and add LinqToSql, you may notice that .dbml file will be added into the solution. This provides the datacontext classes available to perform data operations.

5. Next, create a PersistanceManager class and adds following method. Here I have developed a wrapper of LINQ to SQL ExecuteQuery which provides the automatic binding of the type T and returns the List of T.

public List ExecuteQuery(String queryName, params Object[] param) where T : DataTypes.BaseEntity
{
List lst = new List();
using (DDMSDataContext context = new DDMSDataContext())
{
var items = context.ExecuteQuery(typeof(T), queryName, param);
foreach (var item in items)
{
T t;
t = (T)item;
lst.Add(t);
}
}
return lst;
}

As shown above, this method executes the procedure with the parameters supplied and returns the business object List to user. Once this is done you can call this method from Business layer or any other layer as follows

public List GetAllMedicalConditionsByConditionType(Int32 TypeId)
{
List lstMedConditions = PersistanceManager.GetInstance().ExecuteQuery("Exec SelectAllActiveMedicalConditionsByConditionType {0}", TypeId);
return lstMedConditions;
}