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

Routing in ASP.NET 4

Although routing features comes with ASP.NET 3.5, ASP.NET 4 comes with new additions to make it easier to use the routing mechanisms, such as:
  • The PageRouteHandler class, which is a simple HTTP handler that you use when you define routes. The class passes data to the page that the request is routed to.
  • The new properties HttpRequest.RequestContext and Page.RouteData (which is a shortcut to HttpRequest.RequestContext.RouteData). These properties make it easier to access information that is passed from the route.
  • The following new expression builders, which are defined in System.Web.Compilation.RouteUrlExpressionBuilder and System.Web.Compilation.RouteValueExpressionBuilder: 
    • RouteUrl, which provides a simple way to create a URL that corresponds to a route URL within an ASP.NET server control.
    • RouteValue, which provides a simple way to extract information from the RouteContext object.
  • The RouteParameter class, which makes it easier to pass data contained in a RouteContext object to a query for a data source control (similar to FormParameter).

Global.asax file and add the following code to bind the customers/{id} url pattern with the physical page Customers.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;

namespace WebAppRouting
{
    public class Global : System.Web.HttpApplication
    {
       
        void Application_Start(object sender, EventArgs e)
        {
            // New code added
            RegisterRoutes(RouteTable.Routes);
        }
// New code added
        void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("Customers", "customers//{id}", "~/Customers.aspx");
        }
    }
}

let's create the Customer.aspx file and add the code to get “id” value and display in the page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebAppRouting
{
    public partial class Customers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string customerId = this.Page.RouteData.Values["id"] ?? "Invalid CustomerId";
           
this.lblCustomerId.Text = customerId;
        }
    }
}



URL and QueryString Length

In previous versions of ASP.NET,  URLs were limited to 260 characters in length. But in ASP.NET 4.0 developers have the option of increasing or decreasing  the length of URLs by using  the new maxRequestPathLength and maxQueryStringLength. I’ll illustrate this in an example.

<httpRuntime maxRequestPathLength="360" maxQueryStringLength="1024" />

In previous versions of ASP.NET you were limited to a fixed set of characters but in v4, developers can also validate the invalid characters by specifying values in the requestPathInvalidChars attribute.


Html Encoded Code Expressions

In ASP.NET applications (especially with ASP.NET MVC), we rely heavily on using <%= expression %> syntax (often called "code nuggets") to write some text to the response.
ASP.NET 4 introduces the following new syntax for code expressions:
<%: expression %>. 
This syntax uses HTML encoding by default when writing to the response. This new expression effectively translates to the old version as following:
<%= Server.HtmlEncode(content) %>
OR
<%= HttpUtility.HtmlEncode(content) %>

For those cases, ASP.NET 4 introduces a new interface, IHtmlString, along with a concrete implementation, HtmlString. Instances of these types let you indicate that the return value is already properly encoded (or otherwise examined) for displaying as HTML, and that therefore the value should not be HTML-encoded again. For example, the following should not be (and is not) HTML encoded: <%: new HtmlString("<strong>HTML that is not encoded</strong>") %>.
Html Encode method encodes a particular string to be displayed in a browser. It is important to encode strings prior it’s rendering in the page, mainly to avoid cross-site script injection (XSS) and HTML injection attacks. However, developers so often forget to call the encode function.

<div id="PanelParent">               
          <%= Server.HtmlEncode(content) %>
</div>

In ASP.Net 4.0,

<div id="PanelParent">               
          <%: content %>
</div>


Setting Client IDs

ASP.NET 4 introduces new ClientIDMode property lets you specify more precisely how the client ID is generated for controls. You can set the ClientIDMode property for any control, including for the page. Possible settings are the following:

  • AutoID. This is equivalent to the algorithm for generating ClientID property values that was used in earlier versions of ASP.NET.
  • Static. This specifies that the ClientID value will be the same as the ID without concatenating the IDs of parent naming containers. This can be useful in Web user controls. Because a Web user control can be located on different pages and in different container controls, it can be difficult to write client script for controls that use the AutoID algorithm because you cannot predict what the ID values will be.
  • Predictable. This option is primarily for use in data controls that use repeating templates. It concatenates the ID properties of the control's naming containers, but generated ClientID values do not contain strings like "ctlxxx". This setting works in conjunction with the ClientIDRowSuffix property of the control. You set the ClientIDRowSuffix property to the name of a data field, and the value of that field is used as the suffix for the generated ClientID value. Typically you would use the primary key of a data record as the ClientIDRowSuffix value.
  • Inherit. This setting is the default behavior for controls; it specifies that a control's ID generation is the same as its parent.


