ASP.NET 4.5 – Control display format of Data in Model Binding

I have written few posts on ASP.NET 4.5. One of the best feature I liked that is Model Binding that is almost similar to ASP.NET MVC. This is another feature of Mode binding in ASP.NET 4.5. For better understanding and usage, you should have some knowledge on this basic feature . You can refer my earlier posts on model binding at the links below

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 1

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 2

Now if your model is getting populated using entity framework or in any other way from the database then normally we apply some kind of formatting before displaying the data on the User Interface. Because the way data is stored in database and the way it is displayed on UI is quite different. We transform the data in a friendly, easy and some time in their Locale before displaying. Like say I have a number 100000 stored in database but we display it is 100,000 or displaying the number in specific format. So let’s take an example

I have created a class Employee as

public class Employee
{
    [Required()]
    public int Id { get; set; }
    [Required(), StringLength(30)]
    public string FirstName { get; set; }
    [Required(), StringLength(30)]
    public string Lastname { get; set; }
    [Required(), StringLength(30)]
    public DateTime DateJoined { get; set; }
    [Required(), Range(5, 1000)]
    public int Salary { get; set; }
}

Now let’s see the aspx page

    <div style="font-family:Verdana; font-size:small">
     <asp:DetailsView ID="detailsViewEmployee" runat="server" SelectMethod="GetEmployees"
       InsertMethod="InsertEmployee"  UpdateMethod="UpdateEmployee" AutoGenerateInsertButton="true"
       AutoGenerateEditButton="true" ItemType="Employee" ></asp:DetailsView>
     <asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true"/>
    </div>

Here I am using details view and provided the ItemType as Employee, SelectMethod, InsertMethod and UpdateEmployee methods. The code behind of the file is as

    List<Employee> employees = new List<Employee>();
    protected void Page_Load(object sender, EventArgs e)
    {
        Employee emp = new Employee()
        {
            Id = 1001,
            FirstName = "Brij",
            Lastname = "Mishra",
            Salary = 100000,
            DateJoined = new DateTime(2012, 12, 12)
        };

        employees.Add(emp);
    }

    public IQueryable<Employee> GetEmployees()
    {
        return employees.AsQueryable();
    }
    public void InsertEmployee(Employee e)
    {
        if (ModelState.IsValid)
        {
            employees.Add(e);
        }
    }
    public void UpdateEmployee(Employee e)
    {
        // Update the employee
    }

Now let’s run the code

WithoutDIf you see the encircled area in above screenshot, one is date format and other is a number. One may want to display it in some friendly format. One way to transform the data before displaying and other is to use DisplayFormat Attribute. DisplayAttribute is applied on model so here I am going to apply it on DateJoined property of Employee class asDateJoinedhere we have added the DisplayFormat attribue and provided DataFormatString. This string is used to format the string before displaying it. Let’s add DisplayFormat attribute to salary property as

salaryHere also, We provided a different format string for number. Now let’s run it

formattedNow if you see that Date and number is properly formatted. We just required to add one attribute and provide the format string that is used to format the data.

DisplayFormat attribute provided some more very useful properties. Few of them

  • ApplyFormatInEditMode- Provide this property in attribute and set it true. It will format the data when the form will be in edit mode as well else you’ll loose the formatting in edit mode.
  • NullDisplayText- If any property is null and you want to show some default text then it is very useful. Just provide the string and it’ll be displayed if that property is null
  • ConvertEmptyStringToNull – If you want to convert empty string treated as null then set it true.

Hope you have enjoyed the post and you’ll use the power of DisplayFormat attribute in your ASP.NET 4.5 projects.

Thanks,
Brij

ASP.NET 4.5 : Login using other Authentication Providers Simplified

In this Post, I am going to discuss one of the other new features of ASP.NET 4.5. That you’ll like. I’ll also try to make it simple and include step by step tutorial so that you can implement at your environment.

Now a days, you guys must have seen that almost all leading websites allow you to login with your other accounts/credentials. It may be Facebook, Gmail, Twitter, Microsoft and many other.

I like this feature very much because a user don’t need to register on every website where s/he wants to login and reduce the login credentials count drastically and make life simpler.

So Facebook, Gmail, Twitter… works as Identity provider that provides there APIs that one can integrate with there application and allow user to login with their Facebook, Twitter, Gmail… accounts. There are various ways to implement it and they work on some standard protocols so that everybody can understand their API.

Currently, most leading identity provider follow OAuth standards and OAuth provides a process for end-users to authorize third-party access.

