Вы находитесь на странице: 1из 21

Introduction

As most of us know that web pages are stateless and are HTTP-based, which means that it does not automatically indicate whether a sequence of requests is all from the same client or a new Client or even worst whether a single browser instance is still viewing the site. Every time a client requests a page, a new instance of the page is returned and after each roundtrip the page is destroyed. So in nutshell, state is not maintained between client requests by default. Applications ranging from huge shopping sites to small intranet sites depend on the ability to track individual requests from distinct users and store state on behalf of each user, say for e.g., some preferences selected by user. Right from the days of Classic ASP, there are various technologies available for state management. ASP uses cookie, query string, application, session etc. ASP.NET supports all these along with some richer, easier and more powerful mechanisms, which can be used to build robust web applications. ASP.NET not only greatly simplifies the process, but also solves some of the classic ASP Session object's problems like using Sessions with Web farms or web gardens scenarios.

State Management Options


In a broader view there are two ways to manage web page s state. It could be on Clientside and could be on Server-side. Both of these are used depending on the implications and requirements. First we will look into the client side state management options. Client-side state management: Under Client side state management no information is maintained on the server between round trips. Information will be stored in the page or on the client s computer. The following are the various ways in which Client side state can be maintained: y y y y Cookies Hidden Fields View State Query Strings

Cookies: A cookie is a small amount of data stored either in a text file on the client's file system or in-memory of the client browser session. Cookies are mainly used for tracking data settings. Although cookies are typically used to store user-specific configuration information and preferences, they can be used to store any client-specific state needed by an application (as long as that state is converted to string format) An example could be to customize the welcome page based on the user preferences. The following is an example of using Cookies in ASP.NET:

Collapse
HttpCookie nameCookie= new HttpCookie("Name"); nameCookie.Value = TxtName.Text; Response.Cookies.Add(nameCookie);

Hidden Field: A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. ASP.NET provides the HtmlInputHidden control that offers hidden field functionality. Following is the code example in C#: Collapse
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1; //To set a value Hidden1.Value= Test Value assigned to hidden field ; //to retrieve a value string strValue=Hidden1.Value;

Although its name is Hidden , its value is not hidden; you can see its value through view -> source option in the browser. View State: In addition to session state and cookie state, ASP.NET introduces the ability to store client-specific state through a mechanism called view state. View state is stored in a hidden field on each ASP.NET page called __VIEWSTATE. Each time a page is posted to itself, the contents of the__VIEWSTATE field are sent as part of the post. The primary use of view state is for controls to retain their state across post-backs. The following is an example of using ViewState in C#: Collapse
//to save information ViewState.Add( Test , ViewState Sample ); //to retrieve information string test=ViewState[ Test ];

Query Strings: Query strings provide a simple but limited way of maintaining some state information. You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL and so in some cases security may be an issue. A URL with query strings may look like this: http://www.Himanshu.com/list.aspx?Age=27&Count=101. When list.aspx is being

