Saturday, July 12, 2008

STATE MANAGEMENT

What is ViewState?

ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

Why should we have to move from inproc session to outproc session

I was using Inprocess session objects, but incase of aspnet process crashes the session objects were lost as a result I decided to shift to out of porocess session objects. For this i had to serialize the objects. While doing that I made the classes serializable whose objects I store in sessions. However, when I run the application I get the following error.

Unable to serialize the session state. Please note that non-serializable objects or MarshalByRef objects are not permitted when session state mode is 'StateServer' or 'SQLServer'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Unable to serialize the session state. Please note that non-serializable objects or MarshalByRef objects are not permitted when session state mode is 'StateServer' or
'SQLServer'.

What is the lifespan for items stored in ViewState?

Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).

What does the "EnableViewState" property do? Why would I want it on or off?

It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.


What are the different types of Session state management options available with ASP.NET?

ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

Application and Session Events

The ASP.NET page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops:

• Application events are raised for all requests to an application. For example, Application_BeginRequest is raised when any Web Forms page or XML Web service in your application is requested. This event allows you to initialize resources that will be used for each request to the application. A corresponding event, Application_EndRequest, provides you with an opportunity to close or otherwise dispose of resources used for the request.

• Session events are similar to application events (there is a Session_OnStart and a Session_OnEnd event), but are raised with each unique session within the application. A session begins when a user requests a page for the first time from your application and ends either when your application explicitly closes the session or when the session times out.
You can create handlers for these types of events in the Global.asax file.

Difference between ASP Session and ASP.NET Session?

asp.net session supports cookie less session & it can span across multiple servers.

What is cookie less session? How it works?

By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. If cookies are not available, a session can be tracked by adding a session identifier to the URL. This can be enabled by setting the following:

http://samples.gotdotnet.com/quickstart/aspplus/doc/stateoverview.aspx

How you will handle session when deploying application in more than a server? Describe session handling in a webfarm, how does it work and what are the limits?

By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. Additionally, ASP.NET can store session data in an external process, which can even reside on another machine. To enable this feature:

• Start the ASP.NET state service, either using the Services snap-in or by executing "net start aspnet_state" on the command line. The state service will by default listen on port 42424. To change the port, modify the registry key for the service: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port
• Set the mode attribute of the section to "StateServer".
• Configure the stateConnectionString attribute with the values of the machine on which you started aspnet_state.
The following sample assumes that the state service is running on the same machine as the Web server ("localhost") and uses the default port (42424):

Note that if you try the sample above with this setting, you can reset the Web server (enter iisreset on the command line) and the session state value will persist.
**
What method do you use to explicitly kill a users session?

Abandon()

What are the different ways you would consider sending data across pages in ASP (i.e between 1.asp to 2.asp)?

Session
public properties

ASP.NET supports three modes of session state:

• InProc: In-Proc mode stores values in the memory of the ASP.NET worker process. Thus, this mode offers the fastest access to these values. However, when the ASP.NET worker process recycles, the state data is lost.

• StateServer: Alternately, StateServer mode uses a stand-alone Microsoft Windows service to store session variables. Because this service is independent of Microsoft Internet Information Server (IIS), it can run on a separate server. You can use this mode for a load-balancing solution because multiple Web servers can share session variables. Although session variables are not lost if you restart IIS, performance is impacted when you cross process boundaries.

• SqlServer: If you are greatly concerned about the persistence of session information, you can use SqlServer mode to leverage Microsoft SQL Server to ensure the highest level of reliability. SqlServer mode is similar to out-of-process mode, except that the session data is maintained in a SQL Server. SqlServer mode also enables you to utilize a state store that is located out of the IIS process and that can be located on the local computer or a remote server.

What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state?

Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip.
To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips.
However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
Client-Based State Management Options:
View State
Hidden Form Fields
Cookies
Query Strings
Server-Based State Management Options
Application State
Session State
Database Support

What are the disadvantages of view state / what are the benefits?

Automatic view-state management is a feature of server controls that enables them to repopulate their property values on a round trip (without you having to write any code). This feature does impact performance, however, since a server control's view state is passed to and from the server in a hidden form field. You should be aware of when view state helps you and when it hinders your page's performance.

When maintaining session through Sql server, what is the impact of Read and Write operation on Session objects? will performance degrade?

Maintaining state using database technology is a common practice when storing user-specific information where the information store is large. Database storage is particularly useful for maintaining long-term state or state that must be preserved even if the server must be restarted.
**