So now let’s come to ASP.NET. ASP.NET 4.5 new template has the required code already in place that you require to write to uses the third party Identity provider. You just need to enter some required Ids and secret keys and once you provide it. It’ll start working.

So let’s first create a ASP.NET application as FILE|NEW|Web Site|ASP.NET Web Forms Site. Now if you open the solution explorer, It has created lots of files and that provides many feature already implemented, you must have seen in earlier version as well. I assume you have basic Idea about all that.

Now let’s open a file under App_Code/AuthConfig.cs. Now if you check this file has several lines of commented code. If you see that closely, then actually it adding authentication clients like Twitter, Facebook, Microsoft, Google . Now here, you need Id and secret keys for the authentication clients that you need to provide.

So I have uncommented the code for two authenticated clients Twitter and Google. And I have put my Twitter  key and secret key while Google doesn’t require any. Now as soon as,  you run the application and click on login link at right top, you ‘ll see below

Login

You can see two buttons Twitter and Google. A user can use these accounts to login. Let’s click on twitter.

Twitter Login

It took me on the above page and I entered here my Twitter account and clicked on sign in and it took me at the following page

AfterLogin

here I can change my my user name and I changed it as Brij. As soon as I click on login, I am authenticated and you can see that I am now loggedin.

LoggedinWithTwitter

Now if you click on the user name (Brij) shown in above pic right corner, It shows the following page.

twitter-ResetPwd

It allows you to set a local password. After setting your local password you won’t need to your login via Twitter  to authenticate the current website. Now if you see the last section, it shows twitter account which is used for login.

You can login with other account as well at same point of time. As, I have enabled the two authentication providers Twitter and Google, you are seeing both of these two at last section . And when I click on Google it takes me at Google login page. As soon as I put my credential and click on Sign in button. It shows me that I am logged in as using two accounts. Twitter and Google as

Loggedinwithtwoaccount
Also, you can see after login with two accounts, it shows a remove button to remove any authentication. And as soon as you’ll click on any remove button that authentication will get removed and other remove button will also be removed. Because for login, at least one authentication is required.

Now I’ll tell you, How I created Ids and secret for my local App. To create appId and secret from Twitter go to link TwitterApp .

Once you click on the following the below steps:

  1. Click on Create a New Application
  2. Put the name and description of your application.
  3. Now, put the URL of the your local application. A caveat,  you cannot put the URL generated by Visual Studio integrated server. So host your application at local IIS but twitter wont accept localhost URL as well. You need to have some URL that be hosted on some domain. So how can you mimic that scenario on your local server. I have found a interesting testing domain localtest.me . This is not localhost.me but localtest.me.
    So to set the domain, Go to IIS->Default Web Site. Right Click Default Web Site and Click on Edit Bindings. Here I added a Site Binding (localtest.me)  by Clicking on Add button. I just entered the Host Name localtest.me as

AddBinding

So my application URL for twitter was http://localtest.me/testdomain/Default.aspx.

So once you’ll put all these and save. You’ll get Key and Secret that you can use for your ASP.NET 4.5 local application.

So you have seen, How ASP.NET 4.5 simplified our life by providing inbuild mechanism for using other leading authentication providers. We as developer don’t need to worry about underlying complex logic. Just need to provide some AppIds and Secrets and Google does not require any Id and secret as well.

Hope you all have enjoyed.

Happy Learning,
Brij

FriendlyURL : A new and exciting feature of ASP.NET

This is going to be the last post of 2012 by me. I am very happy that I am writing about a very exciting feature that is coming with ASP.NET.

I am really excited to learn and write on this. I really hated the ugly URLs and the extensions of the page that always visible when one opens the application unless and until you write your own custom url processor. With ASP.NET 4.0, Routing was introduced, which provided the capability to ASP.NET to have easier, manageable and SEO friendly urls, I wrote a post on it. You can click below to have a look on it.

URL Routing with ASP.NET 4.0

But that is little tidy to write. And it looks like writing extra code that does not produces any business functionality.

FriendlyURL as the name suggests gives a clean and SEO friendly URL.Currently it is available via NuGet and in pre release version.

So For this post, I have used my Visual Studio 2012 IDE. I created a new project as File-> New -> Website -> ASP.NET Empty Website.

Once the project got created. I require to install the NuGet for my application. So got to Tools-> Library Package Manager-> Package Manager Console

Package Manager Console

