Wednesday, 31 August 2011

Garbage Collection Process in .NET

In order to understand how to make good use of the garbage collector and what performance problems you might run into when running in a garbage-collected environment, it's important to understand the basics of how garbage collectors work and how those inner workings affect running programs.
This article is broken down into two parts: First I will discuss the nature of the common language runtime (CLR)'s garbage collector in general terms using a simplified model, and then I will discuss some performance implications of that structure.
Simplified Model
For explanatory purposes, consider the following simplified model of the managed heap. Note that this is not what is actually implemented.

Figure 1. Simplified model of the managed heap
The rules for this simplified model are as follows:
  • All garbage-collectable objects are allocated from one contiguous range of address space.
  • The heap is divided into generations (more on this later) so that it is possible to eliminate most of the garbage by looking at only a small fraction of the heap.
  • Objects within a generation are all roughly the same age.
  • Higher-numbered generations indicate areas of the heap with older objects—those objects are much more likely to be stable.
  • The oldest objects are at the lowest addresses, while new objects are created at increasing addresses. (Addresses are increasing going down in Figure 1 above.)
  • The allocation pointer for new objects marks the boundary between the used (allocated) and unused (free) areas of memory.
  • Periodically the heap is compacted by removing dead objects and sliding the live objects up toward the low-address end of the heap. This expands the unused area at the bottom of the diagram in which new objects are created.
  • The order of objects in memory remains the order in which they were created, for good locality.
  • There are never any gaps between objects in the heap.
  • Only some of the free space is committed. When necessary, more memory is acquired from the operating system in the reserved address range.
Collecting the Garbage
The easiest kind of collection to understand is the fully compacting garbage collection, so I'll begin by discussing that.
Full Collections
In a full collection we must stop the program execution and find all of the roots into the GC heap. These roots come in a variety of forms, but are most notably stack and global variables that point into the heap. Starting from the roots, we visit every object and follow every object pointer contained in every visited object marking the objects as we go along. In this way the collector will have found every reachable or live object. The other objects, the unreachable ones, are now condemned.

Figure 2. Roots into the GC heap
Once the unreachable objects have been identified we want to reclaim that space for later use; the goal of the collector at this point is to slide the live objects up and eliminate the wasted space. With execution stopped, it's safe for the collector to move all those objects, and to fix all the pointers so that everything is properly linked in its new location. The surviving objects are promoted to the next generation number (which is to say the boundaries for the generations are updated) and execution can resume.
Partial Collections
Unfortunately, the full garbage collection is simply too expensive to do every time, so now it's appropriate to discuss how having generations in the collection helps us out.
First let's consider an imaginary case where we are extraordinarily lucky. Let's suppose that there was a recent full collection and the heap is nicely compacted. Program execution resumes and some allocations happen. In fact, lots and lots of allocations happen and after enough allocations the memory management system decides it's time to collect.
Now here's where we get lucky. Suppose that in all of the time we were running since the last collection we didn't write on any of the older objects at all, only newly allocated, generation zero (gen0), objects have been written to. If this were to happen we would be in a great situation because we can simplify the garbage collection process massively.
Instead of our usual full collect we can just assume that all of the older objects (gen1, gen2) are still live—or at least enough of them are alive that it isn't worth looking at those objects. Furthermore, since none of them were written (remember how lucky we are?) there are no pointers from the older objects to the newer objects. So what we can do is look at all the roots like usual, and if any roots point to old objects just ignore those ones. For other roots (those pointing into gen0) we proceed as usual, following all the pointers. Whenever we find an internal pointer that goes back into the older objects, we ignore it.
When that process is done we will have visited every live object in gen0 without having visited any objects from the older generations. The gen0 objects can then be condemned as usual and we slide up just that region of memory, leaving the older objects undisturbed.
Now this is really a great situation for us because we know that most of the dead space is likely to be in younger objects where there is a great deal of churn. Many classes create temporary objects for their return values, temporary strings, and assorted other utility classes like enumerators and whatnot. Looking at just gen0 gives us an easy way to get back most of the dead space by looking at only very few of the objects.
Unfortunately, we're never lucky enough to use this approach, because at least some older objects are bound to change so that they point to new objects. If that happens it's not sufficient to just ignore them.
Making Generations Work with Write Barriers
To make the algorithm above actually work, we must know which older objects have been modified. To remember the location of the dirty objects, we use a data structure called the card table, and to maintain this data structure the managed code compiler generates so-called write barriers. These two notions are central the success of generation-based garbage collecting.
The card table can be implemented in a variety of ways, but the easiest way to think of it is as an array of bits. Each bit in the card table represents a range of memory on the heap—let's say 128 bytes. Every time a program writes an object into some address, the write barrier code must compute which 128-byte chunk was written and then set the corresponding bit in the card table.
With this mechanism in place, we can now revisit the collection algorithm. If we are doing a gen0 garbage collection, we can use the algorithm as discussed above, ignoring any pointers to older generations, but once we have done that we must then also find every object pointer in every object that lies on a chunk that was marked as modified in the card table. We must treat those just like roots. If we consider those pointers as well, then we will correctly collect just the gen0 objects.
This approach wouldn't help at all if the card table was always full, but in practice comparatively few of the pointers from the older generations actually get modified, so there is a substantial savings from this approach.
Now that we have a basic model for how things are working, let's consider some things that could go wrong that would make it slow. That will give us a good idea what sorts of things we should try to avoid to get the best performance out of the collector.
Too Many Allocations
This is really the most basic thing that can go wrong. Allocating new memory with the garbage collector is really quite fast. As you can see in Figure 2 above is all that needs to happen typically is for the allocation pointer to get moved to create space for your new object on the "allocated" side—it doesn't get much faster than that. However, sooner or later a garbage collect has to happen and, all things being equal, it's better for that to happen later than sooner. So you want to make sure when you're creating new objects that it's really necessary and appropriate to do so, even though creating just one is fast.
This may sound like obvious advice, but actually it's remarkably easy to forget that one little line of code you write could trigger a lot of allocations. For example, suppose you're writing a comparison function of some kind, and suppose that your objects have a keywords field and that you want your comparison to be case insensitive on the keywords in the order given. Now in this case you can't just compare the entire keywords string, because the first keyword might be very short. It would be tempting to use String.Split to break the keyword string into pieces and then compare each piece in order using the normal case-insensitive compare. Sounds great right?
Well, as it turns out doing it like that isn't such a good idea. You see, String.Split is going to create an array of strings, which means one new string object for every keyword originally in your keywords string plus one more object for the array. Yikes! If we're doing this in the context of a sort, that's a lot of comparisons and your two-line comparison function is now creating a very large number of temporary objects. Suddenly the garbage collector is going to be working very hard on your behalf, and even with the cleverest collection scheme there is just a lot of trash to clean up. Better to write a comparison function that doesn't require the allocations at all.
Too-Large Allocations
When working with a traditional allocator, such as malloc(), programmers often write code that makes as few calls to malloc() as possible because they know the cost of allocation is comparatively high. This translates into the practice of allocating in chunks, often speculatively allocating objects we might need, so that we can do fewer total allocations. The pre-allocated objects are then manually managed from some kind of pool, effectively creating a sort of high-speed custom allocator.
In the managed world this practice is much less compelling for several reasons:
First, the cost of doing an allocation is extremely low—there's no searching for free blocks as with traditional allocators; all that needs to happen is the boundary between the free and allocated areas needs to move. The low cost of allocation means that the most compelling reason to pool simply isn't present.
Second, if you do choose to pre-allocate you will of course be making more allocations than are required for your immediate needs, which could in turn force additional garbage collections that might otherwise have been unnecessary.
Finally, the garbage collector will be unable to reclaim space for objects that you are manually recycling, because from the global perspective all of those objects, including the ones that are not currently in use, are still live. You might find that a great deal of memory is wasted keeping ready-to-use but not in-use objects on hand.
This isn't to say that pre-allocating is always a bad idea. You might wish to do it to force certain objects to be initially allocated together, for instance, but you will likely find it is less compelling as a general strategy than it would be in unmanaged code.
Too Many Pointers
If you create a data structure that is a large mesh of pointers you'll have two problems. First, there will be a lot of object writes (see Figure 3 below) and, secondly, when it comes time to collect that data structure, you will make the garbage collector follow all those pointers and if necessary change them all as things move around. If your data structure is long-lived and won't change much, then the collector will only need to visit all those pointers when full collections happen (at the gen2 level). But if you create such a structure on a transitory basis, say as part of processing transactions, then you will pay the cost much more often.

Figure 3. Data structure heavy in pointers
Data structures that are heavy in pointers can have other problems as well, not related to garbage collection time. Again, as we discussed earlier, when objects are created they are allocated contiguously in the order of allocation. This is great if you are creating a large, possibly complex, data structure by, for instance, restoring information from a file. Even though you have disparate data types, all your objects will be close together in memory, which in turn will help the processor to have fast access to those objects. However, as time passes and your data structure is modified, new objects will likely need to be attached to the old objects. Those new objects will have been created much later and so will not be near the original objects in memory. Even when the garbage collector does compact your memory your objects will not be shuffled around in memory, they merely "slide" together to remove the wasted space. The resulting disorder might get so bad over time that you may be inclined to make a fresh copy of your whole data structure, all nicely packed, and let the old disorderly one be condemned by the collector in due course.
Too Many Roots
The garbage collector must of course give roots special treatment at collection time—they always have to be enumerated and duly considered in turn. The gen0 collection can be fast only to the extent that you don't give it a flood of roots to consider. If you were to create a deeply recursive function that has many object pointers among its local variables, the result can actually be quite costly. This cost is incurred not only in having to consider all those roots, but also in the extra-large number of gen0 objects that those roots might be keeping alive for not very long (discussed below).
Too Many Object Writes
Once again referring to our earlier discussion, remember that every time a managed program modified an object pointer the write barrier code is also triggered. This can be bad for two reasons:
First, the cost of the write barrier might be comparable to the cost of what you were trying to do in the first place. If you are, for instance, doing simple operations in some kind of enumerator class, you might find that you need to move some of your key pointers from the main collection into the enumerator at every step. This is actually something you might want to avoid, because you effectively double the cost of copying those pointers around due to the write barrier and you might have to do it one or more times per loop on the enumerator.
Second, triggering write barriers is doubly bad if you are in fact writing on older objects. As you modify your older objects you effectively create additional roots to check (discussed above) when the next garbage collection happens. If you modified enough of your old objects you would effectively negate the usual speed improvements associated with collecting only the youngest generation.
These two reasons are of course complemented by the usual reasons for not doing too many writes in any kind of program. All things being equal, it's better to touch less of your memory (read or write, in fact) so as to make more economical use of the processor's cache.
Too Many Almost-Long-Life Objects
Finally, perhaps the biggest pitfall of the generational garbage collector is the creation of many objects, which are neither exactly temporary nor are they exactly long-lived. These objects can cause a lot of trouble, because they will not be cleaned up by a gen0 collection (the cheapest), as they will still be necessary, and they might even survive a gen1 collection because they are still in use, but they soon die after that.
The trouble is, once an object has arrived at the gen2 level, only a full collection will get rid of it, and full collections are sufficiently costly that the garbage collector delays them as long as is reasonably possible. So the result of having many "almost-long-lived" objects is that your gen2 will tend to grow, potentially at an alarming rate; it might not get cleaned up nearly as fast as you would like, and when it does get cleaned up it will certainly be a lot more costly to do so than you might have wished.
To avoid these kinds of objects, your best lines of defense go like this:
  1. Allocate as few objects as possible, with due attention to the amount of temporary space you are using.
  2. Keep the longer-lived object sizes to a minimum.
  3. Keep as few object pointers on your stack as possible (those are roots).