What are the contents of cookie?
**

How do you create a permanent cookie?
**

What is ViewState? What does the "EnableViewState" property do? Why would I want it on or off?
**

Explain the differences between Server-side and Client-side code?

Server side code will process at server side & it will send the result to client. Client side code (javascript) will execute only at client side.


Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
**

Which ASP.NET configuration options are supported in the ASP.NET implementation on the shared web hosting platform?

A: Many of the ASP.NET configuration options are not configurable at the site, application or subdirectory level on the shared hosting platform. Certain options can affect the security, performance and stability of the server and, therefore cannot be changed. The following settings are the only ones that can be changed in your site’s web.config file (s):
browserCaps
clientTarget
pages
customErrors
globalization
authorization
authentication
webControls
webServices
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetconfiguration.asp

Briefly describe the role of global.asax?

How can u debug your .net application?

How do u deploy your asp.net application?

Where do we store our connection string in asp.net application?

Various steps taken to optimize a web based application (caching, stored procedure etc.)

How does ASP.NET framework maps client side events to Server side events.

Caching Options in ASP.NET

ASP.NET supports three types of caching for Web-based applications:


Page Level Caching (called Output Caching)
Page Fragment Caching (often called Partial-Page Output Caching)
Programmatic or Data Caching

We'll look at each of these options, including how, and when, to use each option to increase your site's performance!

Output Caching

Page level, or output caching, caches the HTML output of dynamic requests to ASP.NET Web pages. The way ASP.NET implements this (roughly) is through an Output Cache engine. Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML is sent as a response; otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.

Output Caching is particularly useful when you have very static pages. For example, the articles here on 4GuysFromRolla.com are very static. The only dynamic content is the banners, the dynamic selection being performed on a separate ad server. Hence, the articles on 4Guys would be prime candidates for Output Caching.

Output caching is easy to implement. By simply using the @OuputCache page directive, ASP.NET Web pages can take advantage of this powerful technique. The syntax looks like this:

<%@OutputCache Duration="60" VaryByParam="none" %>
[See a live demo!]

The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache. When the duration expires, the cache becomes invalid and, with the next visit, the cached content is flushed, the ASP.NET Web page's HTML dynamically generated, and the cache repopulated with this HTML. The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached. In other words, multiple versions of a page can be cached if the output used to generate the page is different for different values passed in via either a GET or POST.

The VaryByParam is a useful setting that can be used to cache different "views" of a dynamic page whose content is generated by GET or POST values. For example, you may have an ASP.NET Web page that reads in a Part number from the QueryString and displays information about a particular widget whose part number matches the QueryString Part number. Imagine for a moment that Output Caching ignored the QueryString parameters altogether (which you can do by setting VaryByParam="none"). If the first user visited the page with QueryString /ProductInfo.aspx?PartNo=4, she would see information out widget #4. The HTML for this page would be cached. The next user now visits and wished to see information on widget #8, a la /ProductInfo.aspx?PartNo=8. If VaryByParam is set to VaryByParam="none", the Output Caching engine will assume that the requests to the two pages are synonymous, and return the cached HTML for widget #4 to the person wishing to see widget #8! To solve for this problem, you can specify that the Output Caching engine should vary its caches based on the PartNo parameter by either specifying it explicitly, like VaryByParam="PartNo", or by saying to vary on all GET/POST parameters, like: VaryByParam="*".

Partial-Page Output Caching

More often than not, it is impractical to cache entire pages. For example, you may have some content on your page that is fairly static, such as a listing of current inventory, but you may have other information, such as the user's shopping cart, or the current stock price of the company, that you wish to not be cached at all. Since Output Caching caches the HTML of the entire ASP.NET Web page, clearly Output Caching cannot be used for these scenarios: enter Partial-Page Output Caching.

Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached. ASP.NET provides a way to take advantage of this powerful technique, requiring that the part(s) of the page you wish to have cached appear in a User Control. One way to specify that the contents of a User Control should be cached is to supply an OutputCache directive at the top of the User Control. That's it! The content inside the User Control will now be cached for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content. (Note that for this you should not place an OutputCache directive in the ASP.NET Web page that contains the User Control - just inside of the User Control.)

