HI WELCOME TO SIRIS

asp.net interview questions part 4

Leave a Comment

Managed Code and Unmanaged Code related ASP.NET Interview Questions


What is Managed Code and Unmanaged Code? 
Microsoft ASP.NET Web applications run under the control of the common language runtime (CLR). The CLR controls how the application’s assembly executes, allocates, and recovers memory; therefore, ASP.NET applications are said to use managed code. In contrast, most other Windows executables use unmanaged code because the executable itself determines how memory is used.

Examples of unmanaged code include the Microsoft Win32 API, legacy DLLs and EXEs created for Windows applications prior to the Microsoft .NET Framework, and COM objects.


What is Platform Invoke or pinvoke?
The process of executing native code from within a .NET assembly is called platform invoke, or pinvoke for short. You use platform invoke to call the Win32 API directly, to access existing (legacy) DLLs your company uses, or to access procedures compiled to native code for performance reasons.

What are the steps to follow to use Platform Invoke? 
To use platform invoke, follow the following steps:
1. Import the System.Runtime.InteropServices namespace.
2. Declare the unmanaged procedure using the DllImport attribute or the Declare statement.
3. Map the data types of the procedures parameters to the equivalent .NET types.
4. Call the unmanaged procedure and test its return value for success.
5. If the procedure did not succeed, retrieve and handle the exception code using the Marshal object’s GetLastWin32Error method.


What are the limitations of using Unmanaged Code from within a .NET assembly?
Performance : 
Although native-code DLLs can perform some operations more quickly than equivalent code managed by the CLR, these benefits might be offset by the time it takes to marshal the data to pass between the unmanaged procedure and the .NET assembly.
Type safety : Unlike .NET assemblies, unmanaged procedures might not be type-safe. This can affect the reliability of your .NET application. In general, reliability is a paramount concern with ASP.NET Web applications.
Code security : Unmanaged procedures do not use the .NET Framework’s model for code security.
Versioning:Unmanaged code does not support .NET versioning; therefore, assemblies that call unmanaged procedures might lose the benefit of being able to coexist with other versions of the same assembly.


What are COM objects?
COM objects are another type of unmanaged code that you can use from .NET assemblies. Because COM is widely used, Visual Studio includes built-in tools for importing and using COM objects within .NET assemblies. Visual Studio also includes the option of automatically registering .NET class library assemblies for use from COM.

List the steps in order, to use a COM object from a .NET assembly in Visual Studio? 
1. Install and register the COM object on your system.
2. Open the .NET project in Visual Studio, and add a reference to the COM object, as shown in diagram below. If the COM object does not appear on the COM tab of the Add Reference dialog box, you can add a reference directly to the executable by clicking Browse. 


3. Create an instance of the COM object in code, and use it as you would any other object.

What happens when you add a reference to a COM object from with in a dot net application?
When you add a reference to a COM object, Visual Studio automatically generates an interop assembly for the object and places it in the project’s /bin folder. The interop assembly is created from the COM object’s type information and contains the metadata that the CLR uses to call the unmanaged code in the COM object. You can then use COM objects from within .NET code the same way that you use .NET classes.

You can view this interop assembly using the Microsoft Intermediate Language Disassembler (Ildasm.exe) included in the .NET Framework.

Can we create a .NET object for use from COM? 
Yes, Visual Studio can automatically generate type library information and register a .NET class library assembly for use from COM. These automatic tools do not work for ASP.NET Web applications, so you must isolate the code you want to use from COM in its own Class Library project.


How do you hide Public .NET Classes and other public members from COM?
In some cases, you might want to hide selected .NET classes from COM but keep them public for use from other .NET assemblies. The ComVisible attribute allows you to select which public .NET classes and members are included in the generated type library. This attribute applies hierarchically for the assembly, class, and member levels.
How do you handle exceptions between .NET and COM? 
.NET handles errors through exception classes. COM handles errors through 32-bit data types called HRESULTs. All of the .NET exception classes include HResult properties that map to COM HRESULT codes.

If an exception occurs in a .NET object, the exception is automatically mapped to the appropriate HRESULT and returned to COM. Similarly, if an exception occurs in a COM object, the COM HRESULT is mapped to the appropriate exception class, which is returned to .NET, where it can be handled just like any other exception.

If you are creating your own .NET exception classes for use with COM, be sure to set the class’s HResult property so that the exception can be handled within COM.


What are the technical limitations of COM Interop?
The .NET Framework was developed to address the limitations of COM. Because of this evolution, there are limits to the .NET features that you can use from COM. The following list describes these limits:
Static members : COM requires objects to be created before use, so it does not support .NET Static members.
New members : COM flattens the inheritance tree of .NET objects, so members in a derived class that hides members inherited from a base class are not callable.
Constructors with parameters : COM can’t pass parameters to an object’s constructor.