If you do these things, your gen0 collections are more likely to be highly effective, and gen1 will not grow very fast. As a result, gen1 collections can be done less frequently and, when it becomes prudent to do a gen1 collection, your medium lifetime objects will already be dead and can be recovered, cheaply, at that time.
If things are going great then during steady-state operations your gen2 size will not be increasing at all!
Now that we've covered a few topics with the simplified allocation model, I'd like to complicate things a little bit so that we can discuss one more important phenomenon, and that is the cost of finalizers and finalization. Briefly, a finalizer can be present in any class—it's an optional member that the garbage collector promises to call on otherwise dead objects before it reclaims the memory for that object. In C# you use the ~Class syntax to specify the finalizer.
How Finalization Affects Collection
When the garbage collector first encounters an object that is otherwise dead but still needs to be finalized it must abandon its attempt to reclaim the space for that object at that time. The object is instead added to a list of objects needing finalization and, furthermore, the collector must then ensure that all of the pointers within the object remain valid until finalization is complete. This is basically the same thing as saying that every object in need of finalization is like a temporary root object from the collector's perspective.
Once the collection is complete, the aptly named finalization thread will go through the list of objects needing finalization and invoke the finalizers. When this is done the objects once again become dead and will be naturally collected in the normal way.
Finalization and Performance
With this basic understanding of finalization we can already deduce some very important things:
First, objects that need finalization live longer than objects that do not. In fact, they can live a lot longer. For instance, suppose an object that is in gen2 needs to be finalized. Finalization will be scheduled but the object is still in gen2, so it will not be re-collected until the next gen2 collection happens. That could be a very long time indeed, and, in fact, if things are going well it will be a long time, because gen2 collections are costly and thus we want them to happen very infrequently. Older objects needing finalization might have to wait for dozens if not hundreds of gen0 collections before their space is reclaimed.
Second, objects that need finalization cause collateral damage. Since the internal object pointers must remain valid, not only will the objects directly needing finalization linger in memory but everything the object refers to, directly and indirectly, will also remain in memory. If a huge tree of objects was anchored by a single object that required finalization, then the entire tree would linger, potentially for a long time as we just discussed. It is therefore important to use finalizers sparingly and place them on objects that have as few internal object pointers as possible. In the tree example I just gave, you can easily avoid the problem by moving the resources in need of finalization to a separate object and keeping a reference to that object in the root of the tree. With that modest change only the one object (hopefully a nice small object) would linger and the finalization cost is minimized.
Finally, objects needing finalization create work for the finalizer thread. If your finalization process is a complex one, the one and only finalizer thread will be spending a lot of time performing those steps, which can cause a backlog of work and therefore cause more objects to linger waiting for finalization. Therefore, it is vitally important that finalizers do as little work as possible. Remember also that although all object pointers remain valid during finalization, it might be the case that those pointers lead to objects that have already been finalized and might therefore be less than useful. It is generally safest to avoid following object pointers in finalization code even though the pointers are valid. A safe, short finalization code path is the best.
IDisposable and Dispose
In many cases it is possible for objects that would otherwise always need to be finalized to avoid that cost by implementing the IDisposable interface. This interface provides an alternative method for reclaiming resources whose lifetime is well known to the programmer, and that actually happens quite a bit. Of course it's better still if your objects simply use only memory and therefore require no finalization or disposing at all; but if finalization is necessary and there are many cases where explicit management of your objects is easy and practical, then implementing the IDisposable interface is a great way to avoid, or at least reduce, finalization costs.
In C# parlance, this pattern can be quite a useful one:
class X:  IDisposable
   public X(…)
   … initialize resources …

   … release resources …

   public void Dispose()
// this is the same as calling ~X()

// no need to finalize later

Where a manual call to Dispose obviates the need for the collector to keep the object alive and call the finalizer.

Tuesday, 30 August 2011

State management in ASP.NET


State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

Types of State Management

There are 2 types State Management:

1. Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

2. Server – Side State Management
a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. Session State – Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.

Implementation Procedure

Client – Side State Management:

View State:
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When an ASP.NET page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. If the data is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields. The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" />

Encrypting of the View State: You can enable view state encryption to make it more difficult for attackers and malicious users to directly read view state information. Though this adds processing overhead to the Web server, it supports in storing confidential information in view state. To configure view state encryption for an application does the following:


               <pages viewStateEncryptionMode="Always"/>



Alternatively, you can enable view state encryption for a specific page by setting the value in the page directive, as the following sample demonstrates:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ViewStateEncryptionMode="Always"%>

View State is enabled by default, but if you can disable it by setting the EnableViewState property for each web control to false. This reduces the server processing time and decreases page size.
Reading and Writing Custom View State Data:
If you have a value that you’d like to keep track of while the user is visiting a single ASP.NET Web page, adding a custom value to ViewState is the most efficient and secure way to do that. However, ViewState is lost if the user visits a different Web page, so it is useful only for temporarily storing values.
Example: Determine the time of last visit to the page
// Check if View State object exists, and display it if it does

