Handling User Control Events in ASP.Net

Although most of the developers know how to handle events of User Controls, but this will help for those developers who never came across with this before and wants to learn with a simple example that details about handling custom user control events on aspx pages.

What are User Controls?

User controls are just like standard ASP.Net webform with few limitations. It contains a designer view where the user can drag and drop existing controls of ASP.net or third party to structure that user control. In order to learn more about User control you can follow this link http://msdn.microsoft.com/en-us/library/y6wb1a0e(v=vs.100).aspx

Handling custom developed User Control Event

Let suppose we have a user control containing a textbox and a button. And we have an aspx page where we are using that control. Now inorder to handle the button click event of the User control’s button click event on aspx page we will go through the following steps.

Following is a code snippet of User Control named “ctrlCustomUserControl.ascx”

<%@
Control
Language=”C#” AutoEventWireup=”true” CodeBehind=”ctrlMyUserControl.ascx.cs” Inherits=”WebApplication7.ctrlMyUserControl”
%>

<asp:TextBox
ID=”txtBox” runat=”server”></asp:TextBox>

<asp:Button
ID=”btnClickMe” runat=”server” Text=”Click Me!”


onclick=”btnClickMe_Click”
/>

You can see there are two controls placed, one is textbox and the other is button.

Code behind file looks like as follows


public
partial
class
ctrlMyUserControl : System.Web.UI.UserControl

{


public
delegate
void
ClickHandler(object sender, EventArgs e);


public
event
ClickHandler Click;


protected
void btnClickMe_Click(object sender, EventArgs e)

{

Click(sender, e);

}


public
String Text

{


set { this.txtBox.Text = value; }

}

}

 Above code shows that there is a delegate named ClickHandler and I have declare its event named Click. And I have also registered the button click event and called my custom Click event there, which will be registered by the ASPX page will be invoked from this event.

Now, lets look into the “Default.aspx” page where I am using this control.

<%@
Page
Title=”Home Page” Language=”C#” AutoEventWireup=”true”


CodeBehind=”Default.aspx.cs” Inherits=”WebApplication7._Default”
%>

<%@
Register
Src=”~/ctrlMyUserControl.ascx” TagName=”MyControl” TagPrefix=”uc”%>

<form
runat=”server”>


<uc:MyControl
id=”myctrl” runat=”server” OnClick=”myctrl_click”></uc:MyControl>

</form>

Second statement shows the registration of my custom user control on aspx page, tagprefix and tagname values are used to define control tag.

I have used uc as the tagprefix and MyControl as tagname. You can see how I have specified the markup of custom user control. One important thing, you can see that I have specified OnClick event. Actually if you recall the control code behind file there I have an event named “Click” and inorder to register it on any aspx page we have to add a prefix “On” i.e. “OnClick”. This is how we can register custom events of user the control on aspx page.

Code behind of Default.aspx is as follows


public
partial
class
_Default : System.Web.UI.Page

{


protected
void myctrl_click(object sender, EventArgs e)

{

myctrl.Text = “Hello World!”;

}

}

When user click on the button, it will populate “Hello World!” text on the text box.


Happy Coding!


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&#8221;,

     ConsumerKey = “API Key”,

     ConsumerSecret = “Secret Key”,

    Type = Hammock.Authentication.OAuth.OAuthType.RequestToken

    };


    var client = new Hammock.RestClient

    {

    Authority = https://api.linkedin.com/uas/oauth&#8221;, 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=&#8221; + 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&#8221;, 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&#8221;, 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.