Archive for the ‘ASP.Net 4.0’ Category

State Management

What is state management?

Web is Stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, its can’t holds the client information on page. As for example , if we enter a text and client on submit button, text does not appear after post back , only because of page is recreated on its round trip.

Page is recreated before its comes to clients and happened for each and every request. So it is a big issue to maintain the state of the page and information for a web application. That is the reason to start concept of State Management. To overcome this problem ASP.NET 2.0 Provides some features like View State, Cookies, Session, Application objects etc. to manage the state of page.

There are some few selection criteria to selected proper way to maintain the state, as there are many way to do that. Those criteria are:

  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or on the server?
  • Is the information sensitive?
  • What performance and bandwidth criteria do you have for your application?
  • What are the capabilities of the browsers and devices that you are targeting?
  • Do you need to store information per user?
  • How long do you need to store the information?
  • Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?

So, when ever you start to think about state management, you should think about above criteria. based on that you can choose the best approaches for manages state for your web application.

Different types of state management?

There are two different types of state management:

  1. Client Side State Management
    • View State
    • Hidden Field
    • Cookies
    • Control State
  1. Server Side State Management
    • Session
    • Application Object
    • Caching
    • Database

Client Side state management does not use any server resource , it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your requirements and the selection criteria that are already given.

What is view state?

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.

Advantages of view state?

This are the main advantage of using View State:

  • Easy to implement
  • No server resources are required
  • Enhanced security features ,like it can be encoded and compressed.

Disadvantages of view state?

This are the main disadvantages of using View State:

  • It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
  • Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
  • It does not have any support on mobile devices.

When we should use view state?

A few point you should remember when you select view state for maintain your page state.

  • Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
  • Try to avoid storing secure data in view state

When we should avoid view state?

You won’t need view state for a control for following cases,

  • The control never change
  • The control is repopulated on every postback
  • The control is an input control and it changes only of user actions.

Where is view state stored?

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.

Viewstate value is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read. any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.

How to trace your view state information?

If you want to trace your view state information, by just enable “Trace” option of Page Directive

state information

Now Run your web application, You can view the details of View State Size along with control ID in Control Tree Section. Don’t worry about “Render Size Byte” , this only the size of rendered control.


Enabling and Disabling View State

You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false.

To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.

Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information, ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.

For enabling the same, you have to use the same property just set them as True


Encrypt Connection String in web.config

December 7, 2011 Leave a comment

Never keep clear plain connectionstring in web.config file. The risk and consequences of this is self expalanatory. All you need to do is follow below steps and you are through with this.

Steps to be followed.


  1. Go to Visual Studio Command prompt in the “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\”path.
  1. Encrypt Web.Config connectionStrings using below command;
  1. aspnet_regiis -pef “connectionStrings” path of the physical folder where web.config resides (e.g. aspnet_regiis -pef “connectionStrings” D:\ProjectName)
  1. You will get the message “Encrypting configuration section… Succeeded!”
  1. Run Following Commands;
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “ASPNET”
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “NETWORK SERVICE”
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “NT AUTHORITY\NETWORK SERVICE”
  1. Restart IIS

Move ViewState to the bottom of the page

If you move your viewstate from the top of the page to the bottom, you will get better search engine spidering.


Step 1 :

Create a class file in App_code folder of your application and name it as “PageBase.cs“. Copy following code to the class file.


using System.IO;

using System.Web.UI;


namespace WebPageBase


public class PageBase : System.Web.UI.Page


/// This method overrides the Render() method for the page and moves the ViewState

/// from its default location at the top of the page to the bottom of the page. This

/// results in better search engine spidering.


protected override void Render(System.Web.UI.HtmlTextWriter writer)


// Obtain the HTML rendered by the instance.

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);


string html = sw.ToString();


// Hose the writers we don’t need anymore.




// Find the viewstate.

int start = html.IndexOf(@”<input type=””hidden”” name=””__VIEWSTATE””” );

// If we find it, then move it.

if (start > -1)


int end = html.IndexOf(“/>”, start) + 2;


string strviewstate = html.Substring(start, end – start);

html = html.Remove(start, end – start);


// Find the end of the form and insert it there.

int formend = html.IndexOf(@”</form>”) – 1;

html = html.Insert(formend, strviewstate);



// Send the results back into the writer provided.







Step 2 :

Inherit your aspx pages from the base class.


public partial class Page : WebPageBase.PageBase


// Your code here


ASP.Net 4.0 Enahanced Feature

  • Web.config changes

    In .Net Framework 4.0, the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows web.config file to be empty or contains 2 or 3 customized entry.

    • Permanently Redirecting a Page

      . In ASP.NET, developers have traditionally handled requests to old URLs by using by using the Response.Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URLs.

      ASP.NET 4 adds a new RedirectPermanent helper method that makes it easy to issue HTTP 301 Moved Permanently responses, as in the following example:

      • RedirectPermanent(“Newpage.aspx”);

      • Compression of Session

      ASP.NET provides two default options for storing session state across a Web farm: a session-state provider that invokes an out-of-process session-state server, and a session-state provider that stores data in a Microsoft SQL Server database. Because both options involve storing state information outside a Web application’s worker process, session state has to be serialized before it is sent to remote storage. Depending on how much information a developer saves in session state, the size of the serialized data can grow quite large.

      ASP.NET 4 introduces a new compression option for both kinds of out-of-process session-state providers. When the compressionEnabled configuration option shown in the following example is set to true, ASP.NET will compress (and decompress) serialized session state by using the .NET Framework System.IO.Compression.GZipStream class

      <sessionState mode=”SqlServer”

      sqlConnectionString=”data source=servername;Initial Catalog=aspnetstate”

      allowCustomSqlDatabase=”true” compressionEnabled=”true” />

      • Expanding the Range of Allowable URLs

        ASP.NET 4 introduces new options for expanding the size of application URLs. Previous versions of ASP.NET constrained URL path lengths to 260 characters, based on the NTFS file-path limit. In ASP.NET 4, you have the option to increase (or decrease) this limit as appropriate for your applications, using two new httpRuntime configuration attributes. The following example shows these new attributes.

        ASP.NET 4 also enables you to configure the characters that are used by the URL character check.

        When ASP.NET finds an invalid character in the path portion of a URL, it rejects the request and issues an HTTP 400 error.

        <httpRuntime maxRequestPathLength=”260″ maxQueryStringLength=”2048″

        requestPathInvalidChars=”&lt;,&gt;,*,%,&amp;,:,\,?” />

        • CSS Friendly Menu control

          Menu control will Render in <ul> and <li> instead of table. You can specify its property Renderingmode=”list”

          1. Performance Monitoring for Individual Applications in a Single Worker Process

          In order to increase the number of Web sites that can be hosted on a single server, many hosters run multiple ASP.NET applications in a single worker process. However, if multiple applications use a single shared worker process, it is difficult for server administrators to identify an individual application that is experiencing problems.

          ASP.NET 4 leverages new resource-monitoring functionality introduced by the CLR. To enable this functionality, you can add the following XML configuration snippet to the aspnet.config configuration file.

          <?xml version=”1.0″ encoding=”UTF-8″ ?>



          <appDomainResourceMonitoring enabled=”true”/>



          When the appDomainResourceMonitoring feature has been enabled, two new performance counters are available in the “ASP.NET Applications” performance category: % Managed Processor Time and Managed Memory Used. Both of these performance counters use the new CLR application-domain resource management feature to track estimated CPU time and managed memory utilization of individual ASP.NET applications. As a result, with ASP.NET 4, administrators now have a more granular view into the resource consumption of individual applications running in a single worker process.

          • Multi-Targeting

            You can create an application that targets a specific version of the .NET Framework. In ASP.NET 4, a new attribute in the compilation element of the Web.config file lets you target the .NET Framework 4 and later. If you explicitly target the .NET Framework 4, and if you include optional elements in the Web.config file such as the entries for system.codedom, these elements must be correct for the .NET Framework 4. (If you do not explicitly target the .NET Framework 4, the target framework is inferred from the lack of an entry in the Web.config file.)

            The following example shows the use of the targetFramework attribute in the compilation element of the Web.config file.

            <compilation targetFramework=”4.0″/>

            • jQuery Included

              When you create a new website or project, a Scripts folder containing the following 3 files is created:

              • jQuery-1.4.1.js – The human-readable, unminified version of the jQuery library.
              • jQuery-14.1.min.js – The minified version of the jQuery library.
              • jQuery-1.4.1-vsdoc.js – The Intellisense documentation file for the jQuery library.

              Include the unminified version of jQuery while developing an application. Include the minified version of jQuery for production applications.

              In the past, if you used the ASP.NET ScriptManger then you were required to load the entire monolithic ASP.NET Ajax Library. By taking advantage of the new ScriptManager.AjaxFrameworkMode property, you can control exactly which components of the ASP.NET Ajax Library are loaded and load only the components of the ASP.NET Ajax Library that you need.

              • ScriptManager Explicit Scripts

              The ScriptManager.AjaxFrameworkMode property can be set to the following values:

              • Enabled — Specifies that the ScriptManager control automatically includes the MicrosoftAjax.js script file, which is a combined script file of every core framework script (legacy behavior).
              • Disabled — Specifies that all Microsoft Ajax script features are disabled and that the ScriptManager control does not reference any scripts automatically.
              • Explicit — Specifies that you will explicitly include script references to individual framework core script file that your page requires, and that you will include references to the dependencies that each script file requires.

              For example, if you set the AjaxFrameworkMode property to the value Explicit then you can specify the particular ASP.NET Ajax component scripts that you need:

              <asp:ScriptManager ID=”sm1″ AjaxFrameworkMode=”Explicit” runat=”server”>


              <asp:ScriptReference Name=”MicrosoftAjaxCore.js” />

              <asp:ScriptReference Name=”MicrosoftAjaxComponentModel.js” />

              <asp:ScriptReference Name=”MicrosoftAjaxSerialization.js” />

              <asp:ScriptReference Name=”MicrosoftAjaxNetwork.js” />



              • Setting Meta Tags with the Page.MetaKeywords and Page.MetaDescription Properties

              ASP.NET 4 adds two properties to the Page class, MetaKeywords and MetaDescription. These two properties represent corresponding meta tags in your page, as shown in the following example:

              <head id=”Head1″ runat=”server”>

              <title>Untitled Page</title>

              <meta name=”keywords” content=”These, are, my, keywords” />

              <meta name=”description” content=”This is the description of my page” />


              These two properties work the same way that the page’s Title property does.

              1. Enabling View State for Individual Controls

              The ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit. Enabled enables view state for that control and for any child controls that are set to Inherit or that have nothing set. Disabled disables view state, and Inherit specifies that the control uses the ViewStateMode setting from the parent control.

              1. Changes to Browser Capabilities

              ASP.NET determines the capabilities of the browser that a user is using to browse your site by using a feature called browser capabilities. Browser capabilities are represented by the HttpBrowserCapabilities object

              For example, you can use the HttpBrowserCapabilities object to determine whether the type and version of the current browser supports a particular version of JavaScript. Or, you can use the HttpBrowserCapabilities object to determine whether the request originated from a mobile device.

              • Setting Client IDs

                The id attribute in HTML that is rendered for Web server controls is generated based on the ClientID property of the control. Until ASP.NET 4, the algorithm for generating the id attribute from the ClientID property has been to concatenate the naming container (if any) with the ID, and in the case of repeated controls (as in data controls), to add a prefix and a sequential number. While this has always guaranteed that the IDs of controls in the page are unique, the algorithm has resulted in control IDs that were not predictable, and were therefore difficult to reference in client script.

                The 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.

                In some scenarios, such as when you are using master pages, controls can end up with IDs like those in the following rendered HTML:


                This ID is guaranteed to be unique in the page, but is unnecessarily long for most purposes.The easiest way to reduce the length of the rendered ID is by setting the ClientIDMode property as shown in the following example:

                <tc:NamingPanel runat=”server” ID=”NamingPanel1″ ClientIDMode=”Predictable”>

                <asp:TextBox ID=”TextBox1″ runat=”server” Text=”Hello!”></asp:TextBox>


                • ASP.NET Chart Control

                .NET Framework 4 release includes following feature of chart.

                • 35 distinct chart types.
                • An unlimited number of chart areas, titles, legends, and annotations.
                • A wide variety of appearance settings for all chart elements.
                • 3-D support for most chart types.
                • Smart data labels that can automatically fit around data points.
                • Strip lines, scale breaks, and logarithmic scaling.
                • More than 50 financial and statistical formulas for data analysis and transformation.
                • Simple binding and manipulation of chart data.
                • Support for common data formats such as dates, times, and currency.
                • Support for interactivity and event-driven customization, including client click events using Ajax.
                • State management.
                • Binary streaming.
                • ListView Control Enhancements

                The ListView control has been made easier to use in ASP.NET 4. The earlier version of the control required that you specify a layout template that contained a server control with a known ID. The following markup shows a typical example of how to use the ListView control in ASP.NET 3.5.

                <asp:ListView ID=”ListView1″ runat=”server”>


                <asp:PlaceHolder ID=”ItemPlaceHolder” runat=”server”></asp:PlaceHolder>



                <% Eval(“LastName”)%>



                In ASP.NET 4, the ListView control does not require a layout template. The markup shown in the previous example can be replaced with the following markup:

                <asp:ListView ID=”ListView1″ runat=”server”>


                <% Eval(“LastName”)%>



                • CheckBoxList and RadioButtonList Control Enhancements

                  In ASP.NET 3.5, you can specify layout for the CheckBoxList and RadioButtonList using the following two settings:

                  • Flow. The control renders span elements to contain its content.
                  • Table. The control renders a table element to contain its content.

                  In ASP.NET 4, the CheckBoxList and RadioButtonList controls support the following new values for the RepeatLayout property:

                  • OrderedList – The content is rendered as li elements within an ol element.
                  • UnorderedList – The content is rendered as li elements within a ul element.
                  • Default Hashing Algorithm is changed to HMACSHA256

                  ASP.NET uses both encryption and hashing algorithms to help secure data such as forms authentication cookies and view state. By default, ASP.NET 4 now uses the HMACSHA256 algorithm for hash operations on cookies and view state. Earlier versions of ASP.NET used the older HMACSHA1 algorithm.

                  Categories: ASP.Net 4.0