If (ViewState ["lastVisit"]!= null)

Label1.Text = (string)ViewState["lastVisit"]; else

Label1.Text = "lastVisit ViewState not defined.";

// Define the ViewState object for the next page view ViewState.Add("lastVisit", DateTime.Now.ToString());

Control State: If you create a custom control that requires ViewState, you can use the ControlState property to store state information for your control. ControlState allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property. To use control state in a custom control, your control must override the OnInit method and call the Register-RequiresControlState method during initialization and then override the SaveControl-State and LoadControlState methods.

Hidden fields: ViewState stores information in the Web page using hidden fields. Hidden fields are sent back to the server when the user submits a form; however, the information is never displayed by the Web browser (unless the user chooses to view the page source). ASP.NET allows you to create your own custom hidden fields and store values that are submitted with other form data. A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. You can use hidden fields only to store information for a single page, so it is not useful for storing session data. If you use hidden fields, you must submit your pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which happens if the user clicks a link). Unlike view state data, hidden fields have no built-in compression, encryption, hashing, or chunking, so users can view or modify data stored in hidden fields.

Cookies: Web applications can store small pieces of data in the client’s Web browser by using cookies. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary). The most common use of cookies is to identify a single user as he or she visits multiple Web pages.

Reading and Writing Cookies:
A Web application creates a cookie by sending it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request.
Create a cookie -> add a value to the Response.Cookies HttpCookieCollection.
Read a cookie -> read values in Request.Cookies.
// Check if cookie exists, and display it if it does

if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains client-side script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);

else Label1.Text = "No value defined";

// Define the cookie for the next visit Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

If you do not define the Expires property, the browser stores it in memory and the cookie is lost if the user closes his or her browser.

To delete a cookie, overwrite the cookie and set an expiration date in the past. You can’t directly delete cookies because they are stored on the client’s computer.
Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site with a different hostname. You can control a cookie’s scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates:

Response.Cookies["lastVisit"].Path = "/Application1";

Through this the scope is limited to the “/Application1” folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement:
Response.Cookies[“lastVisit”].Domain = “Contoso”;

Storing Multiple Values in a Cookie:
Though it depends on the browser, you typically can’t store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates:
Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();

Response.Cookies["info"]["firstName"].Value = "Tony";

Response.Cookies["info"]["border"].Value = "blue";

Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);

Running the code in this example sends a cookie with the following value to the Web browser:
(visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue)

Query Strings: Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. A typical query string might look like the following real-world example:
In this example, the URL identifies the Default.aspx page. The query string (which starts with a question mark [?]) contains a single parameter named “kbid,” and a value for that parameter, “315233.” Query strings can also have multiple parameters, such as the following real-world URL, which specifies a language and query when searching the Web site:

Value Name | ASP.NET Object | Value
mkt | Request.QueryString[“mkt”] | en-US
setlang | Request.QueryString[“setlang”] | en-US
q | Request.QueryString[“q”] | hello world

Limitations for Query Strings:
1. Some Browsers and client devices impose a 2083 – character limit on the length of the URL.
2. You must submit the page using an HTTP GET command in order for query string values to be available during page processing. Therefore, you shouldn’t add query strings to button targets in forms.
3. You must manually add query string values to every hyperlink that the user might click.
Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) +

", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) +

", Page: " + Server.HtmlEncode(Request.QueryString["page"]);

Server - Side State Management:

Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted.

ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:

a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.

b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.

c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.

Session State: ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary.

You can use session state to accomplish the following tasks:
i. Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit.

ii. Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information.

iii. Raise appropriate session management events. In addition, you can write application code leveraging these events.

ASP.NET session state supports several different storage options for session data:

a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer.

b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.

c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.

d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider.

e. Off Disables session state. You should disable session state if you are not using it to improve performance.


Advantages of Client – Side State Management:

1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management:

1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.

.Net Interview Question

1)     What is .Net Framework?
a)        A programming infrastructure provided by Microsoft for building, deploying and running application and the service that use .Net technologies such as desktop application, Web Application and Web services.
The .Net Framework contains three major parts
                           I.                  Common Language Runtime(CLR)
                         II.                  Framework Class Libraries
2)     Difference between .Net Framework 1.1, 2.0, and 3.5?
Ado .Net Mars, Generics, Partial Classes, DPAPI

3)     What is CLR?
a)     Full form of CLR is Common language runtime. Basically it is an execution engine of .net framework. Its responsibility to care of code execution of program. Following are the responsibility of CLR.
1.      Garbage Collection:  CLR automatic manages the memory thus eliminating the memory leakage problem. When object are not referred GC automatically call and release the memories. Thus providing efficient memory management.
2.      Code Access Security: CAS grants rights to program depending on the security of the machine. Example program has rights to create or edit new file but the security configuration of machine does not allow to program to delete a file.
3.      Code Verification: It prevents the source code to perform illegal operation such as accessing invalid memory location etc.
4.      IL To Native Translator and Optimizer: CLR uses jIT and compiles the IL code to machine code and then executes.
4)     What is CTS?
a)      In order that two language communicate smoothly CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these data types are not compatible so the interfacing between them is very complicated. In order to able that two different languages can communicate Microsoft introduced Common Type System. So “Integer” data type in VB6 and “int” data type in C++ will convert it to System.int32 which is data type of CTS. CLS which is covered in the coming question is subset of CTS.

5)     What is CLS?
a)      This is a subset of the CTS which all .NET languages are expected to support. It was always a dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