It opens a console then type Install-Package Microsoft.AspNet.FriendlyUrls -Pre and press enter as

FriendlyURL NugetInstallation

As you can see, I typed the command and can be seen in  the first red encircled area and press enter. It’ll install the NuGet and you can see the last red encircled area which shows FirendlyUrl is successfully added.

This can be used with two ASP.NET versions: ASP.NET 4.5 and ASP.NET 4.0.

Now you are ready for working with friendly URLs.

If you have  read the Readme.text. It gives a clear  idea how to start with. But I’ll take you through the steps. So let’s start

Step 1-> Add and Create a Class name preferably RouteConfig.cs ( You can have any name. I used MyRouteConfig.cs) and make it static. Also add the name space in the class Microsoft.AspNet.FriendlyUrls

Step 2-> Create a static Function in the class preferably named as RegisterRoutes with a Parameter of type RouteCollection and add  a line  routes.EnableFriendlyUrls() in the method as

public static class MyRouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();
    }
}

Step 3-> Add Global.asax file and add the following line in Application_Start as

  void Application_Start(object sender, EventArgs e)
    {
        MyRouteConfig.RegisterRoutes(RouteTable.Routes)
    }

Now you can start the development of your application. I have created two pages First.aspx and Second.aspx in my solution

That’s it. Now your code is ready for run.

First PageIf you see the above circled area in the above pic, it does not contain page extension (aspx). So now the url looks pretty. As an end user, I don’t care about the page extension and even some time it just irritates me.

Now if you want to redirect to another page, you can redirect by typing URL without page extension as

Response.Redirect("~\\Second");

There is one caveat here. You can not have a folder and Page with same name at the same level. If you have the name of a folder and the name of aspx page at same level, you would not be able to access the page without extension. So please keep it in mind.

Now you must have a question in Querystring. What will happen with Querystring?

You don’t need to worry at all. QueryStrings will work as earlier . Let’s have a look to the URL http://localhost:57353/First?Id=1001 then you can read the QueryString as below similar as earlier

string Id = Request.QueryString["Id"] as string;

Next point, if I have a URL say http://localhost:57353/First/Products/NewProduct and there is no page as NewProduct. What will happen It’ll open First.aspx.

But, How it works?

It starts from last segment (NewProduct) and will check if there is any NewProduct.aspx. If not then it moves to next segment and continue till it finds the exact aspx page.

Let’s explore more. Go to the server side of the page and include the namespace Microsoft.AspNet.FriendlyUrls. You’ll get bunch of methods that will be very useful at certain times.

  • Request.GetFriendlyUrlSegments() – It returns a collections of string which represents the URL segments. So if I have a URL http://localhost:57353/First/Products/NewProduct and the page exists First.aspx then it returns.
    URLSegments
    So you can see above, there is two segments and one can iterate through it. These url segments can be used to pass the values to a page via URL instead of QueryString. It also looks pretty.
  • Request.GetFriendlyUrlFileVirtualPath() – It returns the File virtual path. For the URL, discussed in the above example it will show as
    File Virtual Path
    You can see it shows the Virtual path of the file.
  • Request.GetFriendlyUrlFileExtension() -It returns the extension of the file. For the above url, it will be shown as File Extension
    As you can see, the extension of the page. As now with friendly url, the page extension is not shown. You can get the extension by the above method.

There are other important methods/features available that can be used to generate the URL etc. I’ll discuss some of those here

An available class FriendlyURL provides few static functions/properties that is very useful. Let’s see

  • FriendlyUrl.Segments ; Returns the segments of of the current URL similar as returned by Request.GetFriendlyUrlSegments()
  • FriendlyUrl.Resolve : This can be used to resolve the FriendlyUrl
    • FriendlyUrl.Href – It takes few parameters virtual path and list of url segments and generate the friendly URL out of it. And it is very useful while generating the URL in data binding and several other places. We can write
      FriendlyUrl.Href("~/First", "Product", 1001);
      

      And what it will return
      FriendlyURLgeneration

Hope you must have liked this new coming feature of ASP.NET. This will will let you get rid of aspx extension at URL , Frankly speaking, during my earlier days of career, I used to see the extension to check if the website is developed in asp.net.

I find this feature as one of the most of the exciting features of ASP.NET. Hope you all enjoy it and also like the post.

Enjoy and Love ASP.NET. And A very Happy New Year to all.
Cheers.
Brij

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 2

Last week, I wrote the first part of the post Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5. In the first post , I discussed about Strongly typed data control, Model Binding, filtering data, Value Providers and about writing own Custom value provider. Please find the link of earlier post below.

http://brijbhushan.net/2012/07/01/strongly-typed-data-controls-and-modal-binding-in-asp-net-4-5-part-1/

Model Binding feature also supports editing feature. Control’s like Gridview has three properties

  • InsertMethod
  • UpdateMethod
  • DeleteMethod

you can assign a method that has been written at code behind and the method takes a single parameter with the associated type. And the value of the parameter holds the value to be updated. As say if my Control is associated with a Type say Product then the delete method could be as

public void DeleteProduct(Product p)
{
//Write the logic of deleting the passed product p
}

Now, I’ll talk about Model Validation and custom validation attribute. So let’s start.

We all have used ASP.NET validators many times for validating lot of controls and of course used the same of data controls like GridView also. But Model Binding provides another way of implementing validation.

So now you can use System.ComponentModel.DataAnnotations and apply the validation at your model level. And if your control is bound to some model that validation would be taken care. So let’s start with an example. See how can we put different Validation attribute to our class as below

public class Speaker
{
[Required()]
public int Id { get; set; }
[Required(), StringLength(30)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(), StringLength(30)]
public string Lastname { get; set; }
[Required(), StringLength(30)]
public string ExpertArea { get; set; }
[Url ()]
public string blogURL { get; set; }
[Required(), Range(5,1000)]
public int LastYearSessionCount { get; set; }
public string Email { get; set; }
}

As I put Id as required attribute, it means it is required and if it is not provided it’ll throw an error.

DataAnnotations provides other kind of validations like Range,  StringLength etc as well. Also we can have multiple attributes as well on any property to have multiple validations on same Value as you can see above.

I have used a DetailsView and used this class as model for that DetailsView control as

<asp:DetailsView ID="detailsViewSpeaker" runat="server" SelectMethod="GetSpeakers" InsertMethod="InsertSpeaker" AutoGenerateInsertButton="true"
ItemType="Speaker"></asp:DetailsView>

You must have used ValidationSummary control earlier. Now this control has one more property called ShowModelStateErrors which need to be set as true. This will be enable the page to display all model related errors as

<asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true"/>

Now let’s run the page

You can see the above screen, all the validation errors are Mode state errors.

This is not at all, if your requirement does not get fulfilled by the in built validation attribute then you can write your own custom attribute as well. To create a custom attribute, you need to implement ValidationAttribute and override IsValid method and need to put own custom logic in this method only. lets create a custom validation attribute.

In my example, I have written custom logic for validating an email. Let’s have a look

public class MyCustomValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
Regex regex = new Regex(MatchEmailPattern);
return regex.IsMatch(value.ToString());
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString, name);
}
}

We can also tweak the default validation message by overriding FormatErrorMessage as I have done above. Now Let’s use it in my model. As

public class Speaker
{
[Required()]
public int Id { get; set; }
[Required(), StringLength(30)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(), StringLength(30)]
public string Lastname { get; set; }
[Required(), StringLength(30)]
public string ExpertArea { get; set; }
[Url ()]
public string blogURL { get; set; }
[Required(), Range(5,1000)]
public int LastYearSessionCount { get; set; }
[MyCustomValidation(ErrorMessage = "{0} field custom validation failed. Your email is not in proper format.")]
public string Email { get; set; }
}

Now Let’s run the application

As you can see, I have entered a wrong formatted email. And when clicked on Insert button, the custom validation is error is thrown.

Hope you all have enjoyed this post.

Thanks,

Brij

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 1

Recently, I took  a session on KolkataGeeks and discussed on  ASP.NET 4.5 enhancements. I mainly discussed on changes in data controls and model binding feature added in ASP.NET4.5.

I am going to write a series of post on the same feature here also. Till date, you all must have  had a look on the enhancement and new features introduced in ASP.NET 4.5. The main change in data control that now it provides intellisense support at aspx pages. You need to assign the ItemType property to model that is going to be associated with the data controls. As

Strongly Typed Data Control

These controls are also referred as Strongly Typed Data Controls.

There are also other major changes took place, in the way we provide the DataSource to the our DataControls. Here in my example, I have taken a GridView.

Earlier, we used to provide DataSource to our Data Control and then call DataBind. We used multiple Data Sources like SQLDataSource, ObjectDataSource etc. But now, you have another option which allows us to not set DataSource property and call the DataBind specifically.