An AutoID example
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Panel ID="PanelParent"  runat="server">        
        <asp:Panel ID="PanelChild" runat="server">        
            <asp:TextBox ID="txtMyTextBox" runat="server" ClientIDMode="AutoID" />
        </asp:Panel>
    </asp:Panel>
</asp:Content>

Output:
<div id="MainContent_PanelParent">                
   <div id="MainContent_PanelChild">                
     <input name="ctl00$MainContent$txtMyTextBox" type="text" id="ctl00_MainContent_ txtMyTextBox" /> 
  </div>
</div>


A Static example
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Panel ID="PanelParent"  runat="server">        
        <asp:Panel ID="PanelChild" runat="server">        
            <asp:TextBox ID="txtMyTextBox" runat="server" ClientIDMode="Static" />
        </asp:Panel>
    </asp:Panel>
</asp:Content>

Output:
<div id="MainContent_PanelParent">                
  <div id="MainContent_PanelChild">                 
    <input name="ctl00$MainContent$txtMyTextBox" type="text" id="txtMyTextBox" />  
           </div>
</div>


A Predictable example
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Panel ID="PanelParent"  runat="server">        
        <asp:Panel ID="PanelChild" runat="server">        
            <asp:TextBox ID="txtEcho" runat="server" ClientIDMode="Predictable" />
        </asp:Panel>
    </asp:Panel>
</asp:Content>

Output
<div id="MainContent_PanelParent">                
  <div id="MainContent_PanelChild">                 
    <input name="ctl00$MainContent$txtMyTextBox" type="text" id=" MainContent_txtMyTextBox" />  
           </div>
</div>

New ClientIDRowSuffix property on databound controls also gives a similar functionality when rendering an each data item. Once you set the relevant databound property to ClientIDRowSuffix, the value will be added as a suffix to individual row elements.
<asp:DataList ID="DataList1" ClientIDRowSuffix="Country" runat="server">
</asp:DataList>

After the control renders the “State” value will be added as a suffix to each data row element.

<ul>
       <li id="Mark_US">Mark</li>
       <li id="Bill_UK">Bill</li>
       <li id="Eva_CA">Eva</li>
       <li id="Julia_US">Julia</li>
</ul>



Web.config refactoring

Over the past few years web.config file has grown significantly as ASP.NET has used it for more and more features such as routing, Ajax, IIS 7 and version compatibility. This has made it trickier to maintain even with the Visual Studio environment.
With ASP.NET 4, most of the major elements have been moved to the machine.config file. This has enabled developers to maintain a cleaner, less cluttered, web.config file. The new web.config file is either empty, or includes just the .NET framework version details as shown in the following example.

<?xml version="1.0"?> 
   <configuration>  
      <system.web>   
         <compilation targetFramework="4.0" />   
      </system.web> 
   </configuration>



Auto-Start ASP.NET Applications

Most application requires initial data load or caching operations to be done before serving the client requests. Typical this happens only when the first user request a page. However, often developers and web administrators write fake requests to keep the application alive to increase the response time. To overcome this issue, ASP.NET 4 introduce new Auto-Start feature. Auto-start feature available with IIS 7.5 and it initialize the ASP.NET application to accept requests.
To configure the Auto-start, you need to configure the “Application pool” worker process by setting the startMode attribute to “AlwaysRunning” in the applicationHost.config file. (C:\Windows\System32\inetsrv\config\applicationHost.config)

<applicationPools>
    <Add name=”AppName” managedRuntimeVersion=”v4.0” startMode=”AlwaysRunning”
</applicationPools>

As soon you save the applicationHost.config file the worker process will start and initialize the required application operations before the first user has been served.



Improvements on Microsoft Ajax Library

Microsoft Ajax library is client side library which includes high performance server based user controls and asynchronous page rendering controls. Ajax Library enables developers to easily and quickly write responsive database-driven applications.
There are some significant improvements in the Ajax Library in the ASP.NET 4. of which the most important are:
  • Scrip Loader – the new script loader control enable developers to load all the required scripts only once, thereby eliminating the unnecessary subsequent requests to the server. It supports the ‘lazy load’ pattern which loads scripts only when necessary, and loads scripts in combination, in order to increase the performance of loading a page. It also supports the jQuery script and custom scripts. 
  • JQuery Integration – JQuery is very popular third party javascript library. ASP.NET 4 extensively supports the integration for jQuery by mixing the jQuery and Ajax plug-ins seamlessly. 
  • Client Data Access – by using pre-defined client controls inside the Ajax Library, developers can easily build asynchronous data-driven applications. For example client DataView control will display one or more records by consuming a WCF service. All the relevant time-consuming operations will be handled by the Ajax library asynchronously.


Comments

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