6)     What is Assembly?
a)     An assembly is the primary unit of deployment, Security, and version control in the .Net framework. Assembly is the .dll file which contains metadata information which is used by CLR for everything.
There are two types of assemblies.
1.      Private Assembly: A private assembly is normally used by single application and stored in application directory.
2.      Shared Assembly: A shared a assembly is used by multiple applications. A shared assembly is normally stored in GAC which is repository of assemblies maintained by .Net runtime. Shared assemblies are usually library of code which many applications will find useful. For e.g. Crystal Report classes which will used by application for reports.
7)     What is Namespace?
a)     There are 13000 classes in the .Net framework. This is an overwhelming number. If Microsoft simply jumbled all the classes together then you would never find anything. Fortunately Microsoft divides the classes in the framework into separate Namespaces. A namespace is a simply a category. For e.g. All the file related to working with file system are located in the system.IO namespace
8)     What is Manifest?
a)      Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things (See Figure Manifest View for more details):
1.       Version of assembly
2.       Security identity
3.       Scope of the assembly
4.       Resolve references to resources and classes.
5.      The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a stand-alone PE file that contains only assembly manifest information.
9)     What is GAC?
a)     GAC (Global Assembly Cache) is used where shared .NET assembly reside. GAC is used in the following situations :-
1.       If the application has to be shared among several application.
2.       If the assembly has some special security requirements like only administrators can remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly.

10)  What is Garbage Collection?
a)      Garbage collection is a CLR feature which automatically manages memory. Programmers forget to release the objects while coding (Laziness). CLR automatically releases objects when they are no longer in use and referenced. CLR runs on non-deterministic to see the unused objects and cleans them. One side effect of this non-deterministic feature is that we cannot assume an object is destroyed when it goes out of the scope of a function. Therefore, we should not put code into a class destructor to release resources.
11)  What is Reflection in .net?
a)     All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as “Reflection”. System. Reflection can be used to browse through the metadata information. Using reflection you can also dynamically invoke methods using System.Type.Invokemember.
12)  What are different types of JIT?
a)     JIT is a part of runtime execution environment.
In Microsoft there are three types of complier:
1.      Pre-JIT: - Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.
2.       Econo-JIT: - Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.
3.      Normal-JIT: - Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution.
13)  What are Value types and Reference types?
Value types
Reference types
Value types directly contain the data
Reference types stores reference
Value types are allocated on the stack
Reference types are allocated on the heap
Int, string etc.
Class, pointer, interface

14)  What is Boxing and UnBoxing?
a)      The process of converting implicitly value types to reference type called Boxing where as Unboxing is a process of converting reference types to value types.
15)  What is Difference between VB.Net and
Has support for optional parameter which makes COM interoperability
Not supported
Has With the Construct
Not supported
Not Supported
Supports Operator Overloading

16)  What is the difference between Convert.ToString () and ToString() method?
a)     The basic difference between them is “Convert” function handles NULLS while “i.ToString()” does not it will throw a NULL reference exception error. So as good coding practice using “convert” is always safe.
17)  What is Multi-tasking?
a)      It’s a feature of modern operating systems with which we can run multiple programs at same time example Word, Excel etc.
18)  What is Multi-threading?
a)     Multi-threading forms subset of Multi-tasking. Instead of having to switch between programs this feature switches between different parts of the same program. Example you are writing in word and at the same time word is doing a spell check in background.
19)  What is a Thread?
a)     A thread is the basic unit to which the operating system allocates processor time.
20)  What's Thread.Sleep() in threading ?
a)     Thread's execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000).
21)  What is an application domain?
a)     Previously “PROCESS” where used as security boundaries. One process has its own virtual memory and does not overlap the other process virtual memory; due to this one process cannot crash the other process. So any problem or error in one process does not affect the other process. In .NET they went one step ahead introducing application domains. In application domains multiple applications can run in same process without influencing each other. If one of the application domains throws error it does not affect the other application domains. To invoke method in a object running in different application domain .NET remoting is used.
22)  What is .NET Remoting?
a)     .NET remoting is replacement of DCOM. Using .NET remoting you can make remote object calls which lie in different Application Domains. As the remote objects run in different process client calling the remote object cannot call it directly. So the client uses a proxy which looks like a real object. When client wants to make method call on the remote object it uses proxy for it. These method calls are called as “Messages”. Messages are serialized using “formatter” class and sent to client “channel”. Client Channel communicates with Server Channel. Server Channel uses as formatter to deserialize the message and sends to the remote object.
23)  What is a Web Service?
a)     Web Services are business logic components which provide functionality via the Internet using standard protocols such as HTTP. Web Services uses Simple Object Access Protocol (SOAP) in order to expose the business functionality. SOAP defines a standardized format in XML which can be exchanged between two entities over standard protocols such as HTTP. SOAP is platform independent so the consumer of a Web Service is therefore completely shielded from any implementation details about the platform exposing the Web Service. For the consumer it is simply a black box of send and receives XML over HTTP. So any web service hosted on windows can also be consumed by UNIX and LINUX platform.
24)  Define State Management in .Net?
a)     State Management is a process by which you maintain state and page information over multiple requests for same or different pages
Types of state management system
1.      Client Side State Management
2.      Server Side State Management
1.        Client Side State Management: - In this we store the information on the clients computer and technique to store the state information is
a)     View State: - View state retaining the value between multiple requests for the same page. When the page is processed the current state of page is stored as hidden field.
b)     Control State: - When we create Custom control that requires view state so that we can use control state property to store state information for control.
c)      Hidden fields: - View state stores information in the web page using hidden fields.
d)      Cookies: - Web application can store small piece of data in the client’s web browser by using cookies. A cookie is a small amount of data that is a text file on the client file system.
e)     Query String: - Query String store values in the URL that are visible to the user.
2.      Server Side State Management:- In this we store the information on server and the technique to store the state information is.
a)     Session State: - Session state information is available to all pages opened by user during a single visit.
b)     Application State:- Application  state is available to all pages of which user request a page
25)  What’s a Class?
a)     A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It’s a comprehensive data type which represents a blue print of objects. It’s a template of object.
26)   What’s an Object?
a)     It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition
27)  What is a difference between abstract class and interface?
Abstract Class
Have concrete method as well as abstract methods
Have only abstract methods
Access modifiers can be used
No access modifiers can be used
Class can be inherited only abstract class
Multiple Interfaces can be implemented in single class

