Top 7 Features of ASP.NET Framework 4.0

Introduction

ASP.NET 4.0 is the version of ASP.NET bundled with .NET Framework 4.0. In this article let us delve into what I think are the top 7 features of ASP.NET 4.0.

ASP.NET 4.0 application provides support to websites as well as web application projects. The default ASP.NET application provides a good starter project template with some common items which have to be built for almost all web based projects like a Master Page with a standard template, About us page, Login page, Register page, Change Password page, a default style sheet named Site.css which would already have been referred in the Master page, etc., This undoubtedly would reduce a lot of development effort. All you need to do is simply customize the predefined templates to your needs. If the developer is not interested in the default templates, ASP.NET 4.0 also provides web based projects called EmptyWebApplication and EmptyWebSite, which will not have any default items in the project except the web.config file. Fig 1.0 shows the default home page template.


Fig 1.0

Another noticeable thing would be, when you expand the Web.Config file you would find two files named Web.Debug.config and Web.Release.config. This is a new feature called Web.Config transformation, which will enable developers to maintain separate config files for different application environments. I will soon be writing an article on Web.Config transformation.

Chart Control

In my opinion the introduction of the new Chart Control in ASP.NET 4.0 makes the life of most web application developers a lot easier. In the earlier versions of ASP.NET in order to have a chart on the web page you have to download the MS charts and integrate it into the IDE which only exposed some basic chart features. For more chart features the developers had to use some third party chart controls. Now the ASP.NET chart control provides a wide range of features. In fact it also provides support for 3-D charts. Below is the list of some of supported chart types.

  • Point
  • FastPoint
  • Bubble
  • Line
  • Column
  • Stacked Column
  • Pie
  • Pyramid
  • Etc.,

You need to simply set the data source for this chart control as you do it for a GridView and your chart is ready. Another good thing about the chart controls is that you can customize the style and appearance to a great extent. You can also provide a gradient style to your charts.

Fig 2.0 shows a sample Column Chart.


Fig 2.0

Below is the corresponding .aspx code for the above chart. Note that I have hardcoded the datapoints in order to make the example pretty simple.

<asp:Chart ID="Chart1" runat="server" Width="428px">
            <series>
                <asp:Series Name="Series1">
                    <Points>
                        <asp:DataPoint XValue="1970" YValues="1000" />
                        <asp:DataPoint XValue="1980" YValues="2000" />
                        <asp:DataPoint XValue="1990" YValues="3000" />
                        <asp:DataPoint XValue="2000" YValues="4000" />
                        <asp:DataPoint XValue="2010" YValues="5000" />
                    </Points>
                </asp:Series>
            </series>
            <chartareas>
                <asp:ChartArea Name="ChartArea1">
                    <AxisX Title="Year" IntervalOffsetType="Years">
                    </AxisX>
                    <AxisY Title="City Population" IsLogarithmic="true">
                    </AxisY>
                </asp:ChartArea>
            </chartareas>
</asp:Chart>

Fig 2.1 is a sample Pie chart


Fig 2.1

Below is the code for the above chart

<asp:Chart ID="Chart1" runat="server" >
            <Series>
                <asp:Series Name="Series1" ChartType="Pie" Legend="Legend1">
                    <Points>
                        <asp:DataPoint Label="India" CustomProperties="OriginalPointIndex=0" YValues="40" />
                        <asp:DataPoint Label="China" CustomProperties="OriginalPointIndex=1" YValues="40" />
                        <asp:DataPoint Label="America" LabelAngle="-50"   CustomProperties="OriginalPointIndex=2" YValues="10" />
                        <asp:DataPoint Label="Australia" LabelAngle="-10"  CustomProperties="OriginalPointIndex=3" YValues="10" />
                    </Points>
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                </asp:ChartArea>
            </ChartAreas>
            <Legends>
                <asp:Legend Name="Legend1">
                </asp:Legend>
            </Legends>
            <Titles>
                <asp:Title Name="Population Chart" Text="Population Chart">
                </asp:Title>
            </Titles>
</asp:Chart>

ClientIDMode for controls

In earlier versions of the ASP.NET Framework if you place a control inside a container control like a Template column of a GridView, Template of a Login Control, etc., at runtime the IDs of those controls will be replaced with random unique IDs generated by ASP.NET itself. This was a big and long standing problem for the developers to access the control on the server side using Page.FindControl("controlid") as well as in JavaScript using document.getElementbyId("controlid"). In simple terms the control ids generated at runtime were not predictable.

But .NET developers no longer find themselves in such situation because in ASP.NET 4.0 there is a property called ClientIDMode for all the controls. This has provided good control over the ID generated for the content controls during runtime.

The types of ClientIDModes available are:

  1. AutoID - This is the same random way as it uses to happen in the earlier versions of ASP.NET.
  2. Static - The ID of the control will not change at the runtime. This is pretty handy setting if the control is being used in the container or in the child pages and needs to be accessed on the client scripts.
  3. Predictable - For the controls like a textbox in a GridView template column Static mode will not be useful because of the repeating rows of the GridView. In such scenarios Predictable mode comes in handy where the developer can provide a predictable value say a primary key of the GridViewRow using the ClientIDRowSuffix property. This will append the predictable unique value as suffix to the actual control id. For example if the actual control id in the TemplateColumn is txtBox and the ClientIDRowSuffix is the GridViewRowIndex then the generated IDs during runtime for row1 textbox ID will be GridView1_txtBox_1, for row2 it will be GridView1_txtBox_2 and so on.
  4. Inherit - This will inherit the ClientIDMode value from its parent control.

You don't have to provide the ClientIDMode for each and every control rather you could specify it at the page level in the page directive.

<%@ Master Language="C#" ClientIDMode="Predictable" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="MyWebApplication.SiteMaster" %>

Or it could also be provided at the application level using the web.config specification as shown below.
<system.web>
      <pages clientIDMode="Predictable"></pages>
</system.web>

Note that the ClientIDMode specified at the control level will override the above settings in the page directive and web.config.

Top 7 Features of ASP.NET Framework 4.0

Integration of JQuery

The developers no longer have the trouble of downloading the JQuery library and adding it to the project explicitly because in ASP.NET 4.0 web based applications JQuery is integrated. Developers are now free to use the JQuery, all that needs to be done is simply add the JQuery library reference onto the web page. The JQuery library is a part of the project template by default. The JQuery library is placed under the Scripts folder as shown in Fig 3.0

[query4.jpg]
Fig 3.0

JQuery library is nothing but a JavaScript library which allows you to traverse through the web page controls using the tag name or the control ID more easily and offers a lot of in built functions to provide good animations on the client side. Check the below example where an image is enlarged on hover of the mouse pointer using JQuery.

Add script reference to the JQuery library and add couple of styles to your web page:

<script src="~\Scripts\jquery-1.3.2.min.js" type="text/javascript"></script>
	
<style type="text/css">
		.a img
		{
			border:0px;
		}
		#largeImage
		{
			border-color:Gray;
			border-width:10px;
			border:solid;
			position:absolute;
		}
</style>
Here is the JQuery and the 
<script type="text/javascript">
	$(function(){
		var offset = 10;
		$('img').hover(function(e){
			var imageUri = $(this).attr('src');
			$('<img href="#" src="' + imageUri + '" alt="larger image" id="largeImage"/>').css('top', e.pageY + offset)
																						.css('left', e.pageX + offset)
																						.appendTo('body');
		}, function(){
			$('#largeImage').remove();
		});
	});
	
</script>

Place an image control and set the height and width.

<img alt="Image loading..." id="imageOneTN" height="100px" width="100px" src="Images/Blue hills.jpg" />

Fig 3.1 shows how the images is enlarged and displayed on the web page with no effort.

[query5.jpg]
Fig 3.1

In ASP.NET 4.0 JQuery plug-ins can be combined with Microsoft ASP.NET AJAX controls seamlessly.

Output Caching Enhancement

Output caching is a mechanism where the rendered web page or web user controls can be stored in an in-memory cache on the web server. This cannot be customized in the previous versions of the ASP.NET. This kind of in-memory cache mechanism would end up in hiking up the worker process memory which adversely puts the load on the web servers.

In ASP.NET 4.0 applications you can define your own cache providers by defining a class inheriting from System.Web.Caching.OutputCacheProvider and implementing the methods as per your need. This custom implementation would allow you to store the cached data on the local disk or on a network drive instead of in-memory storage. Let us go ahead and create a custom cache provider.

Create a class called MyCacheProvider inheriting it from the class OutputCacheProvider which is under the namespace System.Web.Caching.

using System;
using System.Web.Caching;

namespace MyWebApplication.CacheProvider
{
    public class MyCacheProvider : OutputCacheProvider
    {
        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            //Create a file using the key on a network drive
            //Write the entry value to the file
            //Set the expiry datetime
            return null;
        }

        public override object Get(string key)
        {
            //Get the content from the file using the key
            return null;
        }

        public override void Remove(string key)
        {
            //Remove the file from the network cache
        }

        public override void Set(string key, object entry, DateTime utcExpiry)
        {
            //Update the existing cache
        }
    }
}

The next step is configuring your application to use the MyCacheProvider for storing the output cache instead of using the default ASP.NET caching mechanism. This is just a configuration setting as shown below:

 <system.web>
    <caching>
      <outputCache defaultProvider="CustomCache">
        <providers>
          <add name="CustomCache" type="MyWebApplication.CacheProvider.MyCacheProvider, MyWebApplication"/>
        </providers>
      </outputCache>
    </caching>
  </system.web>

Now onwards the output caching would be done on your web application using the MyCacheProvider. As you can see you can specify more than one cache provider for the application and set a default provider as well. In order to choose the cache provider at runtime there is a method called GetOutputCacheProviderName in the Global.asax which can be overridden. Below is the code:

public override string GetOutputCacheProviderName(HttpContext context)
{
//return the ASP.NET cache provider only for the login page
       if (context.Request.Path.Contains("Login.aspx"))
       	return "AspNetInternalProvider";
       else
       	return base.GetOutputCacheProviderName(context);
}

Compression of Serialized Session Data

There are three ways of storing a Session state data in ASP.NET InProc, State Server and Sql Server Database. Out of the three options Session state is stored out of the worker process memory in state server where the session is stored on a dedicated state server machine and SQL server database where the session state data is stored in a SQL server.

In these two mechanisms since the session data has to be transferred across the wire they have to be serialized before transmission and deserialized after transmission. The serialized data would grow quite large based on the amount of data stored in session. In ASP.NET 4.0 there is a nice feature to perform compression on the serialized data using the System.IO.Compression.GZipStream class. This will greatly decrease the size of the serialized data. This can be enabled by setting the compressionEnabled attribute of the sessionState tag in the config file to true. Below is the sample config entry:

SqlServer mode

<sessionState compressionEnabled="true"
               mode="SQLServer"
               sqlConnectionString="yourSqlConnectionString"
               allowCustomSqlDatabase="true" />

State Server mode
<sessionState mode="StateServer" compressionEnabled="true"                stateConnectionString="yourStateServerConnectionString">
</sessionState>

Cleaner Web.Config and Multi Targeting

As the features of the ASP.NET application grew like the introduction of AJAX, Routing, etc., it was inevitable that there came many entries in the web.config for supporting these new features. Adversely the web.config was getting more messy which sometimes had confused developers to some extent. In ASP.NET 4.0 web.config all these extra entries have been moved to the machine.config file located at C:\WINDOWS\Microsoft.NET\Framework\v4.0.21006\Config and your application's web.config file inheriting those settings. Thus, it made the config file much cleaner and free from the messy look.

Using a new attribute called targetFramework in the compilation tag allows you to set the applications to target the .NET Frameworks 4.0 and later versions. Below is the web.config compilation tag which specifies that the application is targeting .NET Framework 4.0.

<compilation debug="true" targetFramework="4.0">

URL Length and QueryString Size Customization

In the earlier versions of ASP.NET there was a restriction in the URL length and the query string size of the URL. The maximum length allowed for URLs is 260 characters and the maximum size of Query string allowed is 2 KB.

In ASP.NET 4.0 the restriction has been lifted off and the control is put into the developer's hands. In the web.config file for the httpRuntime tag there is a couple of new attributes called maxUrlLength to customize the URL length and maxQueryStringLength to customize the size of the QueryString.

Below is the configuration entry which would hike up the URL maximum length to 520 characters and QueryString size to 4KB.

<httpRuntime maxQueryStringLength="4096" maxUrlLength="520"/>

Conclusion

I hope this article helpd in some way to help you build on your knwoledge of ASP.NET 4.0. There are many useful and handy features that have been introduced in ASP.NET 4.0. After the actual release, it will definitely trigger many companies to develop applications in ASP.NET 4.0 and also most web based application would undergo migration for sure.

Please provide your valuable comments after reading this article.

Related Articles



About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds