.NET Interview Questions

1. What is the difference between ASP and ASP.Net?

New in ASP .NET
Better language support
Programmable controls
Event-driven programming
XML-based components
User authentication, with accounts and roles
Higher scalability
Increased performance – Compiled code
Easier configuration and deployment
Not fully ASP compatible

Language Support
ASP .NET uses the new ADO .NET.
ASP .NET supports full Visual Basic, not VBScript.
ASP .NET supports C# (C sharp) and C++.
ASP .NET supports JScript as before.

ASP .NET Controls
ASP .NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined as ASP .NET control objects that can be controlled by scripts.
ASP .NET also contains a new set of object oriented input controls, like programmable list boxes and validation controls.
A new data grid control supports sorting, data paging, and everything you expect from a dataset control.

Event Aware Controls
All ASP .NET objects on a Web page can expose events that can be processed by ASP .NET code.
Load, Click and Change events handled by code makes coding much simpler and much better organized.


ASP .NET Components
ASP .NET components are heavily based on XML. Like the new AD Rotator, that uses XML to store advertisement information and configuration.


User Authentication
ASP .NET supports forms-based user authentication, including cookie management and automatic redirecting of unauthorized logins.
(You can still do your custom login page and custom user checking).

User Accounts and Roles
ASP .NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.

High Scalability
Much has been done with ASP .NET to provide greater scalability.
Server to server communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers.
Compiled Code
The first request for an ASP .NET page on the server will compile the ASP .NET code and keep a cached copy in memory. The result of this is greatly increased performance.
Easy Configuration
Configuration of ASP .NET is done with plain text files.
Configuration files can be uploaded or changed while the application is running. No need to restart the server. No more metabase or registry puzzle.
Easy Deployment
No more server restart to deploy or replace compiled code. ASP .NET simply redirects all new requests to the new code.

ASP .NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP .NET.
To overcome this problem, ASP .NET uses a new file extension ".aspx". This will make ASP .NET applications able to run side by side with standard ASP applications on the same server

2. What is the difference between ADO and ADO.Net?

It takes years to explain the differences here but have a look at these 2 links. … its really good. .. it will give clear idea about them …


and also this PowerPoint Slides. ..which will give overview of Ado.net’s objects

3. What is the difference between Record set and Data Set?

In brief…
A Recordset is a single resultset (ie. table)
A DataSet is a structure containing many DataTables. A DataTable is effectively the same as an ADO Recordset.

There are many additional features in a DataSet (ie. Relationships, etc.) and in a DataTable (ie. there is a command to give you the records that have been added / deleted / updated by the user) and DataViews (ie. a subset of the contents of the table – sorted/filtered).

See links below for more info:

4. What is the best session state mode? What is default one?
Default one is InProc. Best Session state depends on the sistuation and the complexity of the application:

Pros and cons of the three session management solutions in brief
InProc –
stored in memory on web server
Pros: least overhead, fastest performance
Cons: breaks web clusters, restarting IIS loses sessions

StateServer – managed by a remote service (aspnet_state)
HTTP protocol over TCP port.
Pros: reasonably fast, works with clusters
Cons: clear text, no authentication, overflows…

SQLServer – stored in SQL Server DB tables
Uses normal ODBC connection.
Pros: reliable, scalable
Cons: relatively slow, much overhead 

5. What is disconnected environment?

In traditional client/server applications, components establish a connection to a database and keep it open while the application is running. For a variety of reasons, this approach is impractical in many applications:

– Open database connections take up valuable system resources. In most cases, databases can maintain only a small number of concurrent connections. The overhead of maintaining these connections detracts from overall application performance.
– Similarly, applications that require an open database connection are extremely difficult to scale up. An application that does not scale up well might perform acceptably with four users but will likely not do so with hundreds. ASP.NET Web applications in particular need to be easily scalable, because traffic to a Web site can go up by orders of magnitude in a very short period.
– In ASP.NET Web applications, the components are inherently disconnected from each other. The browser requests a page from the server; when the server has finished processing and sending the page, it has no further connection with the browser until the next request. Under these circumstances, maintaining open connections to a database is not viable, because there is no way to know whether the data consumer (the client) requires further data access.
– A model based on always-connected data can make it difficult and impractical to exchange data across application and organizational boundaries using a connected architecture. If two components need to share the same data, both have to be connected, or a way must be devised for the components to pass data back and forth.

For all these reasons, data access with ADO.NET is designed around an architecture that uses connections sparingly. Applications are connected to the database only long enough to fetch or update the data. Because the database is not holding on to connections that are largely idle, it can service many more users, This Architecture is called disconnected environment.

6. How do you get Data in to DataSet?

Source Code:

using System;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient; 

           public DataSet GetDataSet
                        (string strConnect,string[] ProcName , string[] DataTable)
                        //* Purpose: Returns Dataset for one or multi datatables
                        //* Input parameters:
                        //*strConnect—-Connection string
                        //*ProcName() —StoredProcedures name in array
                        //*DataTable()—DataTable name in array
                        //* Returns :
                        //*DataSet Object contains data
              DataSet dstEorder ;
                        SqlConnection conn;
                        SqlDataAdapter dadEorder;
                                    int intCnt = ProcName.GetUpperBound(0);
                                    dstEorder = new DataSet();
                                    conn = new SqlConnection(strConnect);
                                    // if one datatable and SP
                                    if(intCnt == 0)
                                                dadEorder = new SqlDataAdapter(ProcName[0], conn);
                                                dadEorder.Fill(dstEorder, DataTable[0]);
                                    // more than one datatable and one SP
                                                //add first data table and first SP
                                                dadEorder = new SqlDataAdapter(ProcName[0], conn);                                        
                                                dadEorder.Fill(dstEorder, DataTable[0]);
                                                // add second datatable and second SP onwards
                                                for(int i=1 ;i< (intCnt +1) ;i++)
                                                dadEorder.SelectCommand = new SqlCommand(ProcName[i], conn);
                                                dadEorder.Fill(dstEorder, DataTable[i]);
                                                return dstEorder;
                                    catch ( Exception objError)
                                               //write error to the windows event log                 

            private void WriteToEventLog( Exception objError)
                        //* Purpose:Writing error to the windows event log
                       //* Input parameters:
                        //*objError—-Exception object
                        //* Returns :                                                        
                        //* ***************************************************

                        System.Diagnostics.EventLog objEventLog = new System.Diagnostics.EventLog();
                        objEventLog.Source = "Your Application Name";

Exmaple to Use

System.Data.DataSet dst ;
string[] arrProcName = new string[2];
string[] arrTableName = new string[2];                           
arrProcName[0] = ""SP_Search  ‘" + FirstName + " ‘";
arrProcName[1] = "sp_getProduct "+ prodID;
arrTableName[0] = "Search";
arrTableName[1] = "Products";
string strConnect = "Data Source=ServerName;InitialCatalog=databaseName;UID=yourUserid; PWD=yourPassword"
dst = objdb.GetDataSet(strConn,arrProcName,arrTableName);

7. How do you update the DataSet?

[Visual Basic]
Public Function CreateCmdsAndUpdate(myDataSet As DataSet, myConnection As String, mySelectQuery As String, myTableName As String) As DataSet
    Dim myConn As New OleDbConnection(myConnection)
    Dim myDataAdapter As New OleDbDataAdapter()
    myDataAdapter.SelectCommand = New OleDbCommand(mySelectQuery, myConn)
    Dim custCB As OleDbCommandBuilder = New OleDbCommandBuilder(MyDataAdapter)


    Dim custDS As DataSet = New DataSet

    ‘ Code to modify data in DataSet here

    myDataAdapter.Update(custDS, myTableName)


    Return custDS
End Function ‘SelectOleDbSrvRows