28)  What is a delegate?
a)     Delegate is a class that can hold a reference to a method or a function. Delegate class has a signature and it can only reference those methods whose signature is compliant with the class. Delegates are type-safe functions pointers or callbacks.
29)  What are events?
a)     As compared to delegates events works with source and listener methodology. So listeners who are interested in receiving some events they subscribe to the source. Once this subscription is done the source raises events to its entire listener when needed. One source can have multiple listeners.
30)  What is the difference between delegate and events?
a)      Actually events use delegates in bottom. But they add an extra layer on the delegates, thus forming the publisher and subscriber model.
b)      As delegates are function to pointers they can move across any clients. So any of the clients can add or remove events, which can be pretty confusing. But events give the extra protection by adding the layer and making it a publisher and subscriber model.
31)  What is shadowing?
a)     When two elements in a program have same name, one of them can hide and shadow the other one. So in such cases the element which shadowed the main element is referenced. Below is a sample code, there are two classes “ClsParent” and “ClsShadowedParent”. In “ClsParent” there is a variable “x” which is a integer. “ClsShadowedParent” overrides “ClsParent” and shadows the “x” variable to a string.
32)  What is the difference between Class and structure’s?
 Following are the key differences between them:-
a)      Structure is value types and classes are reference types. So structures use stack and classes use heap.
b)      Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.
c)       Structures do not require constructors while classes require.
d)     Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
33)  What is Array List?
a)     Array is whose size can increase and decrease dynamically. Array list can hold item of different types. As Array list can increase and decrease size dynamically you do not have to use the REDIM keyword. You can access any item in array using the INDEX value of the array position.
34)   What’s a Hash Table? Twist: - What’s difference between Hash Table and Array List?
a)      You can access array using INDEX value of array, but how many times you know the real value of index. Hash table provides way of accessing the index using a user identified KEY value, thus removing the INDEX problem.

35)  What is the difference between System.String and System.StringBuilder classes?
a)     System.String is immutable; System.StringBuilder can have mutable string where a variety of operations can be performed.
36)  What’ is the sequence in which ASP.NET events are processed ?
Following is the sequence in which the events occur :-
a)      Page_Init.
b)     Page_Prerender
c)       Page_Load.
d)     Control events
e)     Page_Unload event.
Page_init event only occurs when first time the page is started, but Page_Load occurs in subsequent request of the page.
37)  What is event bubbling (Bubble Event)?
a)     Server controls like Datagrid, DataList, and Repeater can have other child controls inside them. Example DataGrid can have combo box inside datagrid. These child control do not raise their events by themselves, rather they pass the event to the container parent (which can be a datagrid, datalist, repeater), which passed to the page as “ItemCommand” event. As the child control send their events to parent this is termed as event bubbling.
38)  What is the difference between Authentication and authorization?
a)     This can be a tricky question. These two concepts seem altogether similar but there is wide range of difference. Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. In short we can say the following authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user’s identity. Authorization is the process of allowing an authenticated user access to resources. Authentication always proceeds to Authorization; even if your application lets anonymous users connect and use the application, it still authenticates them as being anonymous.
39)  What is the difference between Server.Transfer and response.Redirect ? Following are the major differences between them:-
a)      Response.Redirect sends message to the browser saying it to move to some different page, while server.transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in server.transfer there is no round trip while response.redirect has a round trip and hence puts a load on server.
b)      Using Server.Transfer you cannot redirect to a different from the server itself. Example if your server is you can use server.transfer to move to but yes you can move to, i.e. within websites. This cross server redirect is possible only using Response.redirect.
c)       With server.transfer you can preserve your information. It has a parameter called as “preserveForm”. So the existing query string etc. will be able in the calling page. In response.redirect you can maintain the state, but has lot of drawbacks.

40)  How can we kill a user session?
a)     Session.abandon
41)  What is difference between dataset and datareader ?
 Following are some major differences between dataset and datareader :-
a)      DataReader provides forward-only and read-only access to data, while the DataSet object can hold more than one table (in other words more than one rowset) from the same data source as well as the relationships between them.
b)      Dataset is a disconnected architecture while datareader is connected architecture.
c)      Dataset can persist contents while datareader cannot persist contents, they are forward only.
42)  What is normalization? What are different types of normalization? It is set of rules that have been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization. Benefits of normalizing your database will include:
a)     Avoiding repetitive entries
b)     Reducing required storage space
c)      Preventing the need to restructure existing tables to accommodate new data. √ Increased speed and flexibility of queries, sorts, and summaries.
 Following are the three normal forms:
1.      First Normal Form: - For a table to be in first normal form, data must be broken up into the smallest unit’s possible. In addition to breaking data up into the smallest meaningful values, tables in first normal form should not contain repetitions groups of fields.
2.      Second Normal Form: - The second normal form states that each field in a multiple field primary key table must be directly related to the entire primary key. Or in other words, each non-key field should be a fact about all the fields in the primary key.
3.      Third Normal Form: - A non-key field should not depend on other Non-key field. The field "Total" is dependent on "Unit price" and "qty".
43)  What are the different types of joins? What is the difference between them?
a)     Inner join: - Inner join shows matches only when they exist in both tables.Example, in the below SQL there are two tables Customers and Orders and the inner join in made on Customers Customerid and Orders Customerid.So this SQL will only give you result with customers who have orders.If the customer does not have order it will not display that record.
For e.g. SELECT Customers.*, Orders.* FROM Customers INNER JOIN Orders ON Customers.CustomerID =Orders.CustomerID
b)     LEFT OUTER JOIN :- Left join will display all records in left table of the SQL statement.In SQL below customers with or without orders will be displayed. Order data for customers without orders appears as NULL values. For example, you want to determine the amount ordered by each customer and you need to see who has not ordered anything as well. You can also see the LEFT OUTER JOIN as a mirror image of the RIGHT OUTER JOIN (Is covered in the next section) if you switch the side of each table.
For e.g. SELECT Customers.*, Orders.* FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID =Orders.CustomerID
c)      RIGHT OUTER JOIN: - Right join will display all records in right table of the SQL statement. In SQL below all orders with or without matching customer records will be displayed. Customer data for orders without customers appears as NULL values. For example, you want to determine if there are any orders in the data with undefined CustomerID values (say, after a conversion or something like it). You can also see the RIGHT OUTER JOIN as a mirror image of the LEFT OUTER JOIN if you switch the side of each table.
For e.g. SELECT Customers.*, Orders.* FROM Customers RIGHT OUTER JOIN Orders ON Customers.CustomerID =Orders.CustomerID
44)  What are indexes? What is the difference between clustered and nonclustered indexes?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quickly.
There are clustered and nonclustered indexes.
a)     Cluster Index: - A clustered index is a special type of index that reorders the way in which records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
b)     Non Cluster Index: - A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
45)  What is the difference between DELETE TABLE and TRUNCATE TABLE commands?
1.      Delete is dml command and can be rollback
Truncate is ddl command and can’t be rollback
2.      Slower than truncate
Faster than delete
3.      Delete command is used with criteria like Where.
               Cannot be used with citeria.  

46)  What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
a)      You can use Having Clause with the GROUP BY function in a query and WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.
47)  What is the difference between UNION and UNION ALL SQL syntax?
a)     UNION SQL syntax is used to select information from two tables. But it selects only distinct records from both the table, while UNION ALL selects all records from both the tables.
48)  What are transactions in SQL SERVER?
a)      A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a transaction:
49)  Difference between Array and Array List?
a)     The capacity of an Array is fixed. Whereas, ArrayList can increase and decrease size dynamically.
b)      An Array is a collection of similar items. Whereas, ArrayList can hold item of different types.
c)       Array is in the System namespace. Whereas, ArrayList is in the System.Collections namespace.
d)      An Array can have multiple dimensions. Whereas, ArrayList always has exactly one dimension.
e)      We can set the lower bound of an Array. Whereas, the lower bound of an ArrayList is always zero.

50)    What is Serialization?
a)      Serialization is the process of saving the state of an object by converting it to a stream of bytes. The object can then be persisted to file, database, or even memory. The reverse process of serialization is known as deserialization.
Use of Serialization:-
a)  Serialization is used in many scenarios, but the main purpose is to save the state of an object in order to have the ability to recreate the same object when required. It is an important to let the user save work and then be able to continue from that point at a later time
b)   Serialization is also used in creating a clone of an object.
c)   Another important need for serialization arises when the object is required to travel electronically over wire. In such cases the objects are serialized and deserialized. In fact, serialization is one of the fundamental requirements for techniques such as .NET Remoting.
Types of Serialization: -
The XmlSerializer can be used when you need the data in the object to be stored in an XML Format. However, this serialize has the limitation that it can serialize only the public fields of an object.             

The SoapFormatter is ideal in scenarios where you need interoperability. This is ideal in applications spanning heterogeneous environments.

The BinaryFormatter generates a very compact stream when an object is serialized as compared to the other two techniques and hence is useful when data needs to travel electronically across the wire. This is appropriate when the applications do not involve heterogeneous environments.
51)  Describe difference between thread and process?
A process is an instance of running application
Thread is a execution steam of the process
 A process can have multiple thread

When process starts a specific area of memory is allocated to it
When there is a multiple thread in a process. Each thread gets a memory for storing the variable

52)  What is a difference between an Exe and a DLL?
Cannot Create Exe object
Can create DLL object
Exe is an Output process component
DLL is an IN Process Component
Exe is for single use
We can use DLL for multiple use
Exe can be started as stand alone
DLL cannot be

53)  What is the difference between Metadata and manifest?
a)      Metadata and Manifest forms an integral part of an assembly ( dll / exe ) in .net framework. Out of which Metadata is a mandatory component, which as the name suggests gives the details about various components of IL code viz : Methods , properties , fields , class etc. Essentially Metadata maintains details in form of tables like Methods Metadata tables , Properties Metadata tables , which maintains the list of Given type and other details like access specifier , return type etc.
b)      Now Manifest is a part of metadata only , fully called as “manifest metadata tables” , it contains the details of the references needed by the assembly of any other external assembly / type , it could be a custom assembly or standard System namespace .
54)  What is a satellite assembly?
a)      When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
55)  What are user controls and custom controls?
a)     Custom controls: A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASP.NET pages). A custom client control is used in Windows Forms applications.
b)     User Controls: In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control. An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class.
56)  What are the different types of caching?
a)      Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.
ASP.NET has 3 kinds of caching
1.      CachingOutput Caching: Caches the dynamic output generated by a request. Sometimes it is useful to cache the output of a website even for a minute, which will result in a better performance. For caching the whole page the page should have OutputCache directive.<%@ OutputCache Duration="60" VaryByParam="state" %>
2.      Fragment Caching: Caches the portion of the page generated by the request. Sometimes it is not practical to cache the entire page, in such cases we can cache a portion of page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
3.      Data Caching: Caches the objects programmatically. For data caching provides a cache object for eg: cache["States"] = dsStates;