What are the practical limitations of using COM objects? 
The following are the practical limitations of using COM objects from .NET:
Shared solutions might not allow COM objects : ASP.NET host service providers that use nondedicated servers can limit or prohibit the installation of COM objects on their servers.
COM objects are prone to memory leaks : COM uses reference counting to determine when to destroy objects and free memory. It is possible for this reference count to become incorrect, leaving objects in memory indefinitely.
Type libraries might be inaccurate : Because COM separates the object’s description from its implementation, it’s possible for this description to not accurately reflect the object. In this case, the generated interop assembly will also include those inaccuracies.
COM is unmanaged code : All the limitations of unmanaged code apply to COM objects as well.

Interview Questions on ASP.NET Exception Handling


What are Exceptions? 
Exceptions are unusual occurrences that happen within the logic of an application.

What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception handling (SEH) in the Visual Studio .NET documentation.
                try
                catch
                finally 
2. Use error events to deal with exceptions within the scope of an object.
                Page_Error
                Global_Error 
                Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.

Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.

Will the finally block gets executed, if an exception occurs? 
Yes, a finally block will always be executed irrespective of whether an exception has occured or not.

What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.

How do you raise an exception? 
Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to the catch statement.

Will the following code block compile?
try
{
     throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
     Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
     Response.Write(FNFE.Message);
}

No, the following compile time error is reported.
A previous catch clause already catches all exceptions of this or of a super type ('System.Exception').


Catch blocks are evaluated in the order in which they appear in code. The exception declaration of each catch block determines which type of exception the catch block handles. Always order catch blocks from most specific to most general. So, in the preceding sample, FileNotFoundException should be placed before the general Exception catch block.

What is ApplicationException class used for?
If you are creating a large application or creating components that are used by other applications, you might want to define your own exception classes based on the ApplicationException class.

For example, the following code defines a class for the UserLoggedOnException:


public class UserLoggedOnException : System.ApplicationException
{
     // Exception constructor (overloaded).
     public UserLoggedOnException()
     : this("The user is already logged on to the server", null)
     {
     }
     public UserLoggedOnException(string message)
     : this(message, null)
     {
     }
     public UserLoggedOnException(string message, Exception inner)
     : base(message, inner)
     {
     }

The preceding UserLoggedOnException class inherits its properties and methods from the ApplicationException base class. The new exception class provides only its own constructor to set the default message to display. This is a standard practice.

What are Error Events? 
Another way to handle exceptions is through the Web objects’ built-in error events. When an unhandled exception occurs in a Web application, ASP.NET fires the error events shown below.

Page_Error : Occurs when an unhandled exception occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Application_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.

Error events let you handle exceptions for an entire object in a single, centralized location—the error event procedure. This is different from using exception-handling structures, in which exceptions are handled within the procedure where they occurred. You can use error events in the following ways:

As a substitute for exception-handling structures :
Because error events occur outside the scope of the procedure in which the error occurred, you have less information about the steps leading up to the exception and therefore less ability to correct the exception condition for the user. However, using exception-handling events is fine for tasks where you might not be able to correct the exception in code.
As an adjunct to exception-handling structures :
Error events can provide a centralized “backstop” against exceptions that were not foreseen or handled elsewhere. Using the two exception-handling techniques together lets you catch all exceptions before the user sees them, display a reasonable message, and even record the exception in a log as part of an ongoing effort to improve your application.

Give an example to show how error events can be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get the exception that occurred using the GetLastError method.
2. Do something with the exception, such as display a message to the user, take steps to correct the problem, or write to an error log.
3. Clear the exception using the ClearError method.
4. Redisplay the page. Web form processing stops immediately when an exception occurs, so server controls and other items on the page might not be displayed after the exception is cleared.
5. Add the following code to Page_Error event procedure on the web page.
private void Page_Error(object sender, System.EventArgs e)
{
     // Get the error.
     Exception ex = Server.GetLastError();
     // Store the message in a session object.
     Session["Error"] = ex.Message;
     // Clear the error message.
     Server.ClearError();
     // Redisplay this page.
     Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the exception message as a Session state variable before clearing the exception so that the message can be displayed when the page is reloaded by the Transfer method. The following code displays the saved exception message when the page is redisplayed:

Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object sender, System.EventArgs e)
{
     // Display error. if any.
     if (Session["Error"] != null)
     {
     litError.Text = "The following error occurred:
     " +
     Session["Error"].ToString();
     // Clear the Session state variable.
     Session["Error"] = null;
     }
}

Can you have a try block without a catch or a finally block? 
No, you cannot have a try block without a catch or a finally block. A try block cannot exist in isolation. A try block should be followed by either a catch block or a finally block or both.

Is the following code legal?
try
{
     Response.Write("Try block executed");
}
finally
{
     Response.Write("Finally block executed");


Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.

What is wrong with using the following type of exception handler?
catch(Exception E)
{
     //Some Code
}
This handler catches exceptions of type Exception, therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.


Will the second catch block handle the exception thrown by the first catch block? 
try
{
     throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
     Response.Write(FNFE.Message);
     throw new Exception();
}
catch(Exception E)
{
     Response.Write(E.Message);
}

No. For a catch block to handle the exception, the statement that raised the exception must be inside a try block.

What will happen to the exception raised by the code in the following Button1_Click event procedure?
protected void Button1_Click(object sender, EventArgs e)
{
     throw new Exception();
     try
     {
          Response.Write("Hello");
     }
     catch (Exception E)
     {
          Response.Write(E.Message);
     }
}

The exception will not be handled by the catch block because the statement that raised the exception must be inside a try block.

ASP.NET Events related Interview Questions


What are the different levels at which events can occur in an ASP.NET web application?Web application events occur at the application, page, and server control levels

Give some examples for application level events? 


1. Application_Start
Occurs when the first user visits a page within your Web application.

2. Application_End 
Occurs when there are no more users of the application.

3. Application_BeginRequest 
Occurs when at the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the application.

4. Application_EndRequest 
Occurs when at the end of each request to the server.

5. Session_Start 
Occurs when a new user visits a page within your application.

6. Session_End 
Occurs when a user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified in the Web.config file.

7. Application_Error 
Occurs when when there is an unhandled exception in an application.


Where are the application level event handlers present in an ASP.NET web application?Application level event handlers are present in Global.asax of an ASP.NET web application

What is the difference between Application and Session Events? 
At an application level we can have Application and Session events. Use Application events to initialize objects and data that you want to make available to all the current sessions of your Web application. Use Session events to initialize data that you want to keep throughout individual sessions, but that you don’t want to share between sessions.


Give an example of how to use Application and Session events?To see how Application and Session events occur, add the following code to the Global.asax file in a Web forms project.void Application_Start(object sender, EventArgs e)
{
// Create Application state variables.
Application["AppCount"] = 0;
Application["SessCount"] = 0;
// Record application start.
Application["AppCount"] = (int)Application["AppCount"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Count sessions.
Application["SessCount"] = (int)Application["SessCount"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement sessions.
Application["SessCount"] = (int)Application["SessCount"] - 1;
}

Add the following code to WebForm1.aspx file in a Web forms project and set WebForm1 as start up page.
protected void Page_Load(object sender, EventArgs e)
{
// Display Application count.
Response.Write("Number of applications: " +
Application["AppCount"] + "
");
// Display session count.
Response.Write("Number of sessions: " +
Application["SessCount"] + "
");
}
To demonstrate the events, run the preceding code, and then start a new instance of the browser and navigate to the address. Each new instance of the browser increments the session count, but the application count stays at 1.

How long a webform instance is available on the web server? 
Web forms live for barely a moment. When we request a webform from the browser, the applications executable creates an instance of the requested Web form, generates the HTML to respond to the request, and posts that response to the browser. It then destroys the instance of the Web form.

When the client browser has the generated HTML, the user can type text in boxes, select options, and perform other tasks until triggering a postback event, such as a button click. Postback events cause the browser to send the page’s data (view state) back to the server for event processing. When the server receives the view state, it creates a new instance of the Web form, fills in the data from the view state, and processes any events that occurred. As soon as the server has finished, it posts the resulting HTML back to the browser and destroys the instance of the Web form.


Give some examples for page level events and when they occur?
1. Page_Init 

During Page_Init the server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.

2. Page_Load 
During Page_Load the server controls are loaded in the Page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.

3. Page_PreRender 
During Page_PreRender the application is about to render the Page object.

4. Page_Unload 
During Page_Unload the page is unloaded from memory.

5. Page_Disposed 
During Page_Disposed the Page object is released from memory. This is the last event in the life of a Page object.

6. Page_Error 
Page_Error event is raised when an unhandled exception occurs.

7. Page_AbortTransaction 
Page_AbortTransaction is raised when a transaction is aborted.

8. Page_CommitTransaction 
Page_CommitTransaction is raised when a transaction is commited.

9. Page_DataBinding 
Page_DataBinding occurs when a server control on the page binds to a data source.

What is the order in which Page level events occur?
Page_Init
Page_Load
Page_PreRender
Page_Unload
Page_Disposed


What page property is used to differentiate between a postback and initial get request of a page?
IsPostback property of the Page class.

What are the 3 types of Server Control Events? 
Server controls, such as a Button, TextBox, and DropDownList, each have their own sets of events that occur in response to user actions. However, not all server control events are created equal. There are three types of server control events as listed below.
Postback events :These events cause the Web page to be sent back to the server for immediate processing. Postback events affect perceived performance because they trigger a round-trip to the server. A Button control triggers a postback event. A dropdowinlist can also trigger a post back if the AutoPostBack property of the DropDownList is set to true, else a dropdownlist triggers a cached event. The same is the case with a TextBox.

Cached events : 
These events are saved in the page’s view state to be processed when a postback event occurs. A DropDownList and a TextBox can trigger a cached event if the AutoPostBack property is set to false.

Validation events : 
These events are handled on the page without posting back or caching. The validation server controls use these types of events.
How can you convert a Cached event of control to a post back event?You can convert a Cached event of control to a post back event by setting the AutoPostBack property to true.

What is the order in which events are executed? 
The validations controls are evaluated before the page is posted back to the server. When the page is posted back, the Page_Init and Page_Load events are handled, then cached events are handled, and finally the event that caused the postback is processed. Among cached events, the event order is determined by the order of the controls on the Web form.

ASP.NET Interview Questions on Cookies


What are Cookies in ASP.NET? 
Cookies are small pieces of information stored on the client computer.Use cookies to store small amounts of information on the client’s machine. Web sites often use cookies to store user preferences or other information that is client-specific. Because cookies can be refused, it is important to check whether the browser allows them before you try to create them.They are limited to storing only character data and they are limited to 4K in size.


What are different types of Cookies?
Session Cookies
Persistent Cookies

What are Session Cookies? 
Session cookies are stored in-memory during the client browser session. When the browser is closed the session cookies are lost.


How can you create Session Cookies?
You can create session cookies by calling the Add method of the Cookies collection on the Response object. The Cookies collection contains individual cookie objects of type HttpCookie.

//Code to create a UserName cookie containing the name David.
HttpCookie CookieObject = new HttpCookie("UserName", "David");
Response.Cookies.Add(CookieObject); 


//Code to read the Cookie created above
Request.Cookies["UserName"].Value;

What is the difference between Session Cookies and Persistent Cookies?
Persistent Cookies are same as Session Cookies except that, persistent cookies have an expiration date. The expiration date indicates to the browser that it should write the cookie to the client's hard drive. Keep in mind that because a user can delete cookies from their machine that there is no guarantee that a cookie you "drop" on a user machine will be there the next time they visit your site.

What are Persistent Cookies used for? 
Persistent cookies are generally used to store information that identifies a returning user to a Web site. Typical information found in Persistent Cookies includes user names or user IDs.


How do you create a Persistent Cookie?
You create a persistent cookie the same way as session cookies except that you set the Expires property to a Date in the future which will store the Cookie to the client computer harddrive.

//Code to create a UserName Persistent Cookie that lives for 10 days
HttpCookie CookieObject = new HttpCookie("UserName", "David");
CookieObject.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(CookieObject); 


//Code to read the Cookie created above
Request.Cookies["UserName"].Value; 

What is Cookie Dictionary? 
A cookie dictionary is a single cookie object that stores multiple pieces of information. You use the Values property to access and assign new values to the cookie dictionary.


Give an example using Cookie Dictionary?
//Code to create a Cookie Dictionary
HttpCookie CookieObject = new HttpCookie("UserPreference"); 

//Use the Values property to assign new values to the cookie dictionary
CookieObject.Values.Add("UserName", "David");
CookieObject.Values.Add("Country", "USA");
CookieObject.Values.Add("PreviousVisit", DateTime.Now.ToString());
CookieObject.Expires = DateTime.MaxValue; 


//Add the Cookie to the client machine using the Response object
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
HttpCookie ObjectCookie = Request.Cookies["UserPreference"];
string UserName = ObjectCookie.Values["UserName"];
string Country = ObjectCookie.Values["Country"];
string PreviousVisit = ObjectCookie.Values["PreviousVisit"];



What are the advantages of Using Cookies? 
1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).


What are the disadvantages of Using Cookies?
1. Users can delete a cookies.
2. Users browser can refuse cookies,so your code has to anticipate that possibility.
3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.


How do you create a Cookie that never expires?
To create a Cookie that never expires set the Expires property of the Cookie object to DateTime.MaxValue.

Are Cookies secure? 
No, Cookies are not secure. You must pay attention to the type of data you store in cookies.
1. Cookies are not designed to store critical information so storing passwords in a cookie is a bad idea.
2. Keep the lifetime of a cookie as short as practically possible.
3. Encrypt cookie data to help protect the values stored in the cookie.

What are the 2 types of controls that you can use on a webform in ASP.NET?
Web Server Controls
HTML Controls

What’s the difference between Server controls and HTML controls? 
1. Server controls can trigger control-specific events on the server.HTML controls can trigger only page- level events on server (postback).
2. Data entered in a server control is maintained across requests. Server controls retain state.Data is not maintained in an HTML control. Data must be saved and restored using page-level scripts.
3. The Microsoft .NET Framework provides a set of properties for each server control. Properties allow you to change the server control’s appearance and behavior within server-side code.HTML controls have HTML attributes only.
4. Server controls automatically detect browser and adapt display as appropriate.HTML controls do not adapt automatically. You must detect browser in code or write for least common denominator.

What are the 2 Layouts supported by a Web form in ASP.NET?
Grid layout -
 Controls are placed exactly where you draw them, and they have absolute positions on the page. Use grid layout for Microsoft Windows–style applications, in which controls are not mixed with large amounts of text. Pages using grid layout will not always display correctly in non-Microsoft browsers.
Flow layout - This layout positions controls relative to other elements on the page. If you add elements at run time, the controls that appear after the new element move down. Use flow layout for document-style applications, in which text and controls are intermingled.



When do you choose between GridLayout and Flow layout for Web forms?
You use GridLayout for Web forms that have a fixed appearance. You use FlowLayout for Web forms that incorporate text and controls.When you create controls with GridLayout, Visual Studio adds style attributes to each control that set the position of the control.When you create controls with FlowLayout, Visual Studio omits the style attribute.

Give 3 reasons why we use HTML controls over Server Controls? 
Migration from earlier versions of Active Server Pages (ASP) : You can load an ASP application into Visual Studio and revise it gradually, rather than rewrite it completely. Earlier versions of ASP supported only HTML elements, and these elements become HTML controls when you load the project in Visual Studio .NET.
Not all controls require server-side events or state management : This is particularly true when you’re doing data binding. Bound items are usually refreshed from the data source with each request, so it’s more efficient not to maintain state information for bound controls. This means that you can use HTML controls or turn off state management for bound server controls.
You have complete control over what is rendered with HTML controls : ASP.NET adjusts the appearance of server controls based on the browser making the request. HTML controls are not adjusted, so you have direct control over their appearance.
How can you prevent users from editing Text in TextBox control on a web form?By making the TextBox a readonly TextBox. To make a TextBox readonly set the ReadOnly property to True.

How do you convert an ASP.NET TextBox to accept passwords? 
To convert and ASP.NET TextBox to accept passwords set the TextMode property to "Password"
What happens when you set the AutoPostBack property of a TextBox to true?
When AutoPostBack property is set to True, the TextBox control fires a TextChanged postback event when the user leaves the TextBox control after changing the contents. By default, this property is set to False and the Text­Changed event is cached until some other postback event occurs.

What are the 3 values that a TextMode property of TextBox can have? 
SingleLine : Single Line TextBox
MultiLine : Multi Line TextBox(scrollable)
Password : When set to Password, the text box displays dots in place of the characters typed.
How do you limit the number of characters entered by a user in the ASP.NET TextBox?By setting the MaxLength property of the TextBox. If you set the MaxLength property to 10, a user can enter only 10 characters into the TextBox.

Basic ADO.NET Interview Questions


What is Microsoft ADO.NET?
Visual Studio .NET provides access to databases through the set of tools and namespaces collectively referred to as Microsoft ADO.NET

What are the 3 major types of connection objects in ADO.NET? 
OleDbConnection object : Use an OleDbConnection object to connect to a Microsoft Access or third-party database, such as MySQL. OLE database connections use the OleDbDataAdapter object to perform commands and return data.
SqlConnection object : Use a SqlConnection object to connect to a Microsoft SQL Server database. SQL database connections use the SqlDataAdapter object to perform commands and return data.
OracleConnection object : Use an OracleConnection object to connect to Oracle databases. Oracle database connections use the OracleDataAdapter object to perform commands and return data. This connection object was introduced in Microsoft .NET Framework version 1.1.


List the 4 common ADO.NET Namespaces?
System.Data :
 Contains Classes, types, and services for creating and accessing data sets and their subordinate objects
System.Data.SqlClient : Contains Classes and types for accessing Microsoft SQL Server databases
System.Data.OracleClient : Contains Classes and types for accessing Oracle databases (Microsoft .NET Framework version 1.1 and later)
System.Data.OleDb : Contains Classes and types for accessing other databases


List all the steps in order, to access a database through ADO.NET?
1.
 Create a connection to the database using a connection object.
2. Invoke a command to create a DataSet object using an adapter object.
3. Use the DataSet object in code to display data or to change items in the database.
4. Invoke a command to update the database from the DataSet object using an adapter object.
5. Close the database connection if you explicitly opened it in step 2 using the Open method. Invoking commands without first invoking the Open method implicitly opens and closes the connection with each request.


Why will you usually create an ASPNET user account in the Database for an ASP.NET web application?
Web applications run using the ASPNET user account. The SQL database administrator will have to set up this account and grant it permissions before your Web application will have access to a SQL database. For file-based databases, such as Microsoft Access, you must grant permissions on the database file to the ASPNET user account using Windows file security settings.

What is the difference between DataReader and DataAdapter? 
1. Data Reader is read only forward only and much faster than DataAdapter.
2. If you use DataReader you have to open and close connection explicitly where as if you use DataAdapter the connection is automatically opened and closed.
3. DataReader is connection oriented where as Data Adapter is disconnected
Can you inherit from SqlConnection Class?
No, you cannot inheirt from SqlConnection Class. SqlConnection Class is a sealed class. It is a compile time error.

Will the connection be closed, if the SqlConnection object goes out of scope? 
No, If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose.


What happens if connection pooling is enabled?
If connection pooling is enabled and when you call Close or Dispose methods, then the connection is returned to the connection pool. This connection can then be resused.If connection pooling is disabled and when you call Close or Dispose methods, the underlying connection to the server is actually closed.

How do you ensure that the database connections are always closed? 
To ensure that the database connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
using (SqlConnection ConnectionObject = new SqlConnection())
{
ConnectionObject.Open();
//The database connection will be closed when the control exits the using code block
}

How do you read an XML file into a DataSet?
Using the DataSet object’s ReadXML method.

When do you use ExecuteReader, ExecuteNonQuery, ExecuteScalar methods?
If the command or stored procedure that is being executed returns a set of rows, then we use ExecuteReader method.
If the command or stored procedure that is being executed returns a single value then we use ExecuteScalar method.
If the command or stored procedure performs INSERT, DELETE or UPDATE operations, then we use ExecuteNonQuery method. ExecuteNonQuery method returns an integer specifying the number of rows inserted, deleted or updated.

Can your class inherit from SqlCommand Class? 
No, you cannot inheirt from SqlCommand Class. SqlCommand Class is a sealed class. It is a compile time error.

Give an example that shows how to execute a stored procedure in ADO.NET?

using (SqlConnection ConnectionObject = new SqlConnection())
{
//Specify the name of the stored procedure to execute and the Connection Object to use
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify the SQL Command type is a stored procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Open the connection
ConnectionObject.Open();
//Execute the Stored Procedure
int RecordsAffected = CommandObject.ExecuteNonQuery();
}

Can you reuse a SqlCommand object? 
Yes, you can reset the CommandText property and reuse the SqlCommand object.

What are the methods that can ensure asynchronous execution of the Transact-SQL statement or stored procedure?
BeginExecuteNonQuery
BeginExecuteReader

What is SqlCommand.CommandTimeout Property used for? 
CommandTimeout Property is used to Get or set the wait time before terminating the attempt to execute a command and generating an error.
//Specify the CommandTimeout property value
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Wait for 10 seconds to execute the Stored procedure
CommandObject.CommandTimeout = 10; 

The time is in seconds. The default is 30 seconds.

Frequently asked ADO.NET Interview Questions


How do you create an instance of SqlDataReader class?
To create an instance of SqlDataReader class, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.//Error! Cannot use SqlDataReader() constructor
//to create an instance of SqlDataReader class
SqlDataReader ReaderObject = new SqlDataReader();

//Call the ExecuteReader method of the SqlCommand object
SqlCommand CommandObject = new SqlCommand();
SqlDataReader ReaderObject = CommandObject.ExecuteReader();

Creating an instance of SqlDataReader class using SqlDataReader() constructor generates a compile time error - The type 'System.Data.SqlClient.SqlDataReader' has no constructors defined.


How do you programatically check if a specified SqlDataReader instance has been closed?Use the IsClosed property of SqlDataReader to check if a specified SqlDataReader instance has been closed. If IsClosed property returns true, the SqlDataReader instance has been closed else not closed.

How do you get the total number of columns in the current row of a SqlDataReader instance? 
FieldCount property can be used to get the total number of columns in the current row of a SqlDataReader instance.

Give an example for executing a stored procedure with parameters?
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify to CommandObject that you intend to execute a Stored Procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Create an SQL Parameter object
SqlParameter ParameterObject = new SqlParameter();
//Specify the name of the SQL Parameter
ParameterObject.ParameterName = "Parameter1";
//Assign the Parameter value
ParameterObject.Value = "Some Value";
//Specify the Database DataType of the Parameter
ParameterObject.DbType = DbType.String;
//Specify the type of parameter - input-only, output-only, bidirectional
ParameterObject.Direction = ParameterDirection.Input;
//Associate the Parameter to the Command Object
CommandObject.Parameters.Add(ParameterObject);
//Open the connection
ConnectionObject.Open();
//Execute the command
int Records_Affected = CommandObject.ExecuteNonQuery();
//Close the Connection
ConnectionObject.Close();


What is the use of SqlParameter.Direction Property?
SqlParameter.Direction Property is used to specify the Sql Parameter type - input-only, output-only, bidirectional, or a stored procedure return value parameter. The default is Input.

How do you retrieve two tables of data at the same time by using data reader? 
Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.

The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table. The following code shows you how do it.
//Create the SQL Query with 2 Select statements
string SQLQuery = "Select * from Customers;Select * from Employees;";
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand(SQLQuery, ConnectionObject);
//Open the connection
ConnectionObject.Open();
//Execute the command. Now reader object will have 2 tables of data.
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
//Loop thru the tables in the DataReader object
while (ReaderObject.NextResult())
{
while (ReaderObject.Read())
{
//Do Something
}
}
//Close the Reader
ReaderObject.Close();
//Close the Connection
ConnectionObject.Close();

What are the advantages of using SQL stored procedures instead of adhoc SQL queries in an ASP.NET web application? 
Better Performance : As stored procedures are precompiled objects they execute faster than SQL queries. Every time we run a SQL query, the query has to be first compiled and then executed where as a stored procedure is already compiled. Hence executing stored procedures is much faster than executing SQL queries.
Better Security : For a given stored procedure you can specify who has the rights to execute. You cannot do the same for an SQL query. Writing the SQL statements inside our code is usually not a good idea. In this way you expose your database schema (design) in the code which may be changed. Hence most of the time programmers use stored procedures instead of plain SQL statements.
Reduced Network Traffic : Stored Procedures reside on the database server. If you have to execute a Stored Procedure from your ASP.NET web application, you just specify the name of the Stored Procedure. So over the network you just send the name of the Stored Procedure. With an SQL query you have to send all the SQL statements over the network to the database server which could lead to increased network traffic.


Can you update the database using DataReader object?
No, You cannot update the database using DataReader object. DataReader is read-only, foward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record.

What is the difference between a DataReader and a DataSet?

 DataReader
1.
 DatReader works on a Connection oriented architecture.
2. DataReader is read only, forward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record. So using a DataReader you read in forward direction only.
3. Updations are not possible with DataReader.
4. As DataReader is read only, forward only it is much faster than a DataSet.

DataSet
1.
 DataSet works on disconnected architecture.
2. Using a DataSet you can move in both directions. DataSet is bi directional.
3. Database can be updated from a DataSet.
4. DataSet is slower than DataReader.
Give an example scenario of using a DataSet and a DataReader?If you want to just read and display the data(No updates, deletes, or inserts) then use a DataReader.
If you want to do a batch inserts, updates and deletes then use a DataSet.

ASP.NET Interview Questions on windows authentication


What is the advantage of using Windows authentication in a Web application?
Windows authentication uses the security features integrated into the Windows NT and Windows XP operating systems to authenticate and authorize Web application users. The advantage of Windows authentication is that your Web application can use the exact same security scheme that applies to your corporate network - user names, passwords, and permissions are the same for network resources and Web applications. One of the key advantages of Windows authentication is that users who are logged on to the network don’t have to log on again to access the Web application.

What is the default authentication method when you create a new Web application project? 
Windows authentication is the default authentication method when you create a new Web application project.

How do you allow or deny access to specific users using an authorization list from Web.config file, when using windows authentication? 
When the application uses Windows authentication, ASP.NET checks the project’s Web.config authorization list to see which network users are allowed to access the application. The asterisk (*) and question mark (?) characters have special meaning in the authorization list. The * character indicates all users. The ? character indicates unauthenticated users.

To restrict access to specific users, list their names separated by commas in an element. When ASP.NET checks the authorization list in Web.config, it accepts the first match that it finds. Be sure to end the authorization list with a element to deny access to any nonapproved users.


What is Role-Based authorization in windows authentication?
Role-based authorization lets you identify groups of users to allow or deny based on their role in your organization. In Windows NT and Windows XP, roles map to names used to identify user groups. Windows defines several built-in groups, including Administrators, Users, and Guests. You can view, modify, or add groups using the Computer Management console

To allow or deny access to certain groups of users, add the element to the authorization list in your Web application’s Web.config file.


How do you get a User Identity?
Once a user is authenticated and authorized, your application can get information about the user by using the User object’s Identity property. The Identity property returns an object that includes the user name and role information, as shown in the following code:private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text = User.Identity.IsAuthenticated.ToString();
Label2.Text = User.Identity.Name;
Label3.Text = User.Identity.AuthenticationType;
}

How do you determine, what is the role of the current user? 
The User object provides an IsInRole method to determine the role of the current user, as shown in the following example:
if(User.IsInRole("Administrators"))
{
// Do something.
}

Can you specify authorization settings both in Web.config and in IIS? 
Yes, you can specify authorization settings both in Web.config and in IIS. The IIS setting is evaluated first and then the setting in Web.config is evaluated. In general, this means that the most restrictive setting will be used.


What is the user account under which an ASP.NET web application runs by default?
Web application runs under the identity of the ASPNET user account by default.

How can you set the web application to run under a specific user’s account? 
You can set the application to run under a specific user’s account by setting the application’s identity element to enable impersonation


How can you see the impersonated identity under which code is executing?
To see the impersonated identity under which code is executing, use the WindowsIdentity class’s GetCurrent method, as shown in the sample code below
Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name); 

The identity element can be used with any type of authentication; however, it is most useful with Windows authentication because Windows authentication users have accounts with specific permissions.

ASP.NET Forms Authentication related interview questions


What is the advantage of using Forms authentication?

The advantage of using Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Another advantage is that many Web applications, particularly commercial sites where customers order products, want to have access to user information. Forms authentication makes these types of applications easier to create.

List the steps to use Forms authentication in a web application?
1.Set the authentication mode in Web.config to Forms.
2.Create a Web form to collect logon information.
3.Create a file or database to store user names and passwords.
4.Write code to add new users to the user file or database.
5.Write code to authenticate users against the user file or database.

What happens when someone accesses a Web application that uses Forms authentication?
When someone accesses a Web application that uses Forms authentication, ASP.NET displays the logon Web form specified in Web.config. Once a user is authorized, ASP.NET issues an authorization certificate in the form of a cookie that persists for an amount of time specified by the authentication settings in Web.config.

What is the difference between Windows authentication and Forms authentication?
The difference between Windows authentication and Forms authentication is that in Forms authentication your application performs all the authentication and authorization tasks. You must create Web forms and write code to collect user names and passwords and to check those items against a list of authorized users.

What is the use of mode attribute in authentication element in a web.config file?
You use the mode attribute to specify the type of authentication your web application is using. Set the mode attribute to forms to enable Forms authentication.

What is the use of name attribute and loginUrl attribute of a forms element in a web.config file?
Name attribute of forms element is used to set the name of the cookie in which to store the user’s credential. The default is .authaspx. If more than one application on the server is using Forms authentication, you need to specify a unique cookie name for each application.
loginUrl attribute of forms element is used to set the name of the Web form to display if the user has not already been authenticated. If omitted, the default is Default.aspx.

What is protection attribute in a forms element used for in web.config file?
The protection attribute of a forms element of web.config file is used for setting how ASP.NET protects the authentication cookie stored on the user’s machine. The default is All, which performs encryption and data validation. Other possible settings areEncryption, Validation, and None.

What is timeout attribute in a forms element used for in web.config file?
Timeout attribute is used to set the number of minutes the authentication cookie persists on the user’s machine. The default is 30, indicating 30 minutes. ASP.NET renews the cookie automatically if it receives a request from the user and more than half of the allotted time has expired.

In which namespace the FormsAuthentication class is present?
System.Web.Security namespace

Which method checks the user name and password against the user list found in the credentials element of Web.config?
The FormsAuthentication class’s Authenticate method checks the user name and password against the user list found in the credentials element of Web.config.

Which method can be used to remove forms authentication cookie?
Use the signout() method of FormsAuthentication class to sign out when the user has finished with the application or when you want to remove the authentication cookie from his or her machine. For example, the following code ends the user’s access to an application and requires him or her to sign back in to regain access
FormsAuthentication.SignOut();

What is the advantage of Authenticating Users with a Database?
You can authenticate users based on a list in Web.config. The FormsAuthentication class’s Authenticate method is set up to read from web.config file automatically. That’s fine if user names and passwords are created and maintained by a system administrator, but if you allow users to create their own user names or change their passwords, you’ll need to store that information outside the Web.config file. This is because changing Web.config at run time causes the Web application to restart, which resets any Application state and Session state variables used by the application.

What are the advantages of storing user names and passwords in a database rather than a file?
You can store user names and passwords in any type of file; however, using a database has the following significant advantages:
1. User names can be used as primary keys to store other information about the user.
2. Databases can provide high performance for accessing user names and passwords.
3. Adding, modifying, and accessing records are standardized through SQL.

Can you encrypt user names and passwords stored in a file or a database?
Yes, you encrypt user names and passwords stored in a file or a database. You can encrypt them using the FormsAuthentication class’s HashPasswordForStoringInConfigFile method. This method uses the SHA1 or MD5 algorithms to encrypt data, as shown below:
Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");

Can you change authentication type in a subfolder's web.config file?
Authentication type (Windows, Forms, or Passport) can be set only at the application’s root folder. To change authentication type in a subfolder's web.config file, you must create a new Web application project and application starting point for that subfolder.

How can you control access to subfolders in a web application?
The authorization settings in the Web.config file apply hierarchically within the folder structure of a Web application. For instance, you might want to allow all users access to the root folder of a Web application but restrict access to Web forms (and tasks) available from a subfolder. To do this, set the authentication type in the root folder’s Web.config file, and then use the authorization element in the subfolder’s Web.config file to restrict access.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.