There is a property got introduced named as SelectMethod. We can write our own method at server side and assign the method to this property. One thing, we need to take care that it must return the collection of objects and it should be either IEnumerable or IQueryable. Server side method could be as

public IQueryable<Product> GetProducts()
{
return dbcontext.Products.AsQueryable().OrderBy(i => i.Name);
}

And my gridview at aspx

<asp:GridView ID="gridProducts" runat="server" ItemType="AdventureWorksLTModel.Product" AutoGenerateColumns="false"
SelectMethod="GetProducts" >
<Columns>
<asp:TemplateField HeaderText="Product Name" SortExpression="Name">
<ItemTemplate>
<%#Item.Name %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="ListPrice">
<ItemTemplate>
<%#Item.ListPrice %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Color" SortExpression="Color">
<ItemTemplate>
<%#Item.Color %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Now why this method should return only IEnumerable or IQueryable . Controls like GridView provides many features like Paging, Sorting etc. As soon as you assign the method to SelectMethod property. You don’t need to write any special code for Paging, Sorting.. feature. For that it creates Linq  queries on the fly and it can be written only on the collection that implements IEnumerable or IQueryable.

That’s not it, in many cases we provide some kind of filter criteria to the users, based on user can view only filtered data.

ASP.NET4.5 provides many Value Providers that can be used and these value providers are

  • Querystring
  • Session
  • Cookie
  • Control Value
  • Form Value etc..

These value provider can be directly used to filter the data. But how?

These value providers must be passed as a parameter in the method, that is going to be assigned to Select method. Let’s if we want Query String as value provider so we can pass it as

public IQueryable<AdventureWorksLTModel.Product> GetProducts([QueryString("key")]string parameter)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.Where(p => p.Color == parameter).AsQueryable().OrderBy(i => i.Name);
}

where key is the Query String parameter and it can access the value directly in the method as above.

Similarly other value providers can be used. One more example, we can have some control’s value as value provider. For that in my example, I have created a drop down and I want to use drop down’s selected value for filtering the data it can be used as

<asp:DropDownList ID="ddlColors" runat="server" SelectMethod="GetColors" AutoPostBack="true" ></asp:DropDownList>

Above one is my dropdown. And as you can see, It also has SelectMethod, I have assigned it a GetColors method and it is also written as

public IEnumerable<string> GetColors()
{
var colors = (from c in dbcontext.Products
where c.Color != null
select  c.Color).Distinct();
return colors.ToList();
}

Now my SelectMethod method for gridview is

<pre>public IQueryable<AdventureWorksLTModel.Product> GetProducts([Control]string ddlColors)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.Where(p => p.Color == ddlColors).AsQueryable().OrderBy(i => i.Name);
}

You can see the parameter name and it is ddlColors is Id of the dropdown.

Now this is not all. You can also create your own custom value provider. To create your very own Value provider, you need to implement IValueProvider. Here you need to implement a method GetValue which takes a key (string) as a parameter. It returns an instance of ValueProviderResult . It contains the value returned by the ValueProvider.

I created a value provider which takes a value from querystring based on it fetch some data from database and return it. As

public class MyCategoryProvider : IValueProvider
{
private HttpContextBase context;
private string value;
private int limit;
public MyCategoryProvider(HttpContextBase hcb, string val)
{
context = hcb;
value = val;
}

public bool ContainsPrefix(string prefix)
{
throw new NotImplementedException();
}

public ValueProviderResult GetValue(string key)
{
string category = context.Request.QueryString[this.value] as string;
GetPriceLimit(category);
return new ValueProviderResult(limit, limit.ToString(), System.Globalization.CultureInfo.CurrentCulture);
}
}

Now this can not be used directly. Because ValueProvider is used as an Attribute. So now, you need to create a custom attribute which returns the your Value provider.

To Create a Custom attribute you need to inhert from ValueProviderSourceAttribute which is available in namespace System.Web.ModelBinding . Here override the method GetValueProvider which returns the valueprovider. It is wrtitten as

[AttributeUsage(AttributeTargets.Parameter)]
public class CategoryAttribute : System.Web.ModelBinding.ValueProviderSourceAttribute
{
private string code;
public CategoryAttribute(string _code)
{
this.code = _code;
}

public override IValueProvider GetValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
{
return new MyCategoryProvider(modelBindingExecutionContext.HttpContext, this.code);
}
}

Now your custom value provider is ready for use. Let’s use this