57)  What is the difference between a Thread and Process?
A process is a collection of virtual memory space, code, data, and system resources. A thread is code that is to be serially executed within a process. A processor executes threads, not processes, so each application has at least one process, and a process always has at least one thread of execution, known as the primary thread. A process can have multiple threads in addition to the primary thread. Prior to the introduction of multiple threads of execution, applications were all designed to run on a single thread of execution.

When a thread begins to execute, it continues until it is killed or until it is interrupted by a thread with higher priority (by a user action or the kernel’s thread scheduler). Each thread can run separate sections of code, or multiple threads can execute the same section of code. Threads executing the same block of code maintain separate stacks. Each thread in a process shares that process’s global variables and resources.
58)   What is the difference between ADO and ADO.NET?
The old ADO (ActiveX Data Object) has evolved to ADO.NET in the .NET Framework. The ADO.NET object is a lightweight object. The ADO Recordset was a huge object in ADO. It provided the ability to support multiple types of cursors. It provided fast lightweight "firehose" cursor and also supported a disconnected client-side cursor that supported tracking, optimistic locking, and automatic batch updates of a central database. However, all of this functionality was difficult to customize.
ADO.NET breaks the functionality of the ADO object to multiple classes, thereby allowing a focused approach to developing code. The ADO.NET DataReader is equivalent to the "firehose" cursor. The DataSet is a disconnected cache with tracking and control binding functionality. The
DataAdapter provides the ability to completely customize how the central data store is updated with the changes to a DataSet.
59)   Difference between Abstract Class and Interface

1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.
3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.

60)  What is the difference between Web Services and Remoting?
Both Remoting and Web Services are ways of communication between applications.

Remoting - In remoting, the applications involved in the communication process may be located on the same computer, different computers in a same or different network. In remoting, both applications know about each other. A proxy of an application object is created on the other application.

Web Services - Communication between applications using
web services is platform independent and programming independent. The application that consumes the web service, simply accesses it, without needing to know how this web service has actually been implemented & created.

Here are some of the major differences:
  * ASP.
NET Web Services may be accessed using HTTP only. Remoting objects may be accessed over any protocol like TCP, SMTP, HTTP
  * Web Service are Stateless, whereas Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation
ASP.NET provides good support to create Web Services. They are easy to deploy. In comparison, Remoting is little complex.
  * Web services may be considered very reliable, due to the fact that they are hosted on
IIS. In remoting, if IIS is'nt used, then methods like plumbing have to be used to ensure the application reliability.
  * In .NET, when we create an application that consumes a web service, the web service may or may not be built using .NET. But while implementing Remoting in .NET, both the applications must be built in .NET.
  * Using web services, only a limited number of types may be serialized (XML). Using Remoting, objects like SOAP objects, Binary objects & XML Objects may be serialized.
61)  What is the difference between Authorization and Authentication?
Both Authentication and Authorization are concepts of providing permission to users to maintain different levels of security, as per the application requirement.

Authentication is the mechanism whereby systems may securely identify their users.
Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication system.

Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system.

When a user logs on to an application/system, the user is first Authenticated, and then Authorized.

ASP.NET has 3 ways to Authenticate a user:
1) Forms Authentication
2) Windows Authentication
3) Passport Authentication (This is obsolete in .NET 2.0)
The 4th way is "None" (means no authentication)

The Authentication Provider performs the task of verifying the credentials of the user ans decides whether a user is authenticated or not. The authentication may be set using the web.config file.

Windows Authentication provider is the default authentication provider for ASP.NET applications. When a user using this authentication logs in to an application, the credentials are matched with the Windows domain through IIS.

There are 4 types of Windows Authentication methods:
1) Anonymous Authentication - IIS allows any user
2) Basic Authentication - A windows username and password has to be sent across the network (in plain text format, hence not very secure). 3)
Digest Authentication - Same as Basic Authentication, but the credentials are encrypted. Works only on IE 5 or above
4) Integrated Windows Authentication - Relies on
Kerberos technology, with strong credential encryption

Forms Authentication - This authentication relies on code written by a developer, where credentials are matched against a database. Credentials are entered on web forms, and are matched with the database table that contains the user information.

Authorization in .NET - There are two types:

FileAuthorization - this depends on the NTFS system for granting permission
UrlAuthorization - Authorization rules may be explicitly specified in web.config for different web URLs.
62)  What is the difference between System.Array.CopyTo and System.Array.Clone in .NET?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy.
63)  What is the difference between ExecuteScalar and ExecuteNonQuery? What is ExecuteReader?
ExecuteScalar - Returns only one value after execution of the query. It returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is required.

ExecuteNonQuery - This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of
DML commands.
SqlCommand cmd = new SqlCommand("Insert Into t_SomeTable Values('1','2')",con);
//note that con is the connection object
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed
ExecuteReader - This method returns a DataReader which is filled with the data that is retrieved using the command object. This is known as a forward-only retrieval of records. It uses our SQL statement to read through the table from the first to the last record.