requested, the category and product information can be obtained by using the following codes: Collapse
[c#] string Age, Count; Age =Request.QueryString[ Age ]; Count =Request. QueryString [ Count ];

Server-side state management


In case of Server Side State management, the information will be stored on the server, the good part is that it has higher security but it can use more web server resources. The Server Side State management can again be distributed under two subheads: In Process State Management and Out of Process State Management. In Process State Management talks about Application and Session objects while Out of process State Management talks about storing state in SQL Server or State Server provided by .NET. Let us explore each one of them in detail. In Process State Management Configuring In-process Mode In-process is the default session state mode. To use in-process mode, set the mode attribute of the <SESSIONSTATE> element to Inproc. The following shows a sample configuration setting for in-process mode: Collapse
<configuration> <system.web> <sessionState mode="Inproc" cookieless="false timeout="20"/> </sessionState> </system.web> </configuration>

Application object The Application object provides a mechanism for storing data that is accessible to all code running within the Web application. The information that is global to the application may be stored in application objects. For efficiency, this state is typically stored once and then read from many times. There are various issues, which a programmer should consider before using Application Variables. The programmer should consider issues like memory occupation, concurrency and synchronization implications of storing and accessing a global variable within a multithreaded server environment, the scalability of Application level variables as they can not be shared across a Web farm (in which an application is hosted by multiple servers) or a Web garden (in which an application is hosted by multiple processes on the same server).

In spite of these issues, well-designed application-level variables can be very powerful in Web applications. You can do a one-time (or infrequent) loading and calculation of information and then use application state to cache it for speedy, in-memory access during later Web requests. Session object Session object can be used for storing session-specific information that needs to be maintained between server round trips and between requests for pages. Session object is per-client basis, which means different clients generate different session objects. The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session. Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing URL-legal ASCII characters. SessionID values are generated using an algorithm that ensures uniqueness and SessionIDs are generated on random basis, which makes it harder to guess the session ID of an existing session. Depending on the configuration settings, the SessionIDs are communicated across client-server requests either by an HTTP cookie or a modified URL. The following is an example of storing Session value in ASP.NET: Collapse
//to store information Session[ UserName ]= Himanshu ; //to retrieve information myname=Session[ UserName ];

Storing Session State out of Process ASP.NET introduces the ability to store session state out of process, which can be set using the sessionState element in an ASP.NET application'sweb.config file. The default location is in-process, as it was in classic ASP. If the mode attribute is set to StateServer or SqlServer, however, ASP.NET manages the details of saving and restoring session state to another process or to an SQL Server database. This is appropriate because it is possible to build ASP.NET applications that access session state in the normal way, and then by switching the sessionState mode in a configuration file, that same application can be deployed safely in a Web farm environment. Storing State in SQL Server Database One of the widely used options for storing session state outside the server process is to keep it in an SQL Server database. ASP.NET supports this through the SQLServer mode in the sessionState configuration element in web.config file. For using this mode, you must run the InstallSqlState.sqlscript on the database server where session state will be stored. This script can be found in the main Microsoft.NET directory. As soon as you run the script, it creates a table that can store client-specific state indexed by session ID in the tempdb of

that SQL Server. The ASP state table is created in the tempdb database, which is not a fully logged database, thus increasing the speed of access to the data. Following is an example of configuring web.config file to use SQL Server: Collapse
<configuration> <system.web> <sessionState mode = "SQLServer" "data source=192.168.1.103;user id=sa;password=" /> </sessionState> </system.web> </configuration>

Database enables you to store large amount of information pertaining to state in your Web application. Sometimes users continually query the database by using the unique ID, you can save it in the database for use across multiple request for the pages in your site. The ASP.NET State Service The State Service can run either on the same machine as the Web application or on a dedicated server machine. The .NET Framework providesaspnet_state.exe that could be used as a service to maintain state. Using the State Service option is useful when you want out-of-process session state management but do not want to have to install SQL Server on the machine hosting the state. Following is an example of configuring web.config file to use State Server: Collapse
<configuration> <system.web> <sessionState mode="StateServer" stateConnectionString="10.1.1.29:23454"/> </sessionState> </system.web> </configuration>

Conclusion
In this article, I have tried to give a complete overview of the state management options provided in .NET. Though ASP.NET has more functions and utilities than ASP to enable you to manage page state more efficiently and effectively, the developer should consider all the pros and cons of using them and take some time to decide which one would be best applied to the application. The following are the issues, which a developer should think about before making any choice. y y How important is the information? The amount of information or the data, which needs to be stored.

y y

Whether persistent or in-memory cookies can be used with the Client? The place where the information will be stored, i.e., the Client or the Server.

Considering all these, let's try our best to unleash the power of ASP.NET in the most efficient and elegant way.

License
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here

Table of Contents
y y y y y Introduction Overview ASP.NET Application Folders Advantages of ASP.NET Application Folders Different Types of Application Folder Details of Application Folders o App_Code Folder o Bin Folder o App_Data Folder o App_Theme Folder o App_Browser Folder o App_WebReference Folder o Resource Folders  App_LocalResource Folder  App_GlobalResource Folder Summary

Introduction
First of all I would like to thank Sean Ewington for his article Beginner's Walk - Web Development, which gives me a great opportunity to write an article for beginners on ASP.NET web development here on CodeProject. After writing articles on caching and view state for beginners, I have decided to write an article for beginners on the ASP.NET Application Folders. However, I will be back with another article on rest of state management. Like my other articles, I believe this will also give you very good idea on the Application Folders. Please give your valuable suggestions and ideas for improvement that I can incorporate into this article, as well as my future articles.

Overview - ASP.NET Application Folders

ASP.NET 2.0 uses a file-based approach. That means, all class files, resource files, data files and folders are maintained in a hierarchical structure. If we are working with ASP.NET 2.0, we can add files and folders using the Add Items option. If we look at a sample application hierarchy, it will look like the following figure.

We can add as many as files and folders as we like (according to our requirements) within our solutions,and it won't be necessary to recompile them each and every time they are added. It is ASP.NET'stask to dynamically compile them when required. So, what ASP.NET 2.0 does is, it uses a predefined folder structure containing the files (classes, images, resources, etc.), to compile them dynamically and we can access those files throughout the application. ASP.NET also provides special folders to maintain files and resources. Let's see the advantages of using these folders.

Advantages of ASP.NET Application Folders


Following are the main advantages of use of ASP.NET's Application Folders y y y y We can maintain resources (classes, images, code, databases, themes) in an organized manner, which allows us to develop and maintain sites easily All files and folders are accessible through the application We can add as many files as required Files are compiled dynamically when required

Different Types of Application Folder


ASP.NET treats the following folders in a special manner. They are:

y y y y y y y y

App_Code Bin App_Data App_Theme App_Browser App_WebReference App_LocalResource App_GlobalResource

Details of the Application Folders


Now, to look at the use of these folders, I am going to start from App_Code.

App_Code Folder
As its name suggests, the App_Code Folder stores classes, typed data sets, etc. All the items that are stored in App_Code are automatically accessible throughout the application. If we store any class files (like .cs or .vb) it compiles them automatically. It automatically creates type data sets from .xsd(XML schema) files, and creates XML web service proxy classes from WSDL.Let's have a look at how we can use the App_Code folder. We can add an App_Code folder, by Solution File right click Add ASP.NET Folder App_Code. The App_Code folder is now added to your application.

Note: Try to add one more App_Code folder by using the same steps. Oops... the App_Code folder is no longer available there. So, ASP.NET allows you to add an App_Code folder only once. Now we can add new items like classes, text and xml files into the App_Code folder and we can also add existing files there.

Let's have a look at one example that shows how it works. Into the App_Code folder, I have added a class MyCSharpClass.cs.

In that class I have written a small spice of code for adding two numbers.

Now, Try to access this class, from any where in your application. You will see that MyCSharpClassis accessiblethroughout the application.

If we want to store different classes like .cs or .vb, then what will happen? If we kept both .cs and .vb classes in the same folder, it will give following compilation error:

This is because all the classes contained in the App_Code folder are built into a single assembly and it can't have different languages at root level, or even at child level folders in following manner:

We have a solution to overcome this problem. We have to create separate folders for C# and for VB or other classes.

Store class files separately in those folders and an configure the folder hierarchy in the web.config file.

Now I will move to our next part -the Bin folder.

Bin Folder
The Bin folder is used for keeping assemblies inside it. We can access those as a reference from anywhere of our web application. Use of Bin folder comes into the picture if we use any class library within our web application. Suppose we are creating a class library called TestLib After building the library, we will get TestLib.dll. Now, right click on solution file Add References Project, select the TestLibProject, click on OK. Check the Binfolder, it will contain TestLib.dll and TestLib.pdb files.

Assemblies in the Bin folder do not need to registered on the system, ASP.NET recognizes the presence of DLLs inside the Bin Folder. Keeping .pdb files inside Bin folder helps us in debugging. The main limitation of storing assemblies in the Bin folder is that their scope is

limited to the current application. Therefore, they cannot access any code outside of current web application. [Source] Next, let's have a look at App_Data folder

App_Data Folder
The App_Data folder is used as a ata storage for the web application. It can store files such as .mdf, .mdb, and XML. It manages all of your application's data centrally. It is accessible from anywhere in your web application.The real advantage of the App_Data folder is that, any file you place there won't be downloadable. We can add .mdf files to the App_Data folder directly by selecting Add New Item. From there we can a create table, procedure or function without opening SQL Server.Now if we want to add that data to our application, we can easily use it.

Now, look at the connection string that we need to write for accessing the App_Data folder's databases.

We can connect with MyDB.mdf database using this connection string. Check the example below, which I have used to read the table data from theMyDB.Mdf file. /p>

App_Theme Folder
If you want to give your web sites a consistent look, then you need to design themes for your web application. The App_Themes folder contains all such themes. An App_Theme folder can contain two subfolders; one for CSS files and the other for skin files. When we add an App_Theme folder, a subfolder with name Theme1 will be automatically created. We can change the name of the theme folder as per our requirements.

I will not cover how to create skin files or CSS file in this article, my main concern here is how to apply them. You can easily find the details ofskins and CSS via Google. Now that we have to apply the theme to the page, there are several way to do that. We could set the theme from aspx page using a page directive in following way:

While we are going to set themefrom aspx page, the list of themes available to us is as shown in the figure. We can set the theme from the code behind file also, and we can even change theme at runtime (using HttpHandler.

App_Browser Folder
The App_Browser folder contains browser information files (.browser files). These files are XML based files which are used to identify the browser and browser capabilities. You will find the browser files in the following location:

If you want to change a .browser file, just copy the file to the App_Browser folder and change it. You can create new browser files by just clicking onAdd New Item of the App_Browser folder

As I already mentioned, a browser file is a configuration file, it generally looks like this:

See here for more information

App_WebReference Folder
As the name suggests, the App_WebReference folder contain references to any web services. If we added any web services with our web application, they go automatically into the App_WebReference folder, in the same way as in windows applications, if we added any DLLs, they would go under theReference folder.

Resources Folders
Before starting on the App_GlobalResource and App_LocalResource folders, I would like to give a small introduction on ASP.NET resources. If you are, say, creating sites for a multinational company, or a public web sites that can be accessible from all over the world, you need to consider the best way to address users in different cultures and different countries in different languages. ASP.NET provides the infrastructure to create web applications that automatically adjust formatting and language according to the user's preferences, by using resource files.The main purpose of resource files islocalization of the web application. ASP.NET uses resource files to make supporting multiple languages simpler. Visual Studio 2005 can automatically generate XML resource files that contain text for your controls in different languages. When a user visits the sites, they can change the languages of the sites based on their preference. There are two type of resources: y y Local resources Global resources

The App_LocalResource folder contain local resource files and the App_GlobalResource folder contains global resource files. App_LocalResource Folder Local resources are specific to a single web page, and should be used for providing multilingual functionalityon a web page. Local resources must be stored in the App_LocalResource subfolder of the folder containing the web page. Because you might have local resources for every page in your web application, you might have App_LocalResource subfolders in every folder.

Resource file names should be like <pageName>[.langauge].resx. Some examples of local resource files are, Mypage.aspx.ex.resx andMypage.aspx.de.resx. Default.aspx.resx is the base resource file to use if no other resource file matches with the user's current culture. If you want to create local resources for a page, open the design view of the page and then from Tool Menu select Generate Local Resource. You will then see that a resource file is automatically created in the corresponding App_LocalResource folder.

Note: Default2.aspx.resx is the resource file for Default2.aspx, and Others.aspx.resx is the resource file for Others.aspx. Both resource files are inside the App_LocalResource folder. The following code shows you the XML code for the resource file. To change the resource file, we can either change the XMLdirectly or use the Resource Editor.

If we change anything on the page, the resource file will be automatically updated. If you want a test application for Local_Resource, just create a copy of Default2.aspx.resx and rename it to default2.aspx.fr.resx (for French resources). Now, as a test, I have changed the button's tool tipfor the French resource to "French ToolTip". Now change your web browser settings and set French as the default culture.

(For Internet Explorer, use Tools Internet options top of the list and test the application)

Languages, add French to the

Test the button tool tip in this way, and you can test it for other languages also.

App_GlobalResource Folder The App_GlobalResource folder can be read from any page or code that is anywhere in the web site. Global resources must be stored in theApp_GlobalResource folder at the root of the application. We should use the App_GlobalResource folder when we need a single resource for multiple web pages. We candefine ASP.NET control properties by manually associating them with resources in global resource files.You can add a global resource file by right clicking on the App_GlobalResource folder and clicking on Add Items. Add .resx files as resources.

We can access these resources programmatically by using the Resource.Resourceobject. E.g.: Collapse
Label1.Text = Resource.Resource.MyText

We can use the GetLocalResourceObject()and GetGlobalResourceObject()methods to access global resources, and then cast them to the correct type. Collapse
Label1.Text = GetLocalResourceObject("Label1.Text").ToString();

Summary
I have explained in this article all about the use of application folders that are available in ASP.NET. I hope I have described them well enough for you to understand. There is lots more to learn, like how to design themes and skins, and working with resource files. I am giving some reference links at the end, that can help you in further study. Please read these links, at least the one on resources, which are a very important part of ASP.NET 2.0. In future I plan to write an article for beginners on ASP.NET Resources. But not now.

Thanks for reading, and please don't forget to give your suggestions!

Вам также может понравиться