public IQueryable<Product> GetProducts([Category("cat")]int parameter)
{
AdventureWorksLTEntities dbcontext = new AdventureWorksLTEntities();
return dbcontext.Products.AsQueryable().Where(p => p.ListPrice <= parameter).OrderBy(i => i.Name);
}

So, you can see that I have used Category as a Value Provider.

Hope you all have enjoyed the post. I’ll discuss more on Validation and other things in my next post.

Cheers,
Brij

Speaking on ASP.NET 4.5 new features

Hello friends,

I will be speaking on ASP.NET 4.5 new features in an online session organized by http://kolkatageeks.com/.

This would be a one hour session, In which I’ll be discussing on the enhancement made in Data Controls and the ModelBinding feature. It will be fully demo oriented session and you’ll enjoy it.

This is an online event and you can join from anywhere if you have PC/Laptop with internet connection.

If you have not registered yourself on http://kolkatageeks.com/ then Register and you’ll get the details.

Time : 20th May 2 PM to 3 PM

 This is absolutely free event.

Session details: http://kolkatageeks.com/WebCast.aspx

Online meeting details will sent registration.

Hope you’ll enjoy it..

Thanks,

Brij

Asynchronous HTTPHandlers with ASP.NET 4.5

In my last post, I discussed about writing Asynchronous HTTPModule with ASP.NET 4.5. You can check the link Below.
Writing asynchronous HTTP Module in ASP.NET 4.5

In last post, I also briefly discussed about the enhancement made in .NET 4.0 and .NET 4.5, that made our life very easy to write asynchronous code. And in ASP.NET 4.5, we can use these features easily.

I also discussed, why at certain situations Asynchronous HTTPModules are important. In the same way, Asynchronous HTTPHandlers can play a vital role in site performance. The working of Asynchronous Handler can be shown as

Asynchronous HTTPHandler

Asynchronous HTTPHandler

As we know if we need to create a normal custom HTTPHandler. We need to implement IHTTPHandler interface and if we want to create a custom Asynchronous HTTPHandler, we need to implement IHttpAsyncHandler.

In this post, I will be discussing, How we can write Asynchronous HTTPHandlers with the help of new features introduced in .NET 4.5 framework.

In the example, I’ll create an asynchronous HTTPHandler with the help of asp.net 4.5 that downloads rss feed.

To create Asynchronous HTTPHandler in asp.net 4.5, we need to implement the method ProcessRequestAsync of new abstract class HttpTaskAsyncHandler that got newly introduced.

For that I created a class library named AsyncHandlerLibrary , which has a Handler class CustomAsyncHandler which implements HttpTaskAsyncHandler.

So the class CustomAsyncHandler  will be as

   public class CustomAsyncHandler : HttpTaskAsyncHandler
    {

        public override async Task ProcessRequestAsync(HttpContext context)
        {
            string url = context.Request.QueryString["rssfeedURL"];
            if (string.IsNullOrWhiteSpace(url))
            {
                context.Response.Write("Rss feed URL is not provided");
            }
            WebClient webClient = new WebClient();

            //It starts downloading the rss asynchronously and the asp,net thread become free
            //and become available in threadpool
            //once the the it load the rssfeed loading completes it get assigned to another ASP.NET thread from the threadpool
            var rssfeed = await
                webClient.DownloadStringTaskAsync(url);

            // Writing the rss on the screen
            context.Response.Write(rssfeed);
        }

        public override bool IsReusable
        {
            get { return true; }
        }

        public override void ProcessRequest(HttpContext context)
        {
            throw new Exception("The ProcessRequest method has no implementation.");
        }

    }

Now if you see the above code, I have implemented ProcessRequestAsync , in which I read the rss url from query string. And asynchronously downloaded the rss feed and later wrote it in response.

Now you can see, with help of new keywords async keyword and await operator of .NET 4.5, it is extremely easy to write asynchronous code. It also got ensured that same can be used in asp.net with the introduction of new APIs.

Now build the project and add the reference in your web application. Also add this in your web.config file as

 <system.webServer>
  <handlers>
     <add name="myHandler" verb="*" path="*.rss"  type="AsyncHandlerLibrary.CustomAsyncHandler"/>
  </handlers>
</system.webServer>

Now you need to run you application with the url with query string say as http://brijbhushan.net/feed/. And in a while the rss feed would be downloaded as

Now you can seen it has never been so easy to write Asynchronous HTTPHandler. Now enjoy coding with ASP.NET 4.5

Hope you all have enjoyed the above post.