Most important new features in ASP.NET 4.0 - Part 1


The focus of ASP.NET 4.0 has mainly been on improving the performance and Search-engine Optimization (SEO). In this article, we'll be taking a look at the most important new features in ASP.NET 4.0.

1.    Output cache extensibility
2.    Session state compression
3.    View state mode for individual control
4.    Page.MetaKeyword and Page.MetaDescription properties
5.    Response.RedirectPermanent method
6.    Routing in ASP.NET
7.    Increase the URL character length
8.    New syntax for Html Encode
9.    Predictable Client IDs
10.  Web.config file refactoring
11.  Auto-Start ASP.NET applications
12.  Improvements on Microsoft Ajax Library

Output Cache extensibility

Output caching, or Page-Level Caching, caches the entire rendered markup of an ASP.NET web page for a specific time-period. This has always been one of the essential features for ASP.NET that is used extensively to increase application performance. However there have been some limitations on the feasible extent of caching, because cached content always had to be stored in-memory. One limitation of output caching with ASP.NET V1 to V3.5, though, is that the cache store itself is not extensible – and the cached content always has to be stored in-memory.
But with ASP.NET 4.0 developers can extend their caching by using Output-cache providers. Developers can now create ‘output-cache providers’ that store the cache contents to any persistence mechanism such as databases, disks, cloud storage and distributed cache engines.
To create a custom output-cache provider, a class which derived fromSystem.Web.Caching.OutputCacheProvider has to be created in ASP.NET 4.0. There are four public methods which you have to override in order to provide your own implementation for add, remove, retrieve and update functionality. Also, the output-cache provider has to be registered in the web.config file as shown below.

<system.web>
<compilation debug="true" targetFramework="4.0">
<caching>
      <outputCache defaultProvider="MyCacheProvider">
        <providers>
          <add name ="MyCacheProvider" type="MyCustomCache, CacheSample" />
        </providers>
      </outputCache>
    </caching>
</system.web>

