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.

Writing asynchronous HTTP Module in ASP.NET 4.5

Today again, I am going to discuss , one of the new features that got enhanced in ASP.NET 4.5. And It is Asynchronous HTTP Module . And it’s going to be very useful if used meticulously.

First Just to give a brief Idea, why Asynchronous HTTPModules are important ?

As we all know, web is stateless. A Web page is created from scratch every time whenever it is posted back to the server. In traditional web programming, all the information within the page and control gets wiped off on every postback. Every request in ASP.NET goes through a series of events.

Every request is served by am HTTP handler and it goes a series of HTTPModules (HTTPPipeline) which can be read, update the request. A lot of features of ASP.NET like Authentication, Authorization, Session etc are implemented as HTTP Module in ASP.NET. Let’s have a view on the Request Processing

ASP.NET Request Processing : HTTPPipeline and HTTPHandler


Now as you can see the request is assigned to a thread T1 from the available threads is thread pool. And the request is passed through several HTTPModules and finally served my HTTPHandler and response is send back with the same thread (T1).

During the entire processing, same thread is engaged in serving  the same request and cannot be used by any another request till request processing completes.  During the request processing if any HTTPModules depends on some entities like I/O based operations, web services, Databases queries etc then it takes long to complete which makes the thread busy for long which makes asp.net thread will not do anything during that duration and will be useless.  In this kind of scenarios the throughput goes down rapidly.

In the above scenario, synchronous HTTPModule can degrade the site performance a lot. So if we can make  HTTPModules as asynchronous  that can increase the through put a lot.  In asynchronous mode, ASP.NET thread get released as soon as the control get passed to another component/module, it does not wait. And the thread becomes available in thread pool and can be used to serve another request. When the component completes its assigned task then it got assigned to new ASP.NET thread which completes the request. The flow can be graphically presented as

Working of an asynchronous HTTPModule

In the above picture, An asp.net thread T1 is assigned from threadpool to server the request. When the control got passed to File System to log message, asp.net thread got  released and when essage logging got completed, control passed to asp.net and it is assigned to another thread say T2 from thread pool.
In .NET Framework 4.o, there was some major enhancement made for asynchronous programming model. Any asynchronous operation is represents a Task and it comes under the namespace System.Threading.Tasks.Task.

In .NET 4.5, there are some new operator and keyword introduced that makes the life easy for implement Asynchronous feature. One is async keyword and await operator.

These two enables us to write the asynchronous code is similar fashion as we write for synchronous mode.

And these features can be easily used while writing HTTPModules and HTTPHandlers. We’ll be using these enhancements in writing our custom asynchronous HTTPModule.

In my sample as depicted in image, I am creating a module that writes some log messages in a text file for every request made.

So to create a Custom HTTPModule, Create a class library project. And create a class  say named LogModule which implements IHttpModule. For this you need to add a reference of Assembly System.Web.

LogModule would contains the methods discussed below.

We need to implement two methods Init and Dispose that are part of IHTTPModule interface.

Here first , I have written an asynchronous method that actually reads the information from the request and writes in the log file asynchronously . For this I have used WriteAsync of FileStream

private async Task WriteLogmessages(object sender, EventArgs e)
{
	HttpApplication app = (HttpApplication)sender;
        DateTime time = DateTime.Now;

        string line = String.Format(
        "{0,10:d}    {1,11:T}    {2, 32}   {3}\r\n",
        time, time,
        app.Request.UserHostAddress,
        app.Request.Url);
        using (_file = new FileStream(
            HttpContext.Current.Server.MapPath(
              "~/App_Data/RequestLog.txt"),
            FileMode.OpenOrCreate, FileAccess.Write,
            FileShare.Write, 1024, true))
        {
            line = line + "  ," + threaddetails;
            byte[] output = Encoding.ASCII.GetBytes(line);

            _file.Seek(_position, SeekOrigin.Begin);
            _position += output.Length;
            await _file.WriteAsync(output, 0, output.Length);
        }

}

Here you can see the await key word, what it means..

As per msdn “An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

await is used with some asynchronous method that returns task and is used suspend the execution of the method until the task completes and control is returned back to the caller to execute further. await should be used with the last expression of any code block.

And Init method would be like

public void Init(HttpApplication context)
{
        // It wraps the Task-based method
        EventHandlerTaskAsyncHelper asyncHelper =
           new EventHandlerTaskAsyncHelper(WriteLogmessages);

        //asyncHelper's BeginEventHandler and EndEventHandler eventhandler that is used
        //as Begin and End methods for Asynchronous HTTP modules
        context.AddOnPostAuthorizeRequestAsync(
        asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler);

}

So apart from above these methods, we need to implement the dispose method.

Now compile your class library and use the reference in your ASP.NET website . Now as you must be knowing that we need to need to add the entry in the config file. So it’ll be as

<system.webServer>
<modules>
<add name="MyCustomHTTPModule" type="MyCustomHTTPModule.LogModule, MyCustomHTTPModule"/>
</modules>
</system.webServer>

Now when you run your application, you will see the logs are created in a text file in App_Data folder as mentioned path in the code.

Hope you all have liked this new feature.

Request Validation with ASP.NET 4.5 : A deep dive

DownLoad Sample

Security is always the one of the greatest concerns of Applications and when it comes to web applications, they are more prone to security breach. All the web technologies provides many features that are used to write secured web applications.

Here In this post, I am going to discuss Request Validation feature, mainly focusing ASP.NET 4.5 version.

Request validation introduced since ASP.NET 1.1 is available. By default it is enabled and it prevents to accept un-encoded HTML/XML etc from Client to server. It validates all the data that is passed from client to server. It can be any form like

  • Cookies
  • Form Collection
  • Querystring
  • Server variables

This helps to avoid script injection attacks. So it is always recommended to validate all the data that is passed from client to server because it can be malicious code and can be harmful the application.

Although, if we are sure that this situation would not arise, it can be disabled at application level or page level so no request will get validated. But this is not the case every time. On some occasions, we may need to allow users to enter some html, xml etc.. data . In this case, we need to partially validate the request.

There are several scenarios where we need to turn off the request validation just because of some specific data we don’t need to get validated. It leads us to write less secure code because we are the whole request goes to unvalidated. There are scenarios like in blog sites where we normally allow the user to write html , xml etc as input

Till ASP.NET 4.0, we have option to disable the request validation in the entire application or can be done page by page. But till now we did not have option to partially validate the page. ASP.NET 4.5 enables us to validate some specific part of the request.

ASP.NET 4.5 provides us two features.

  • Selectively un-validate the request
  • Deferred or lazy validation

How to allow partially unvalidated request in asp.net 4.5

(Note : I have VS11 beta version for this post)

I have created a sample application and have two textboxes – txtValidate and txtunValidate, with a submit button.

Let’s have a use case that I want to validate txtValidate but not txtunValidate. You must remember that this was not possible with earlier version of ASP.NET.I’ll also discuss it in detail later. To use this feature , you must set requestValidationMode as 4.5 in web.config like

            <httpruntime requestvalidationmode="4.5" />
 

Apart from this, ASP.NET 4.5 added one more property ValidateRequestMode with input controls. And it can have the following values

  • Enabled: Request validation is enabled for the control. Bydefault it is enabled
  • Disabled: Input values for this control would not be validated
  • Inherit: Property value will be inherited from parent

So let’s proceed with sample, and as I don’t want to validate txtunValidate so I need to set ValidateRequestMode attribute as disabled like

Sample aspx code

Now Let’s run the code.

sample runningAnd as you can see I’ve put some script tag in txtunValidate and it worked fine. But let us remove the requestValidationMode from web.config and try to submit the same input again.

Request Validation error

and see it gave the HttpRequestValidationException exception and got the above screen. Now lets again put the attribute requestValidationMode in web.config and try to put some script in txtValidate and submit. It’ll show you the same exception again as expected. So here you can see, ASP.NET 4.5 enables us to selectively validate the request.

Deferred or lazy validation

This is also introduced in asp.net 4.5 and I’ll say that above feature is just a corollary of this feature.

To provide these features, Microsoft has done some major changes in the way Request Validation feature got implemented in earlier version of ASP.NET. As we know, to process a request, ASP.NET creates an instance of HTTPContext which holds the instance of HTTPRequest and HTTPResponse with other required data. All the input data that is passed from client to server, it is posted in form collection, querystring etc.. ASP.NET validates every data that is passed from client to server.

Actually in ASP.NET 4.5, whenever the data is accessed from the request it gets validated. Like when we access the form collection to some input as Request.Form[uniqueId] the validation triggers. To provide selective validation, Microsoft has introduced a new collection property named as Unvalidated in the HTTPRequest class. This contains all the data that is passed from client to server like cookies, form collection, querystring etc as

UnValidated collection

Now the same data is available at two places. In UnValidated collection and normal in HTTPRequest. When we set the ValidateRequestMode is disabled, the data is accessed from UnValidated collection else normal request. UnValidated collection don’t trigger any validation while other one triggers. I’ll show you a demo later.

In earlier version of ASP.NET 1.1/2.0/3.5, Request validation is done at earlier level of page processing. There were also some good amount of changes took place in ASP.NET 4.0, which provides us the feature to validate the non-ASP.NET resources as well which was not available earlier.

Under the hood

I have the same application and I have removed the requestValidationMode attribute from web.config and putting some html tags as I did above example and pressed submit. So I got the HttpRequestValidationException as

Validation exception in earlier versions of ASP.NET

Now let’s put the requestValidationMode as 4.5 and try the same as above. I have removed the disable attribute. Again I got the same exception as below

Validation error in ASP.NET 4.5

But if we examine the circled part of the stacktrace, we can easily Identify that in 4.5, the validation exception got thrown from TextBox’s LoadPostData method.

Let’s do some experiment to examine this. I have made two case studies for this.

Case Study 1

As we all know the ASP.NET Page LifeCycle as

ASP.NET page life cycleAs you can see, here LoadPostData is a part of PageLife Cycle and comes after LoadViewState. All of the Input control’s data don’t get wiped off during postback even if viewstate is not enabled for that control. I have written a post on it. You can view this here.

So this is the LoadPostData method that is responsible to get the data from Form collection and assign it to the control. As I said, Now asp.net 4.5, validates the input only when you access the data from form collection. That’s why if you look the stacktrace then it is visible that the exception is thrown from LoadPostData method only and page life cycle is the last stage of ASP.NET Request Processing.

Now lets try to have an clarification using a demo. As I mentioned, in ASP.NET 4.5, the validation triggers only when the data is accessed and the data is accessed at LoadPostData for input controls. So lets create a custom textbox. For this I’ll override LoadPostData method and will do nothing in that. It means that the data would not be accessed for the customTextBox at LoadPostData. So even if the ValidationMode is enabled for the CustomtextBox, it wont be fired. Lets see this

I have created a CustomtestBox and overridden the LoadPostData method as

   public class CustomTextBox : System.Web.UI.WebControls.TextBox
    {
        protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            return false;
        }
    }
 

You can see, I have just returned false in the LoadPostData method. Now I have used my CustomTextBox at my aspx page as

CustomtextboxNow set the requestValidationMode as 4.5 in web.config and enter some script tag and submit.

You would not get any error even RequestValidation is enabled. This proves the validation fires only when data is accessed from the form collection.

Case Study 2

Here I’ll also try to prove the same as above. I have already shown above that How the new UnValidated property of Context holds all the data including form collection, querystring, cookies etc. So whenever the data is accessed from the UnValidated collection, the validation is not fired. But when it is accessed from the normal form collection, validation gets fired.

So here I am going to use again the earlier sample. In that example I had two textboxes and a submit button. Here the change is that at server side, instead of accessing the data form txtValidate.Text, I’ll be accessing the data from FormCollection. So I’ll set the the ValidateRequestMode as disabled for both the textbox and will try to get the data one will be form normal Form Collection and another is from Unvalidated’s form collection as

   protected void Button1_Click(object sender, EventArgs e)
    {
        string textValidated = this.Context.Request.Unvalidated.Form[txtValidate.UniqueID];
        string textUnValidated = this.Context.Request.Form[txtunValidate.UniqueID];
    }
 

Now lets enter some html tags in both the textboxes and submit the page using debugger as

Exception using debuggerOh!! see even we have disabled the validation, even in that situation when data is accessed from normal Form collection the validation is fired.

This again proves the validation is fired only when the data is acessed and when the ValidateRequestMode is set as disabled it is accessed from the UnValidated property.

Hope you all have enjoyed the post. Do share your precious feedback.

Cheers,
Brij

Unobtrusive Validation with ASP.NET 4.5

ASP.NET 4.5 has been improved and latest version ASP.NET. It includes an array of new and modified features. Today we’ll discuss one new feature Unobtrusive Validation that is introduced with ASP.NET 4.5 .

So what is Unobtrusive Validation?

In a normal validation scenario,when we use a validator to validate any any control and use Client side validation, some JavaScript is generated and rendered as HTML. Also some supportive JavaScript files is also get loaded by the browser for the validation.

Now with feature Unobtrusive Validation, inline JavaScript is not generated and rendered to handle the Client Side validation. Instead of this it uses HTML5 data-* attributes for all these validation.

Continue reading