Now that we've tackled Output Caching and Fragment Caching, there is still one more caching technique worth discussing: Data Caching. In Part 2 we'll examine what, exactly, Data Caching is and how you can use it to improve the performance of your ASP.NET Web pages. We'll also examine a really cool, real-world caching demo!
In Part 1 we looked at how to use Output Caching and Fragement Caching of an ASP.NET Web page. These two techniques cached either the full HTML output of an ASP.NET Web page, or a portion of the HTML output of an ASP.NET Web page (by caching the HTML output of a User Control). In this part, we'll examine Data Caching, which is an in-memory cache used for caching objects.

Data Caching

Sometimes, more control over what gets cached is desired. ASP.NET provides this power and flexibility by providing a cache engine. Programmatic or data caching takes advantage of the .NET Runtime cache engine to store any data or object between responses. That is, you can store objects into a cache, similar to the storing of objects in Application scope in classic ASP. (As with classic ASP, do not store open database connections in the cache!)

Realize that this data cache is kept in memory and "lives" as long as the host application does. In other words, when the ASP.NET application using data caching is restarted, the cache is destroyed and recreated. Data Caching is almost as easy to use as Output Caching or Fragment caching: you simply interact with it as you would any simple dictionary object. To store a value in the cache, use syntax like this:

Cache["foo"] = bar; // C#
Cache("foo") = bar ' VB.NET

To retrieve a value, simply reverse the syntax like this:

bar = Cache["foo"]; // C#
bar = Cache("foo") ' VB.NET

Note that after you retrieve a cache value in the above manner you should first verify that the cache value is not null prior to doing something with the data. Since Data Caching uses an in-memory cache, there are times when cache elements may need to be evicted. That is, if there is not enough memory and you attempt to insert something new into the cache, something else has gotta go! The Data Cache engine does all of this scavenging for your behind the scenes, of course. However, don't forget that you should always check to ensure that the cache value is there before using it. This is fairly simply to do - just check to ensure that the value isn't null/Nothing. If it is, then you need to dynamically retrieve the object and restore it into the cache.

For example, if we were storing a string myString in the cache whose value was set from some method named SetStringToSomething(), and we wanted to read the value of myString from the cache, we'd want to:

Read the myString from the cache: str = Cache("myString")
Ensure that str wasn't null/Nothing. If it was, we'd want to get the value of str from SetStringToSomething(), and then put it in the cache, like so:
'Try to read the cache entry MyString into str
str = Cache("myString")

'Check if str is Nothing
If str is Nothing then
'If it is, populate str from SetStringToSomething()
str = SetStringToSomething()

'Now insert str into the cache entry myString
Cache("myString") = str
End If

Besides using the dictionary-like key/value assignment, as shown in the example above, you can also use the Insert or Add method to add items to the cache. Both of these methods are overloaded to accommodate a variety of situations. The Add and the Insert methods operate exactly the same except the Add method returns a reference to the object being inserted to the cache. Because of the similarity of the two methods, I will concentrate on the Insert method. Note that the Insert method allows you to simply add items to the cache using a key and value notation as well. For example to simply add an instance of the object bar to the cache named foo, use syntax like this:

Cache.Insert("foo", bar); // C#
Cache.Insert("foo", bar) ' VB.NET

(Note that this is synonymous to using the Cache("foo") = bar syntax we looked at earlier.)

Note that with inserting items into the Data Cache using the Cache(key) = value method or the Cache.Insert(key, value) we have no control over when (if ever) the items are evicted from the cache. However, there are times when we'd like to have control over when items leave the cache. For example, perhaps we want to have an inserted item in the cache to only live for n seconds, as with Output Caching. Or perhaps we'd like to have it exit the cache n seconds after it's last accessed. With Data Caching, you can optionally specify when the cache should have a member evicted.

Additionally, you can have an item evicted from the cache when a file changes. Such an eviction dependency is called a file dependency, and has many real-world applications, especially when working with XML files. For example, if you want to pull data out of an XML file, but you don't want to constantly go to disk to read the data, you can tell the ASP.NET caching engine to expire the cached XML file whenever the XML file on disk is changed. To do this, use the following syntax:

Cache.Insert("foo", bar, new CacheDependancy(Server.MapPath("BarData.xml")))

By using this syntax, the cache engine takes care of removing the object bar from the cache when BarData.xml file is changed. Very cool! There are also means to have the inserted cache value expire based on an interval, or at an absolute time, as discussed before. For more information on these methods, consult the documentation for the Cache.Insert method.

No comments: