Why some of the ASP.NET web controls Require ViewState under any circumstances?

By Mohammad Mahdi Ramezanpour at May 09, 2010 10:33
Filed Under: ASP.NET

The first thing you should know before I continue is the definition of ViewState:

View state refers to the page-level state management mechanism, utilized by the HTML pages emitted by ASP.NET applications to maintain the state of the web form controls and widgets. The state of the controls is encoded and sent to the server at every form submission in a hidden field known as __VIEWSTATE. The server sends back the variable so that when the page is re-rendered, the controls render at their last state. At the server side, the application may change the ViewState, if the processing requires a change of state of any control. The states of individual controls are decoded at the server, and are available for use in ASP.NET pages using the ViewState collection.

When you’re developing an ASP.NET Web-Forms application and the performance is a consideration, you can disable the ViewState in some of your pages that you don’t want to make use of. Disabling ViewState will affect the page’s HTML source code a lot and removes a lot of useless codes from your page as you can see in the picture below:

A website that disabled the ViewState:

APageWithoutViewstateEnabled 

Another website that let the ViewState being enabled:

PageWithViewStateEnabled

You can see the difference between two pictures above. So disabling the ViewState is something necessary if you don’t want to use it.

But unfortunately, some of the controls in ASP.NET such as RadioButtonList need to use the ViewState under any circumstances! So you CANNOT disable the ViewState if you need to use these kinds of controls.

I think is an ASP.NET bug so I reported is to the Microsoft. I believe, about 70%-80% of ASP.NET developers don’t want to use the ViewState at least in some of their pages.

IIS 7 URL Rewrite extension and OutputCache conflict

By Mohammad Mahdi Ramezanpour at April 23, 2010 06:30
Filed Under: ASP.NET, IIS

These days, I’m developing a new .NET website which is hosted by Windows Server 2008 R2 and IIS 7.5. For some purposes, I was using the “Intelligencia.UrlRewriter” module which was introduced by Scott Guthrie and everything is working fine on my Windows Server 2003 and IIS 6 home server. I also tested it on my development machine which has a Windows 7 Ultimate installed and everything was going well.

For some security reasons, my hosting company restricted using rewrite modules and they suggested me to use IIS 7 native URL Rewrite extension.

During the migrating process, I realized that the “~” operator is not working correct! Fortunately Ruslan Yakushev was explained about the “~” failure in URL Rewrite module:

You can use the ~ operator in ASP.NET Web server controls to reference the root of the application directory when you need to set a path. However, if URL rewriting changes the directory hierarchy of the requested URL, this can cause links that are specified with the ~ operator to be resolved incorrectly. For example, imagine that the Default.aspx page at the root of a Web application named app1 contains the following Image control:

<asp:Image runat="server" ImageUrl="~/Images/MyImage.gif" />

If URL rewriting changes the URL from http://localhost/app1/folder/file to http://localhost/app1/default.aspx, the links that are specified with the ~ operator will be resolved relative to the rewritten URL path, which would be relative to the /app1 folder. The following example shows the resulting HTML markup for the img element:

<img src="Images/MyImage.gif" ... >

Because the browser requested http://localhost/app1/folder/file, it will try to obtain the image from http://localhost/app1/folder/Images/MyImage.gif. This results in a 404 (File Not Found) error.

The URL Rewrite module for IIS 7.0 includes an update for ASP.NET that fixes this behavior. The update causes the ~ operator in Web server controls to be resolved relative to the originally requested URL. In the previous example, the HTML markup in the response will contain the correct URL path for the img element, as shown in the following markup:

<img src="../Images/MyImage.gif" ... >

The update for ASP.NET applies only to .NET Framework 3.5 SP1 and later. In order to get the update, upgrade the .NET Framework to version 3.5 SP1 and then run the IIS 7.0 URL Rewrite module installer, which will install the ASP.NET update.

But my problem didn’t solve! Even check my web server and saw that it has .NET Framework 3.5 SP1 and UrlRewiter 2.0 installed!!!

After lots of challenges, I realized, the “~” operator in my user controls that has the Output cache directive enabled, doesn’t work well and after I omitted the @OutputCache from my user control, everything was back to normal. Note that if you don’t use the UrlRewrite module in your application, everything will be working well, even if you set the OutputCache directive and I think it’s a bug that should be reported to the Microsoft.