public DataSet CreateCmdsAndUpdate(DataSet myDataSet,string myConnection,string mySelectQuery,string myTableName)
    OleDbConnection myConn = new OleDbConnection(myConnection);
    OleDbDataAdapter myDataAdapter = new OleDbDataAdapter();
    myDataAdapter.SelectCommand = new OleDbCommand(mySelectQuery, myConn);
    OleDbCommandBuilder custCB = new OleDbCommandBuilder(myDataAdapter);


    DataSet custDS = new DataSet();

    //code to modify data in dataset here

    myDataAdapter.Update(custDS, myTableName);


    return custDS;

8. In Multi User environment, What happens when second user updates back end, when first user already deleted / modified the same record?

The DB locks the row until the first operation is completed and

9. What is RDBMS and In-Memory Resident RDBMS?

RDBMS, short for relational database management system and pronounced as separate letters, a type of database management system (DBMS) that stores data in the form of related tables. Relational databases are powerful because they require few assumptions about how data is related or how it will be extracted from the database. As a result, the same database can be viewed in many different ways.
An important feature of relational systems is that a single database can be spread across several tables. This differs from flat-file databases, in which each database is self-contained in a single table.

Almost all full-scale database systems are RDBMS’s. Small database systems, however, use other designs that provide less flexibility in posing queries.

In-Memory Resident RDBMS is nothing but a DB with in the memory. This is what we call also as working in disconnected mode as described above. Sometimes, it is necessary to deal with the same data in multiple pages or forms inside your application. In this situation, it is always very costly to go back to the DB and get the data, so get the dat from the DB by conencting to it once and put the Data into the classes provided by MS like SqlDataAdapter,OleDbDataAdapter,DataSet,DataTable.
DataRelation and DataView

You can use these classes to build a memory-resident representation of a database (an in-memory database). A DataSet represents the in-memory database itself. Once you create a DataSet, you can populate it with one or more DataTables that represent database tables. You create the DataTables with the help of either the SqlDataAdapter or OleDbDataAdapter class. You can then define various relationships between the tables with the DataRelation class and create filtered or sorted views on the DataTables with DataViews.

Why would you want to build an in-memory database? In certain situations, it is useful to have all the data from a database table available to your ASP.NET application in such a way that it is disconnected from the underlying database. For example, using the classes from this group, you can cache one or more database tables in your server’s memory and use the same data in multiple ASP.NET pages.

10. What is 5th Normal form?

Go thru for all types of Normal Forms.

11. What is indexing in RDBMS? Why we use and what are the types in SQL Server and what is the difference between them?

SQL Server allows two basic types of indexes:
clustered and nonclustered.


Creates an object where the physical order of rows is the same as the indexed order of the rows, and the bottom (leaf) level of the clustered index contains the actual data rows. A table or view is allowed one clustered index at a time.


Creates an object that specifies the logical ordering of a table. With a nonclustered index, the physical order of the rows is independent of their indexed order. The leaf level of a nonclustered index contains index rows. Each index row contains the nonclustered key value and one or more row locators that point to the row that contains the value. If the table does not have a clustered index, the row locator is the row’s disk address. If the table does have a clustered index, the row locator is the clustered index key for the row.
The basic difference between these two depends on what you store in the Table and the way you fetches the data from the Table.

Clustered indexes are most efficient for range queries and sorts based on the clustering keys because the data pages are sorted based on the clustering keys. However, keep in mind that clusterd indexes are more expensive when it comes updates/inserts/deletes. Also, keep the clustered index keys small because all the other nonclustered indexes will use the clustring keys to locate rows in the tabels. When you don’t have a clustered index, non-clustered indexes will have row IDs in them to map directly to the table rather than using the clustered index as an intermediary to locate rows.

Whether to use composite indexes depends on whether you want to inforce primary key or unique constraints on the table based more than one column and for performance when the criteria utilize all the the columns in the composite index.

For example, if you have a composite index on columns A and B, and your queries only restrict on B, then you won’t get much performance boost. But when your queries restrict on both A and B, then you’ll get the maximum boost.

Composite indexes are also very efficient for Covered Queries. For example, if all the columns mentioned in your query (select list, where clause, join criteria, etc) are covered by one or more indexes, then SQL server can use index intersection to get the result set without touching the table proper. For example, if you have this query:

select A, B
from SomeTable
where C = 5 and D between 1 and 2

If you have two composite indexes, one on (A, B, D), and the other on C, then the above query is covered and SQL server uses index intersection to get the results very quickly without touching the table.

12. What are the objects in DataSet?
This is queations is a bit Confusing for me. What exactly is the question here?

13. How do you define the relation between tables in Data set?

DataRelation class is used to do the same.
One of the primary functions of a DataRelation is to allow navigation from one DataTable to another within a DataSet. This allows you to retrieve all the related DataRow objects in one DataTable when given a single DataRow from a related DataTable. For example, after establishing a DataRelation between a table of customers and a table of orders, you can retrieve all the order rows for a particular customer row using DataRow.GetChildRows.

The following code example creates a DataRelation between the Customers table and the Orders table of a DataSet and returns all the orders for each customer.

[Visual Basic]
Dim custOrderRel As DataRelation = custDS.Relations.Add("CustOrders", _
                     custDS.Tables("Customers").Columns("CustomerID"), _

Dim custRow As DataRow
Dim orderRow As DataRow

For Each custRow in custDS.Tables("Customers").Rows
  For Each orderRow in custRow.GetChildRows(custOrderRel)
DataRelation custOrderRel = custDS.Relations.Add("CustOrders",
foreach (DataRow custRow in custDS.Tables["Customers"].Rows)
  foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))

14. Write the code to define the PK and FK relation ship using Data Set and its Objects.

Dim connstr As String
connstr = "Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=c:db.mdb;Mode= ReadWrite"
Dim cnn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As New DataSet()
cnn = New OleDbConnection(connstr)
da = New OleDbDataAdapter("select * from customers", cnn)
da.Fill(ds, "customers")

Here I populated the dataset with Customers table.

Primary Key Constraints
Now, we will add CustomerID as a primary key constraint to the customers table from our dataset.
Dim pk(1) As DataColumn
pk(0) = ds.Tables(0).Columns("custid")
ds.Tables("customers").PrimaryKey = pk

Foreign Key Constraints
Lets assume that we have another table called orders and I populate the orders data as follows:
Da.SelecteCommand.CommandText="select * from orders"
da.Fill(ds, "orders")

CustID is foreign key in Orders table.
Add following code that establishes foreign key constraints between them.

Dim fk As ForeignKeyConstraint
fk = New ForeignKeyConstraint("fk", ds.Tables(0).Columns("custid"),
fk.DeleteRule = Rule.Cascade
fk.UpdateRule = Rule.Cascade
ds.EnforceConstraints = True

Here we have created an object of ForeignKeyConstraint with name "fk" that sets foreign key of orders table. Next, we have also set rulaes for cascade update and deletes. Finally we have added this constraint to the constraints collection of the datatable.

15. What are the scenarios for Data Reader and Data Set Usage?

A DataReader is a stream of data that is returned from a database query. When the query is executed, the first row is returned to the DataReader via the stream. The stream then remains connected to the database, poised to retrieve the next record. The DataReader reads one row at a time from the database and can only move forward, one record at a time. As the DataReader reads the rows from the database, the values of the columns in each row can be read and evaluated, but they cannot be edited.

The DataReader can only retrieve one row at a time from the data source and in order for it to get the next record, it has to maintain its connection to the data source. The DataSet, however, doesn’t need to know about where it gets its data. The DataReader can only get its data from a data source through a managed provider. The DataSet can also get its data from a data source via a managed provider, but the data source can also be loaded manually, even from an XML file on a hard drive. If the .NET Framework does not provide a managed provider that is specifically designed for your database

Your situation will dictate when and where you’ll use a DataSet versus a DataReader. For example, the DataSet’s disconnected nature allows it to be transformed into XML and sent over the wire via HTTP if appropriate. This makes it ideal as the return vehicle from business-tier objects and Web services. A DataReader cannot be serialized and thus cannot be passed between physical-tier boundaries where only string (XML) data can go.

DataSet objects are a good choice when the data must be edited or rows added or deleted from the database. It is not the only choice, however, as a DataReader could be used to retrieve the data and changes would be sent to the database via a SqlDataAdapter through a separate, self-maintained DataRow array. That process can be quite messy because the SqlDataReader cannot allow edits as the DataSet can. As mentioned earlier, the DataSet is also a good choice when you need data manipulation such as filtering, sorting, or searching. Since the DataSet can be traversed in any direction, all of these features are available. This flexibility also makes the DataSet an easy choice when the situation calls for multiple iterations of the rowset. A DataReader can move forward only, so to loop through it more than once, the DataReader would be closed and reopened and the query would hit the database a second time

16. How do u create Data Table / Data Relation objects?

See answer to Question 14.

17. What view state in ASP.Net?

Microsoft ASP.NET Web Forms pages are capable of maintaining their own state across multiple client round trips. When a property is set for a control, the ASP.NET saves the property value as part of the control’s state. To the application, this makes it appear that the page’s lifetime spans multiple client requests. This page-level state is known as the view state of the page. In Web Forms pages, their view state is sent by the server as a hidden variable in a form, as part of every response to the client, and is returned to the server by the client as part of a postback.

The view state is a key element of an ASP.NET page because it is the primary means to persist the state of the Web server controls. Whenever the page posts back, the state is restored, updated using the current form parameters, then used to run the postback event handler. Normally, the view state is a hashed string encoded as Base64 and stored in a hidden field called __VIEWSTATE. In this way, the view state is not cached on the client, but simply transported back and forth with potential issues both for security and performance. Since it is performance overhead, you need to decide properly when and where you should use viewstate in your webform

18. Write code to maintain View State.

The viewstate is enabled by default for all the server controls.

19. Can we keep Data Set in view state?
The example stores a dataset in view state on a Web Forms page. It first creates an XML representation of the dataset and then stores the XML as a string.

Dim sw As New System.IO.StringWriter
ViewState("dsNorthwind") = sw.ToString()

This example retrieves the DataSet from a view state.
if (Page.IsPostBack)
   System.IO.StringReader sr =
      new System.IO.StringReader((string)(ViewState["dSet"]));

Note: As a rule, in the Web Applications, storing datasets in view state only if the dataset is very small. Large datasets can significantly increase the size of the ASPX page, resulting in slower download to the client and slower posting.

20. How to set the automatic state maintenance for controls?
By means of ViewState property for that Control. Set this property to true if you want automatic state maintennece. As I told you, The viewstate is enabled by default for all the server controls.

21. ** Does HTML controls support the automatic state maintenance?

22. Is view state is encrypted in between requests?
Yes, Normally, the view state is a hashed string encoded as Base64 and stored in a hidden field called __VIEWSTATE

23. What are the Record Set Lock options in ADO?

Types of Locks
Indicates optimistic batch updates. Required for batch update mode.

Many applications fetch a number of rows at once and then need to make coordinated updates that include the entire set of rows to be inserted, updated, or deleted. With batch cursors, only one round trip to the server is needed, thus improving update performance and decreasing network traffic. Using a batch cursor library, you can create a static cursor and then disconnect from the data source. At this point you can make changes to the rows and subsequently reconnect and post the changes to the data source in a batch.

Indicates that the provider uses optimistic locking—locking records only when you call the Update method. This means that there is a chance that another user may change the data between the time you edit the record and when you call Update, which creates conflicts. Use this lock type in situations where the chances of a collision are low or where collisions can be readily resolved.

Indicates pessimistic locking, record by record. The provider does what is necessary to ensure successful editing of the records, usually by locking records at the data source immediately before editing. Of course, this means that the records are unavailable to other users once you begin to edit, until you release the lock by calling Update. Use this type of lock in a system where you cannot afford to have concurrent changes to data, such as in a reservation system.

Indicates read-only records. You cannot alter the data. A read-only lock is the "fastest" type of lock because it does not require the server to maintain a lock on the records.

Does not specify a type of lock

24. What are the Cursor types and Locations in ADO?

Static cursors
Dynamic cursors
Forward-only cursors
Keyset-driven cursors

Static cursors detect few or no changes but consume relatively few resources while scrolling, although they store the entire cursor in tempdb. Dynamic cursors detect all changes but consume more resources while scrolling, although they make the lightest use of tempdb. Keyset-driven cursors lie in between, detecting most changes but at less expense than dynamic cursors.

Although the database API cursor models consider a forward-only cursor to be a distinct type of cursor, SQL Server does not. SQL Server considers both forward-only and scroll as options that can be applied to static, keyset-driven, and dynamic cursors

25. **Does all combinations of Lock types and cursor types and locations are avaialble in ADO. What happens if we set in appropriate type?

The cursor and lock type combinations that are supported by the ADO Data Providers depend on whether the cursor is located on the client side or the server side. To view combinations for a specific location, see:

See http://support.sas.com/rnd/eai/oledb/app_cursorlocktypes.htm for more eloberated discussions.

26. When we should use location as client in ADO?

Client-side cursors, specified with the adUseClient keyword, are handled internally by ADO. These cursors offer more functionality than their server-side counterparts, and also result in less load being placed on the server. Most advanced ADO functionality is designed for use with client-side cursors, and I personally use client-side cursors for all my applications.

When using a client-side adUseClient cursor, only the adOpenStatic cursor is available, and we cannot use the adLockPessimistic lock type.

Client-side cursors also help decrease load on our SQL server, since with a static cursor data is sent to the client and then the server has no further communications with the client. This allows your server to scale a lot better than with server-side cursors.

For most uses, adUseClient/adOpenStatic is your best choice, with adLockReadOnly as your lock type for any read-only operations (export to a file, load rows to a listview, combobox, etc.) and adLockOptimistic as your lock type for any read/write operations

27. What is the difference between Optimistic and Pessimistic Locking?
Optimistic lock is an implicit lock that tries to make best assumption about locking strategy and minimize time spent in lock of resource. Optimistic lock is usually implemented with some kind of timestamp strategy. Pessimistic lock is an explicit lock that set by client.

28. What are the session Modes in ASP.Net?

Storage location

InProc – session kept as live objects in web server (aspnet_wp.exe). Use "cookieless" configuration in web.config to "munge" the sessionId onto the URL (solves cookie/domain/path RFC problems too!)
StateServer – session serialized and stored in memory in a separate process (aspnet_state.exe). State Server can run on another machine
SQLServer – session serialized and stored in SQL server

InProc – Fastest, but the more session data, the more memory is consumed on the web server, and that can affect performance.
StateServer – When storing data of basic types (e.g. string, integer, etc), in one test environment it’s 15% slower than InProc. However, the cost of serialization/deserialization can affect performance if you’re storing lots
of objects. You have to do performance testing for your own scenario.
SQLServer – When storing data of basic types (e.g. string, integer, etc), in one test environment it’s 25% slower than InProc. Same warning about serialization as in StateServer

HEre I would like to add more questions related to Session State of ASP.NET.

Session states works on some web servers but not on others.
A: Maybe machine name problem. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112 .

Q: Why isn’t Session_End fired when I call Session_Abandon?
A: First of all, Session_End event is supported only in InProc mode. In order for Session_End to be fired, your session state has to exist first. That means you have to store some data in the session state and has completed at least one request.

Q: Why are my Session variables lost frequently when using InProc mode?
A: Probably because of application recycle. See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316148

Q: Why does the SessionID remain the same after the Session times out or abandoned?
A:Even though the session state expires after the indicated timeout period, the session ID lasts as long as the browser session. What this implies is that the same session ID can represent multiple sessions over time where the instance of the browser remain the same.

Q: Why does the SessionID changes in every request?
A: This may happen if your application has never stored anything in the session state. In this case, a new session state (with a new ID) is created in every request, but is never saved because it contains nothing.

However, there are two exceptions to this same session ID behavior:
– If the user has used the same browser instance to request another page that uses the session state, you will get the same session ID every time. For details, see "Why does the SessionID remain the same after the Session times out?"
– If the Session_OnStart event is used, ASP.NET will save the session state even when it is empty.

Q: Can I share session state between ASP.NET and ASP pages?
A: Yes! Here is http://www.eggheadcafe.com/articles/20021207.asp on how to do this in either direction using two "intermediate" pages. And here is another article http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/ConvertToASPNET.asp on how to do it with SQL Server.

Q: What kinds of object can I store in session state?
A: It depends on which mode you are using:
– If you are using InProc mode, objects stored in session state are actually live objects, and so you can store whatever object you have created.
– If you are using State Server or SQL Server mode, objects in the session state will be serialized and deserialized when a request is processed. So make sure your objects are serializable and their classes must be marked as so. If not, the session state will not be saved successfully. In v1, there is a bug which makes the problem happen unnoticed. See this KB for more info:

Q: How come Response.Redirect and Server.Transfer is not working in Session_End?
A: Session_End is fired internally by the server, based on an internal timer. Thus, there is no HttpRequest associted when that happens. That is why Response.Redirect or Server.Transferdoes not make sense and will not work.

Q: Do I have a valid HttpContext in Session_End?
A: No, because this event is not associated with any request.

Q: Will my session state be saved when my page hit an error?
No. Unless you call Server.ClearError in your exception handler.

Q: How do I use session state with web services?
A: The extra trick needed is on the caller side. You have to save and store the cookies used by the web service. See the MSDN documentation on HttpWebClientProtocol.CookieContainer property.

However, please note if you’re using proxy object to call a web service from your page, the web service and your page cannot share the same session state due to architecture limitation.

This can be done if you call your web service through redirect.

Q: I am writing my own HttpHandler. Why is session state not working?
A: Your HttpHandler has to implement the "marker" interface IRequiresSessionState or IReadOnlySessionState in order to use session state.

Q: I am using a webfarm, and I lost session state when directed to some web servers.
A: For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm.

Q: Why isn’t session state availabe in the Application_OnAcquireRequestState (or other)
event handler?

A: Session state is available only after the HttpApplication.AcquireRequestState event is called. For details, see: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconhandlingpublicevents.asp

Q: If using "cookieless", how can I redirect from a HTTP page to an HTTPS page?
A: Try this:
String originalUrl = "/fxtest3/sub/foo2.aspx";
String modifiedUrl = "https://localhost" + Response.ApplyAppPathModifier(originalUrl);
NOTE: Fully qualified URLs in the response.redirect, server.transfer, and FORM action
tags cannot be used with cookiless sessions. Here is an example of a fully qualified
URL: http://www.eggheadcafe.com/default.asp   More info here:http://www.eggheadcafe.com/articles/20021207.asp

Q: What isn’t Session available in my event handler in global.asax?
A: It depends on which event you’re handling. Session is available only after AcquireRequestState event.

Q: Does session state have a locking mechanism that serialize the access to state?
Session state implements a reader/writer locking mechanism:
– A page (or frame) that has session state write access (e.g. <%@ Page EnableSessionState="True" %>) will hold a writer lock on the session until the request finishes.
– A page (or frame) that has session state read access (e.g. <%@ Page EnableSessionState="ReadOnly" %>) will hold a reader lock on the session until the request finishes.
– Reader lock will block a writer lock; Reader lock will NOT block reader lock; Writer lock will block all reader and writer lock.
– That’s why if two frames both have session state write access, one frame has to wait for the other to finish first.

29. **Suppose session Mode is set to State server and the APP is
restarted, is the session state is available to the application?


30. **While n number of users are visiting our site, If we change
the global.asa, while application is running, what happens to the
session and application variables?

31. Can an application written in COBOL language be run in .Net?

YES, Fujitsu Software came up with Fujitsu Cobol which allows the COBOL programmer to take advantage of .NET. Go thru http://www.adtools.com/info/whitepaper/net.html

32. What is CTS and CLS?

CTS is Common Type System.
The common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime’s support for cross-language integration. The common type system performs the following functions:

– Establishes a framework that helps enable cross-language integration, type safety, and high performance code execution.
– Provides an object-oriented model that supports the complete implementation of many programming languages.
– Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other.
More at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconthecommontypesystem.asp

To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the common type system; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages. The CLS also establishes requirements for CLS compliance; these help you determine whether your managed code conforms to the CLS and to what extent a given tool supports the development of managed code that uses CLS features

33. What is auto event wire up property in asp.net?

Events raised by ASP.NET server controls work somewhat differently than events in traditional client forms or in client-based Web applications. The difference arises primarily because of the separation of the event itself from where the event is handled.

In client-based applications, events are raised and handled on the client. In Web Forms pages, on the other hand, events associated with server controls are raised on the client but handled on the Web server by the ASP.NET page framework.

For events raised on the client, the Web Forms control event model requires that the event information be captured on the client and an event message transmitted to the server, via an HTTP post. The page framework must interpret the post to determine what event occurred and then call the appropriate method in your code on the server to handle the event.

The ASP.NET page framework also supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true (or if it is missing, since by default it is true), the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.

The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name your event handlers. Therefore, in Visual Studio, the AutoEventWireup attribute is set to false by default and the designer generates explicit code to bind page events to methods.

If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs

34. What is meta data?
Metadata is a description or definition of electronic data, or data about data. Often, metadata can only be accessed in certain viewing modes. Metadata can include descriptive HTML tags and information about when a document was created, and what changes have been made on that document

35. What is reflection and what’s its use?

REflection is basically a process of knowing about the properties of an assembly at run time.
The reflection reflects, the classes, interfaces, and objects in the current assembly. You’ll want to use the reflection if you are writing development tools such as debuggers, class browsers, and GUI builders.

With the reflection you can:
– Determine the class of an object.
– Get information about a class’s modifiers, fields, methods, constructors, and superclasses.
– Find out what constants and method declarations belong to an interface.
– Create an instance of a class whose name is not known until runtime.
– Get and set the value of an object’s field, even if the field name is unknown to your program until runtime.
– Invoke a method on an object, even if the method is not known until runtime.
– Create a new array, whose size and component type are not known until runtime, and then modify the array’s components

36. What is delegate? Explain? Write code?

A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure

The following is a simple example of declaring and using a delegate.

// keyword_delegate.cs
// delegate declaration
delegate void MyDelegate(int i);

class Program
   public static void Main()
      TakesADelegate(new MyDelegate(DelegateFunction));

   public static void TakesADelegate(MyDelegate SomeFunction)
   public static void DelegateFunction(int i)
      System.Console.WriteLine("Called by delegate with number: {0}.", i);

37. What is shadowing in vb.net?

Shadowing is a concept of polymorphism usage in Object Oriented Programming.
This is a concept related to over-riding functions at run-time or making a shadow of the object’s methods in the inherited classes.
The Shadows keyword indicates that a declared programming element shadows, or hides, an identically named element, or set of overloaded elements, in a base class. You can shadow any kind of declared element with any other kind

The purpose of shadowing is to protect the definition of your class members. The base class might undergo a change that creates an element with the same name as one you have already defined. If this happens, the Shadows keyword forces references through your class to be resolved to your previously defined member, instead of to the new base class element.

38. What is the difference between namespace and assemblies?

A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under the control of the developer. For example, types MyCompany.FileAccess.A and MyCompany.FileAccess.B might be logically expected to have functionality related to file access. The .NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality, such as the Microsoft® ASP.NET application framework, or remoting functionality. Design tools can make use of namespaces to make it easier for developers to browse and reference types in their code. The concept of a namespace is not related to that of an assembly. A single assembly may contain types whose hierarchical names have different namespace roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a namespace is a logical design-time naming convenience, whereas an assembly establishes the name scope for types at run time.



One thought on “.NET Interview Questions

  1. i like these faqs. because i am a learner to .NET and i am working on VB. really these are very helpful to the people like me…thanks very much for these faqs. i request you to please update my knowledge with the faqs like this whenver you have…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s