Add - this method is passed a key, the object to add to the cache, and its expiry. However, if there already exists an item in the cache with this key, the Add method must return the data associated with the key and not add the passed-in data.
Get - this method is passed a key and returns the requested cached data (if it still exists in the cache and hasn't expired).
Remove - this method is passed a key and is tasked with removing that key (and its data) from the cache.
Set - this method is passed a key, the object to add or update in the cache, and its expiry.

You can also set this custom output-cache provider as your default cache mechanism. So once you add the page cache directives all of your contents will be stored using the custom output-cache provider.

<%@ OutputCache Duration="60" VaryByParam="None"  %>
If I add an [OutputCache] attribute on any action method within an ASP.NET MVC Controller the content will also be cached and stored using my MyCacheProvider provider:
public class CustomerController : Controller
{
    [OutputCache(Duration=60)]
    public ActionResult View(string CustomerID)
    {

Customizing Which Output Cache Provider is Used

Above I configured ASP.NET to by default always cache content using my “MyCacheProviderprovider whenever output caching is used within the application.
As a slightly more advanced option, developers can also configure ASP.NET to dynamically choose which output cache provider to use on a per-request basis.  This is useful for scenarios where you want to have a slightly richer set of cache semantics. For example, you might want to cache the frequently access pages in the memory for faster access using the built-in ASP.Net in-memory provider and less frequent pages on disk.

By overriding the GetOutputCacheProviderName() method within the Global.asax you can configure which output cache provider to use for different requests.

public class Global : System.Web.HttpApplication
{
    public override string GetOutputCacheProviderName(HttpContext context)
    {
        if (context.Request.Path.EndsWith("Default.aspx"))
            return "AspNetInternalProvider";
        else
            return base.GetOutputCacheProviderName(context);
    }
}
   
Caching can significantly reduce network latency and boost an application's performance. If you have a large number of concurrent requests to the same resource, caching can come in handy by allowing you to avoid redundant calls to the data stores. In this article, I explored the new features in the Cache API in .NET Framework 4, the ASP.NET Cache extensibility feature, and how these can be leveraged to implement your own custom cache provider. 

Session State compression

In ASP.NET, Session is a server-side state management technique that helps you to preserve user specific data in memory so that they can be accessed and used when required. If the data that is to be stored in the session is large, it would consume more server resources. Now, Session data can be stored in either of the following two modes:
·         In Process - Stored in the same ASP.NET Process
·         Out of Process - Stored in the database or in some other system

The available session state modes:

  •  InProc mode, which stores session state in memory on the Web server. This is the default.
  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom mode, which enables you to specify a custom storage provider.
  • Off mode, which disables session state.


ASP.NET 4 now comes with in-built support for compressing Session data for storing out-of-process sessions. To enable this feature, just set the compressionEnabled attribute to "true" as shown in the code snippet below:
<sessionState
  mode="SQLServer"
  stateConnectionString="some connection string..."
  compressionEnabled="true"/>

The ASP.NET session state is a mechanism to maintain session-specific data through subsequent requests. In some instances, you may wish to store your session state data in a session-state server or in Microsoft SQL server. However, these two options require you to store data out of the web application’s worker process. To send across to the relevant sources, (State server or Microsoft SQL Server), session-state data has to be serialized. This can take a significant time if the size of the data to be serialized grows significantly. This will increase the latency of the application.
This latency can be reduced if the size of the data is lessened by compression. ASP.NET 4.0 introduces a new mechanism to compress your session state data for both Session-state server and Microsoft SQL server.  Compression can be enabled by setting the compressionEnable to true in the web.config file. In this example, the session-state data will be serialized/desterilized using System.IO.Compression.GZipStream.
<sessionState  mode="SqlServer"  sqlConnectionString="data source=DB;Initial Catalog=LudmalDB"  allowCustomSqlDatabase="true"  compressionEnabled="true"/>
With this compression feature, developers can often reduce the time it takes for a web application to respond by reducing the size of session data.


View State mode for Individual Controls

View state is a mechanism to maintain page controls’ state on subsequent post backs. ASP.NET stores the view state data for controls that are in the page, even if it’s not necessary. Since the view state data is stored in the pages’ html, the size of the request object will be increased, and make performance worse.
In ASP.NET 4.0, each web control will include a ViewStateMode property which lets developers disable view-state by default, and enable it just for the controls for which a persistence of state is required. ViewStateMode has the following three values;
·         Enabled – enables the view state for this control and any child control.
·         Disabled – disable the view state.
·         Inherits – this specify the control uses the settings from its parent control.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
ViewStateMode="Disabled" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>View State Demo in ASP.NET 4.0</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="One" ViewStateMode="Enabled"></asp:Label><br />
        <asp:Label ID="Label2" runat="server" Text="Two"></asp:Label> <br /><br/>      
        <asp:Button ID="Button1" runat="server" Text="PostBack" />
    </div>
    </form>
</body>
</html>

Observe that ViewStateMode on the Page is set to Disabled. The child Label1 control has ViewStateMode set to Enabled, so Label1 ‘ideally’ should save view state. Since the ViewStateMode property is not set on Label2 , so the Label2 control inherits this property value from its parent (Page) and therefore saves no view state.
Note: The default value of ViewStateMode is Enabled for Page object. The default value of ViewStateMode is Inherit for controls.
By setting these values in page controls accordingly, a significant performance improvement can be gained in response-time.


Page.MetaKeywords and Page.MetaDescription properties

To increase the relevance of pages in searches, developers should  include relevant “keyword” and “description” meta tags in the html <head> section.     Unfortunately, it takes some time to add these tags for each and every page, and the alternative of adding these tags programmatically was difficult.
But with ASP.NET 4.0, there are two new properties in the code behind file;
·         Page.MetaDescription – equivalent to meta name “description”
·         Page.MetaKeywords – equivalent to meta name “keywords”
This will enable developers to easily and programmatically add the relevant keywords and description.
protected void Page_Load(object sender, EventArgs e)
    {
        Page.MetaDescription = "My ASP.Net Training Session";
        Page.MetaKeywords = "ASP.Net, Training, MicroSoft";
    }
This will even be useful for Master pages—where you only have to add these properties in the master page. In addition to “keywords” and “description” settings in the code behind, developers can also set these values within the @Page directive.


Response.RedirectPermanent Method

ASP.NET 4.0 has improved SEO (Search-engine Optimization) facilities. Typically developers use Response.Redirect(string url) to handle requests for old URLs. However, this leads to an extra round trip to access the old URLs and so will negatively affect your page-ranking  in search-engines.
ASP.NET 4.0 introduces a new Response.RedirectPermanent (string url) helper method to be used as HTTP 301 (Moved permanently) to handle requests. This will enable search-engines to index URLs and content efficiently and thus improve the page rankings. 
Response.Redirect:

using System;
using System.Web.UI;

namespace WebApplication1
{
    public partial class List : Page
    {
      protected void Page_Load(object sender, EventArgs e)
      {
          // Get response.
          var response = base.Response;
         
        // Redirect temporarily.
          response.Redirect("http://www.dotnetperls.com/list", false);
      }
    }
}

Response Result:

HTTP/1.1 302 Found
Content-Type: text/html; charset=utf-8
Location: http://www.dotnetperls.com/list
Server: Microsoft-IIS/7.0
Date: Fri, 13 Aug 2010 21:18:34 GMT
Content-Length: 144

<html><head><title>Object moved</title></head>
<body>
<h2>Object moved to <a href="http://www.dotnetperls.com/list">here</a>.</h2>
</body>
</html>

Response.RedirectPermanent:

using System;
using System.Web.UI;

namespace WebApplication1
{
    public partial class List : Page
    {
      protected void Page_Load(object sender, EventArgs e)
      {
          // Get response.
          var response = base.Context.Response;
         
        // Redirect permanently.
          response.RedirectPermanent("http://www.dotnetperls.com/list", false);
      }
    }
}

Response Result:

HTTP/1.1 301 Moved Permanently
Date: Fri, 13 Aug 2010 16:10:05 GMT
Server: Microsoft-IIS/6.0
Location: http://www.dotnetperls.com/list
Content-Type: text/html; charset=utf-8
Content-Length: 144

<html>
<head><title>Object moved</title></head>
<body>
<h2>Object moved to <a href="http://www.dotnetperls.com/list">here</a>.</h2>
</body>
</html>

When to use: 

Response.Redirect is perfect when your page is temporarily changed and will be changed to original within a short span of time.

Response.RedirectPermanent is useful when you are thinking of deleting the Page1 totally after the search engines changes its cache.


Server.Transfer is useful when you are thinking of keeping the page for ever, and to let search engine unaware of this redirection. 

Comments

  1. Try this C# Interview Questions...

    http://net-informations.com/faq/default.htm

    ReplyDelete

Post a Comment

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options