I hope it helps.

Oxite, An open source CMS based on ASP.NET MVC by Microsoft

By Mohammad Mahdi Ramezanpour at December 09, 2008 20:30
Filed Under: Microsoft, ASP.NET, ASP.NET MVC, LINQ, SQL Server

 Oxite Logo - Photo taken from http://www.codeplex.com/oxite I know it’s a little old but in this post I want to talk about Oxite.

Oxite is a new open source blogging system based on ASP.NET MVC which built by Erik Porter, Nathan Heskew, Mike Sampson and Duncan Mackenzie.

This is a simple blog engine written using ASP.NET MVC, and is designed with two main goals:

· To provide a sample of 'core blog functionality' in a reusable fashion. Blogs are simple and well understood by many developers, but the set of basic functions that a blog needs to implement (trackbacks, RSS, comments, etc.) are fairly complex. Hopefully this code helps.

· To provide a real-world sample written using ASP.NET MVC.

As they said, this blog engine built not only for developers and as sample and this has been used in MIX Online too.

Here is some other information from http://visitmix.com/lab/oxite:

Oxite was developed carefully and painstakingly to be a great blogging platform, or a starting point for your own web site project with CMS needs. Its line-up of sexy attributes includes: provider-based architecture allowing you to swap out database and search providers (SQL Server DB, local and Live search providers included), built for testability and hence most likely to be voted "hottest in class" by TDD fans (repositories, everything has an interface, etc.), database file and string resource storage so that files get stored in database and strings stored for localization, built to take full advantage of ASP.NET MVC but broken into assemblies so that even ASP.NET WebForm developers can use the data backend and utility code, supports use of Visual Studio Team Suite (DB Pro, Test, etc.), and Background Services Architecture (sending trackbacks, emails, etc. all done as a background process to prevent delays on the web site itself).

Download it now and get some other information by click here

Manage your users with the new ASP.NET 3.5 Personalization feature – Part 1

By Mohammad Mahdi Ramezanpour at December 01, 2008 11:59
Filed Under: ASP.NET, XML

Nearly all developers who’re developing web applications have been working with sessions, cookies, etc.

For example, when you want to authenticate your users you store you user’s authentication information in sessions and cookies. Previously, I posted about ASP.NET Form Authentication which most of ASP.NET developer are working with it because it’s one of the most stable ways for user authentications.

ASP.NET 3.5 provides a new feature named “Personalization” that has very flexible infrastructure enables you to store user’s information in server not client (Cookies store information on client computers). In this post, I’m going to show you how you can use profiles and I’m sure you’ll love it.

ASP.NET has a deep focus on web.config file. You can do lots of things in your configuration file. In order to work with profiles you need to let ASP.NET what user data you want to store. So you have to add some elements to you web.config file:

<system.web>
 
    <profile>
        <properties>
            <add name="FirstName"/>
            <add name="LastName"/>
            <add name="Age" type="System.Int32"/>
        </properties>
    </profile>
    
</system.web>

Web.Config file properties are accessible in code-behind - Photo taken by myselfAs you can see in the code, you determine what properties your profile should have. You can add them very easily and Visual Studio IntelliSense will help you too.

When you added your custom properties you can see them in code-behind so you can get or set you profile information.

Notice that “Age” property in the above code snippet, I just assigned a type attribute for it. It means that you can also specify the type of a property for example:

· string: System.String

· bool: System.Boolean

· int: System.Int32

· …

You can also assign your custom type. For example, imaging you want to store user’s cart information. You can store information in a class and then set the type of your profile property to that class. Here is an example:

<Serializable()> _
Public Class Cart
 
    Private _ProductName As String
    Private _Price As Decimal
    Private _Quantity As Int16
 
    Public Property ProductName() As String
        Get
            Return _ProductName
        End Get
        Set(ByVal value As String)
            _ProductName = value
        End Set
    End Property
 
    Public Property Price() As Decimal
        Get
            Return _Price
        End Get
        Set(ByVal value As Decimal)
            _Price = value
        End Set
    End Property
 
    Public Property Quantity() As Int16
        Get
            Return _Quantity
        End Get
        Set(ByVal value As Int16)
            _Quantity = value
        End Set
    End Property
 
End Class

Note that the class must be Serializable.

Now you can add your property with your custom type:

<add name="Cart" type="Cart" serializeAs="Binary" />

You can also provide default values for your properties. It means if you leave your property with no value, a default value will be replace with null:

<add name="Active" type="System.Boolean" defaultValue="false"/>

It possible to make your properties read-only:

<add name="Active" type="System.Boolean" readOnly="true"/>

I the next part, I’ll show you how to store profile information in a data source such as SQL Server, XML, etc.

How to create a tab control using ASP.NET and JavaScript

By Mohammad Mahdi Ramezanpour at November 16, 2008 19:54
Filed Under: .NET General, ASP.NET, Web design, JavaScript

It may happen to any ASP.NET Developer that the customers want to have a Tab Control in their websites. There are many ASP.NET components such as Telerik RAD Controls, ComponentArt, DevExpress, etc. which can help you out in this but sometimes they are expensive for your project capacity.

In this post, I’m going to show you how you can create a very simple Tab Control using ASP.NET and JavaScript.

You can do lots of thing in order to create a Tab Control but what I’m going to do is to create a class that is inherited from System.Web.UI.WebControl:

    public class TabControl : System.Web.UI.WebControls.WebControl
    {
    }

You can make your Tab Control flexible by adding some properties to it. For example, enable your developers to set CssClass to a TabItem:

 

private string _MainCssClass;
private string _ItemCssClass;
private string _InActiveCssClass;
private string _ActiveCssClass; 
private Unit _ItemWidth = 70;
private HorizontalAlign _HorizontalAlign = HorizontalAlign.NotSet;
private string _LinkCssClass;

They’re OK; but the interesting part is to use of a string array in order to store TabItem names:

private string[] _TabNames = { "Item1", "Item2" };

This is also a property, so developers can add their own items. Another important property is a list of Panels of those TabItems. Actually, Panels are the content of each TabName:

private List<Panel> _Panels = new List<Panel>();

In the field above, developers can add their specified panels for each TabItem. The most important method in creating custom web controls is the Render() method which enable you to design your control using HTML tags. Here is my Render() method:

 

protected override void Render(System.Web.UI.HtmlTextWriter w)
{
    if (_Panels.Count == 0 || _Panels == null)
        throw new NullReferenceException("Please specify at least one panel.");
 
    w.WriteLine("<!-- Developed by Mohammad Mahdi Ramezanpour. © 2008 Marlik. -->");
    w.WriteLine(String.Format(@"<table cellpadding=""0"" cellspacing=""0""
    class=""{0}""><tr id=""MarlikTabControl"">", _MainCssClass));
    foreach (Panel p in this.Panels)
    {
        cols.Add("Tab_" + _itemIndex);
        w.WriteLine(String.Format(@"<td onmouseover=""javascript:this.style.cursor='hand';""
        class=""{0} {3}"" align=""{5}"" id=""Tab_{4}"" 
        onclick=""ShowTabContent('{1}', 'Tab_{4}');"" width=""{2}"">",
         _ItemCssClass, p.ClientID, this._ItemWidth, this._InActiveCssClass, 
         this._itemIndex, this._HorizontalAlign.ToString()));
        w.WriteLine(String.Format(@"<a class=""{1} {2}"">{0}</a>",
        _TabNames[_itemIndex], _LinkCssClass,  _ItemCssClass));
        _itemIndex++;
        w.WriteEndTag("td");
    }
    w.Write("</tr></table>");
    w.WriteLine(JavaFunctions().ToString());
    base.Render(w);
}

How it works?

In the first I checked for available panels and if there was no panels so an exception will be throwing using NullReferenceException.

As you know, there is a writer parameter as System.Web.UI.HtmlTextWriter in Render() method that enable you to generate HTML codes in your web component. You have to use that if you want to use HTML or any client-side code in your web control. Add I did above is to create a HTML <table></table> tag but rows and columns will be generating dynamically using HtmlTextWriter.

You can download the full code here: TabControl

Currently Reading

Quote of the day

Send Persian SMS