Wednesday, December 22, 2010

ASP.Net Interview Questions

Globalization -

What is Globalization?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. This process involves translating the user interface elements of an application into multiple languages, using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.

The Microsoft .NET Framework simplifies localization tasks substantially by making its formatting, date/time, sorting, and other classes culturally aware. Using classes from the System.Globalization namespace, you can set the application’s current culture, and much of the work is done automatically!

What are the 3 different ways to globalize web applications?

Detect and redirect approach :
In this approach we create a separate Web application for each supported culture, and then detect the user’s culture and redirect the request to the appropriate application. This approach is best for applications with lots of text content that requires translation and few executable components.

Run-time adjustment approach : In this approach we create a single Web application that detects the user’s culture and adjusts output at run time using format specifiers and other tools. This approach is best for simple applications that present limited amounts of content.

Satellite assemblies approach : In this approach we create a single Web application that stores culture-dependent strings in resource files that are compiled into satellite assemblies. At run time, detect the user’s culture and load strings from the appropriate assembly. This approach is best for applications that generate content at run time or that have large executable components.

In ASP.NET, how do you detect the user's language preference on his/her computer?
Use the Request object’s UserLanguages property to return a list of the user’s language preferences. The first element of the array returned by UserLanguages is the user’s current language on his/her computer.

What are the steps to follow to get user's culture at run time?
To get the user’s culture at run time, follow these steps:
1. Get the Request object’s UserLanguages property.
2. Use the returned value with the CultureInfo class to create an object representing the user’s current culture.

For example, the following code gets the user’s culture and displays the English name and the abbreviated name of the culture in a label the first time the page is displayed:
private void Page_Load(object sender, System.EventArgs e)
{
// Run the first time the page is displayed
if (!IsPostBack)
{
// Get the user's preferred language.
string sLang = Request.UserLanguages[0];
// Create a CultureInfo object from it.
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + ": " +
CurrentCulture.Name;
}
}

What are the advantages of using detect and redirect approach to globalizing web applications?
1. Content is maintained separately, so this approach allows the different applications to present very different information, if needed.
2. Users can be automatically directed to sites that are likely to be geographically close, and so can better meet their needs.
3. Content files (Web forms and HTML pages, for example) can be authored in the appropriate natural language without the complexity of including resource strings.

What are the disadvantages of using detect and redirect approach to globalizing web applications?
1. Using this approach requires that the executable portion of the Web application be compiled and deployed separately to each culture-specific Web site.
2. This approach requires more effort to maintain consistency and to debug problems across Web sites.

What is the use of culture attribute of the globalization element in web.config?
The Web.config file’s globalization element is used to create a culture-specific Web application. The culture attribute of the globalization element specifies how the Web application deals with various culture-dependent issues, such as dates, currency, and number formatting.

Web.config globalization settings in subordinate folders override the globalization settings in the application’s root Web.config file. You can store content for various cultures in subfolders within your application, add Web.config files with the globalization settings for each culture, then direct users to the appropriate folder based on the user’s CurrentCulture.

The text on the webform is usually written from left to right. How do you change the writing direction to "right to left"?
The wrting direction of a webform can be changed using the HTML dir attribute as shown below.


You can use the dir attribute individually in panels, text boxes, or other controls as well. Setting the dir attribute on the body element applies right-to-left formatting to the entire page.

What do you mean by neutral cultures?
Neutral cultures represent general languages, such as English or Spanish, rather than a specific language and region. When you set the culture attribute for a Web application in Web.config, ASP.NET assigns that culture to all the threads running for that Web application. Threads are the basic unit to which the server allocates processor time. ASP.NET maintains multiple threads for a Web application within the aspnet_wp.exe worker process.

What are advantages of setting the culture dynamically at the thread level over creating separate Web applications for each culture?
1. All cultures share the same application code, so the application doesn’t have to be compiled and deployed for each culture.
2. The application resides at a single Web address, you don’t need to redirect users to other Web applications.
3. The user can choose from a full array of available cultures.

For what type of web applications setting the culture dynamically is best suited?
Setting the culture dynamically is best suited for simple Web applications that don’t contain large amounts of text that must be translated into different languages.




DataSet-

What is a DataSet?
DataSet is an in-memory cache of data.

In which namespace is the DataSet class present?
System.Data

Can you add more than one table to a dataset?
Yes

Can you enforce constarints and relations on tables inside a DataSet?
Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.

What happens when you invoke AcceptChanges() method on a DataSet?
Invoking AcceptChanges() method on the DataSet causes AcceptChanges() method to be called on each table within the DataSet.

Both the DataRow and DataTable classes also have AcceptChanges() methods. Calling AcceptChanges() at the DataTable level causes the AcceptChanges method for each DataRow to be called.

When you call AcceptChanges on the DataSet, any DataRow objects still in edit-mode end their edits successfully. The RowState property of each DataRow also changes. Added and Modified rows become Unchanged, and Deleted rows are removed.

If the DataSet contains ForeignKeyConstraint objects, invoking the AcceptChanges method also causes the AcceptRejectRule to be enforced.

Is there a way to clear all the rows from all the tables in a DataSet at once?
Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.

What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.

DataSet.Copy() copies both the structure and data.

How do you get a copy of the DataSet containing all changes made to it since it was last loaded?
Use DataSet.GetChanges() method

What is the use of DataSet.HasChanges() Method?
DataSet.HasChanges method returns a boolean true if there are any changes made to the DataSet, including new, deleted, or modified rows. This method can be used to update a DataSource only if there are any changes.

How do you roll back all the changes made to a DataSet since it was created? Invoke the DataSet.RejectChanges() method to undo or roll back all the changes made to a DataSet since it was created.

What happnes when you invoke RejectChanges method, on a DataSet that contains 3 tables in it?
RejectChanges() method will be automatically invoked on all the 3 tables in the dataset and any changes that were done will be rolled back for all the 3 tables.

When the DataTable.RejectChanges method is called, any rows that are still in edit-mode cancel their edits. New rows are removed. Modified and deleted rows return back to their original state. The DataRowState for all the modified and deleted rows will be flipped back to unchanged.

What is the DataSet.CaseSensitive property used for?
When you set the CaseSensitive property of a DataSet to true, string comparisons for all the DataTables within dataset will be case sensitive. By default the CaseSensitive property is false



HTTP Modules and HTTP Handlers -

What is an HTTP Handler?
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

What is HTTP module?
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

What is the interface that you have to implement if you have to create a Custom HTTP Handler?
Implement IHttpHandler interface to create a synchronous handler.
Implement IHttpAsyncHandler to create an asynchronous handler.

What is the difference between asynchronous and synchronous HTTP Handlers?
A synchronous handler does not return until it finishes processing the HTTP request for which it is called.

An asynchronous handler runs a process independently of sending a response to the user. Asynchronous handlers are useful when you must start an application process that might be lengthy and the user does not have to wait until it finishes before receiving a response from the server.

Which class is responsible for receiving and forwarding a request to the appropriate HTTP handler?
IHttpHandlerFactory Class

Can you create your own custom HTTP handler factory class?
Yes, we can create a custom HTTP handler factory class by creating a class that implements the IHttpHandlerFactory interface.

What is the use of HTTP modules?
HTTP modules are used to implement various application features, such as forms authentication, caching, session state, and client script services.

What is the difference between HTTP modules and HTTP handlers?
An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.

What is the common way to register an HTTP module?
The common way to register an HTTP module is to have an entry in the application's Web.config file.

Much of the functionality of a module can be implemented in a global.asax file. When do you create an HTTP module over using Global.asax File?
You create an HTTP module over using Global.asax file if the following conditions are true

1. You want to re-use the module in other applications.
2. You want to avoid putting complex code in the Global.asax file.
3. The module applies to all requests in the pipeline.


Data Access Security-

What are the best practices to follow to secure connection strings in an ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.

Why is "Connecting to SQL Server using Integrated Security" considered a best practice?
Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.

What is the advantage of storing an XML file in the applications App_Data folder? The contents of the App_Data folder will not be returned in response to direct HTTP requests.

What is Script injection?
A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code.

What is SQL injection?
A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of, or in addition to, the commands that you have built into your application.

What are the best practices to keep in mind when accepting user input on a web application?
1.
Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even if the client has by passed the client side validation by disabling javascript in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application.

What are the steps to follow to avoid Script Injection attacks?
1.
Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView control to encode user input when the row is in edit mode.

What are the steps to follow to avoid SQL Injection attacks?
Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings together.

Can you encrypt view state data of an aspx page?
Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.

Master Pages-

What are Master Pages in ASP.NET? or What is a Master Page?
ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.

What are the 2 important parts of a master page?
The following are the 2 important parts of a master page
1. The Master Page itself
2. One or more Content Pages

Can Master Pages be nested?
Yes, Master Pages be nested.

What is the file extension for a Master Page?
.master

How do you identify a Master Page?
The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages.

Can a Master Page have more than one ContentPlaceHolder?
Yes, a Master Page can have more than one ContentPlaceHolder

What is a ContentPlaceHolder?
ContentPlaceHolder is a region where replaceable content will appear.

How do you bind a Content Page to a Master Page?
MasterPageFile attribute of a content page's @ Page directive is used to bind a Content Page to a Master Page.

Can the content page contain any other markup outside of the Content control?
No.

What are the advantages of using Master Pages?
1. They allow you to centralize the common functionality of your pages so that you can make updates in just one place.
2. They make it easy to create one set of controls and code and apply the results to a set of pages. For example, you can use controls on the master page to create a menu that applies to all pages.
3. They give you fine-grained control over the layout of the final page by allowing you to control how the placeholder controls are rendered.
4. They provide an object model that allows you to customize the master page from individual content pages.

What are the 3 levels at which content pages can be attached to Master Page?
At the page level - You can use a page directive in each content page to bind it to a master page

At the application level - By making a setting in the pages element of the application's configuration file (Web.config), you can specify that all ASP.NET pages (.aspx files) in the application automatically bind to a master page.

At the folder level - This strategy is like binding at the application level, except that you make the setting in a Web.config file in one folder only. The master-page bindings then apply to the ASP.NET pages in that folder.

What is @MasterType directive used for?
@MasterType directive is used to create a strongly typed reference to the master page.

Are controls on the master page accessible to content page code?
Yes, controls on the master page are accessible to content page code.

At what stage of page processing master page and content page are merged?
During the initialization stage of page processing, master page and content page are merged.

Can you dynaimically assign a Master Page?
Yes, you can assign a master page dynamically during the PreInit stage using the Page class MasterPageFile property as shown in the code sample below.
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/MasterPage.master";
}

Can you access non public properties and non public methods of a master page inside a content page?
No, the properties and methods of a master page must be public in order to access them on the content page.

From the content page code how can you reference a control on the master page?
Use the FindControl() method as shown in the code sample below.
void Page_Load()
{
// Gets a reference to a TextBox control inside
// a ContentPlaceHolder
ContentPlaceHolder ContPlaceHldr = (ContentPlaceHolder)Master.FindControl ("ContentPlaceHolder1");
if(ContPlaceHldr != null)
{
TextBox TxtBox = (TextBox)ContPlaceHldr.FindControl("TextBox1");
if(TxtBox != null)
{
TxtBox.Text = "TextBox Present!";
}
}
// Gets a reference to a Label control that not in
// a ContentPlaceHolder
Label Lbl = (Label)Master.FindControl("Label1");
if(Lbl != null)
{
Lbl.Text = "Lable Present";
}
}

Can you access controls on the Master Page without using FindControl() method?
Yes, by casting the Master to your MasterPage as shown in the below code sample.
protected void Page_Load(object sender, EventArgs e)
{
MyMasterPage MMP = this.Master;
MMP.MyTextBox.Text = "Text Box Found";
}


Passport Authentication-

What is Passport Authentication?
Passport authentication identifies users via Microsoft Passport’s single sign-on service. Microsoft Passport is meant to provide Internet users with a single identity that they can use to visit a wide variety of Web sites that require authentication. Information about the user is available to your application through a profile that is stored with Microsoft.

What are the advantages of Passport authentication?
The advantages of Passport authentication are that the user doesn’t have to remember separate user names and passwords for various Web sites and that the user can maintain his or her profile information in a single location. Passport authentication also provides access to other Microsoft services, such as Passport Express Purchase.

What is passport software development kit (passport SDK)?
To use Passport authentication in your Web application, you must install the Passport SDK. The Passport SDK is free for preproduction development and testing. To deploy a site for public use, you must obtain an annual license from Microsoft.

How does Passport authentication work?
When a user accesses an application that implements Passport authentication, ASP.NET checks the user’s machine for a current passport authentication cookie. If none is found, ASP.NET directs the user to a Passport sign-on page. Once the user signs in, the Passport service authenticates the user, stores an authentication cookie on the user’s computer, and directs the user back to the originally requested Web page.

What are the steps to follow to use Passport authentication?
1. Install the Passport SDK. Passport is not included with Visual Studio, although the .NET Framework does include classes for working with the Passport SDK once it is installed.
2. Set the application’s authentication mode to Passport in Web.config. Set authorization to deny unauthenticated users.
3. Use the PassportAuthentication_OnAuthenticate event to access the user’s Passport profile to identify and authorize the user.
4. Implement a sign-out procedure to remove Passport cookies from the user’s machine.

Where is PassportAuthentication_OnAuthenticate event present?
PassportAuthentication_OnAuthenticate event is present in Global.asax.


Forms Authentication-

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 are Encryption, 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.



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.


ADO.Net-

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.

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.


Themes and Skins-

What is a "theme" in ASP.NET?
A "theme" is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server.

What is the extension for a skin file?
.skin

What are the 2 types of control skins in ASP.NET?
1.
Default skins
2. Named skins

What is the difference between Named skins and Default skins?
A default skin automatically applies to all controls of the same type when a theme is applied to a page. A control skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.)

A named skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows you to set different skins for different instances of the same control in an application.

What are the 3 levels at which a theme can be applied for a web application?
1
. At the page level - Use the Theme or StyleSheetTheme attribute of the @ Page directive.

2. At the application level - Can be applied to all pages in an application by setting the element in the application configuration file.

3. At the web server level - Define the element in machine.config file. This will apply the theme to all the web applications on that web server.

What is the name of the folder that contains the application themes?
App_Themes

What is a global theme?
A global theme is a theme that you can apply to all the Web sites on a server. Global themes allow you to define an overall look for your domain when you maintain multiple Web sites on the same server.

What is the difference between themes and CSS?
1. Themes can define many properties of a control or page, not just style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.

2. Themes can include graphics.

3. Themes do not cascade the way style sheets do. By default, any property values defined in a theme referenced by a page's Theme property override the property values declaratively set on a control, unless you explicitly apply the theme using the StyleSheetTheme property.

4. Only one theme can be applied to each page. You cannot apply multiple themes to a page, unlike style sheets where multiple style sheets can be applied.

What are the security concerns to keep in mind when using themes?
Themes can cause security issues when they are used on your Web site. Malicious themes can be used to:

1. Alter a control's behavior so that it does not behave as expected.

2. Inject client-side script, therefore posing a cross-site scripting risk.

3. Expose sensitive information.

4. The mitigations for these common threats are:

5. Protect the global and application theme directories with proper access control settings. Only trusted users should be allowed to write files to the theme directories.

6. Do not use themes from an untrusted source. Always examine any themes from outside your organization for malicious code before using them on you Web site.

7. Do not expose the theme name in query data. Malicious users could use this information to use themes that are unknown to the developer and thereby expose sensitive information.



Arrays-

What is the difference between arrays in C# and arrays in other programming languages?
Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences as listed below

1. When declaring an array in C#, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.

int[] IntegerArray; // not int IntegerArray[];

2.
Another difference is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.

int[] IntegerArray; // declare IntegerArray as an int array of any size
IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array

What are the 3 different types of arrays that we have in C#?
1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays

Are arrays in C# value types or reference types?
Reference types.

What is the base class for all arrays in C#?
System.Array

How do you sort an array in C#?
The Sort static method of the Array class can be used to sort array items.

Give an example to print the numbers in the array in descending order?
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}

What property of an array object can be used to get the total number of elements in an array?
Length property of array object gives you the total number of elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}

Give an example to show how to copy one array into another array?
We can use CopyTo() method to copy one array into another array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}


Caching-



What is caching?
High-performance Web applications should be designed with caching in mind. Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching is important to Web applications because each time a Web form is requested, the host server must process the Web form’s HTML and run Web form code to create a response. By caching the response, all that work is bypassed. Instead, the request is served from the reponse already stored in memory.

Caching an item incurs considerable overhead, so it’s important to choose the items to cache wisely. A Web form is a good candidate for caching if it is frequently used and does not contain data that frequently changes. By storing a Web form in memory, you are effectively freezing that form’s server-side content so that changes to that content do not appear until the cache is refreshed.

What directive is used to cache a web form?
The @OutputCache page directive is used to cache a Web form in the server’s memory.

What is the use of duration attribute of @OutputCache page directive?
The @OutputCache directive’s Duration attribute controls how long the page is cached. For example if you set the duration attribute to 60 seconds, the Web form is cached for 60 seconds.

The first time any user requests the Web form, the server loads the response in memory and retains that response for 60 seconds. Any subsequent requests during that time receive the cached response.

After the cache duration has expired, the next request for the Web form generates a new response, which is then cached for another 60 seconds. Thus the server processes the Web form once every 60 seconds at most.

What are the 2 required attributes of the @OutputCache directive?
The @OutputCache directive has two required attributes:
1.
Duration
2.
VaryByParam.
How do you cache multiple responses from a single Web form?
The VaryByParam attribute lets you cache multiple responses from a single Web form based on varying HTTP POST or query string parameters. Setting VaryByParam to None caches only one response for the Web form, regardless of the parameters sent.

You can also cache multiple responses from a single Web form using the VaryByHeaders or VaryByCustom attribute.

The VaryByCustom attribute lets you cache different responses based on a custom string. To use VaryByCustom, override the GetVaryByCustomString method in the Web application’s Global.asax file.

Is it possible to cache a web form without using @OutputCache directive?
Yes, you can cache a web form using the Response object’s Cache property, which returns an HttpCachePolicy object for the response. The HttpCachePolicy object provides members that are similar to the OutputCache directive’s attributes.

Give a simple example to show how to cache a web form without using @OutputCache directive?
For example, the following code caches the Web form’s response for 60 seconds:
private void Page_Load(object sender, System.EventArgs e)
{
// Cache this page
DateTimeLabel.Text = System.DateTime.Now.ToString();
// Set OutputCache Duration. Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(60));
// Set OutputCache VaryByParams.
Response.Cache.VaryByParams["None"] = true;
// Set OutputCache Location.
Response.Cache.SetCacheability(HttpCacheability.Public);
}

The preceding code is equivalent to the following OutputCache directive:
@ OutputCache Duration="5" VaryByParam="None" Location="Any"

What is @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property used for?
The @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property determine where Microsoft ASP.NET stores cached responses. By default, ASP.NET caches responses at any available location that accepts cache items - the client, proxy servers, or the host server. In practice, those locations might or might not allow caching, so you can think of the Location/SetCacheability setting as more of a request than a command.

What is HttpCachePolicy object’s SetAllowResponseInBrowserHistory method used for?
You can override the cache location settings using the HttpCachePolicy object’s SetAllowResponseInBrowserHistory method. Setting that method to True allows the response to be stored in the client’s history folder even if the location setting is None or Server.


Which object can used to store frequently used items in the server’s memory for quick retrieval?
Cache object can be used to store frequently used items in the server’s memory for quick retrieval.

Is the cache object available for all web forms with in a web application?
Yes, the Cache object is global, that is, data stored in the Cache object is available anywhere within a Web application. In this way, the Cache object is very similar to the intrinsic Application object.

What are the 3 different ways to store data in the Cache object?
Use assignment.
Assigning a value to an unused key in the Cache object automatically creates that key and assigns the value to that key. Assigning a value to a key that already exists replaces the cached value with the assigned value.
Use the Insert method.
The Insert method uses parameters rather than assignment to create or change cached data. Insert optionally accepts parameters to establish dependencies and set expiration policy.
Use the Add method.
The Add method is similar to Insert; however, it requires all parameters and returns an object reference to the cached data.

For example, the following Cache statements all add the same item to the cache:

using System.Web.Caching;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)

{
Cache["NewItem"] = "Some string data";
Cache.Add("NewItem", "Some string data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, null);
Cache.Insert("NewItem", "Some string data");
}
}

What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?
absoluteExpiration
A DateTime object that identifies when the data should be removed from the cache. If you’re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.
slidingExpiration
A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you’re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.


Which delegate can be used to notify the application when items are removed from the cache?
onRemoveCallback is used to notify the application when items are removed from the cache.

How do you retrieve the value of a cache item stored in the servers memory?
You can retrieve the value of a cache item stored in the servers memory through the item’s key, just as you do with the Application and Session objects. Because cached items might be removed from memory, you should always check for their existence before attempting to retrieve their value, as shown in the following code:

private void Button1_Click(object sender, EventArgs e)
{
if (Cache["ChachedItem"] == null)
{
Lable1.Text = "Cached Item not found.";
}
else
{
Lable1.Text = Cache["ChachedItem"].ToString();
}
}

Which method can be used to remove data from the cache?
Cache object’s Remove method can be used to remove data from the cache as shown in the following code example / sample.

private void RemoveButton_Click(object sender, System.EventArgs e)
{
Cache.Remove("CachedItem");
}

How do you control how long data is cached?
The Cache object’s Add and Insert method parameters allow you to control how long an item is stored in the server’s memory. In practice, these parameter settings provide only indirect control of how long data remains in memory. If your server runs low on available memory, ASP.NET recovers as much memory as possible from expired cache items. If that’s not enough, ASP.NET will unload unexpired items from the cache based on their priority and when they were last accessed.

What is CacheItemPriority enumeration used for?
CacheItemPriority enumeration is used to set the relative importance of cached items. CacheItemPriority.NotRemoveable has the highest priority and CacheItemPriority.Low has the lowest priority.

Which is the only "event” provided by Cache object?
CacheItemRemoved "event” is the only "event” provided by Cache object.

How do you update the Cache object when data changes?
Items stored in the cache are often copies of data that is stored and maintained elsewhere, such as records in a database. Use the Add and Insert methods’ dependency parameter to establish a relationship between a cached data item and an external source, such as a file, a folder, or a group of files.

The dependency parameter accepts a CacheDependency object, which in turn identifies the file, folder, or set of files to watch for changes. ASP.NET checks the time stamp of the items in the CacheDependency object, if one of those time stamps is later than the DateTime entered for the cached item, ASP.NET unloads that item from the cache.


What is fragment caching?
Caching parts of web form is called as fragment caching. Sometimes you want to cache only part of a Web form response. For instance, a Web form might contain many pieces of variable information plus a single large table that almost never changes. In this case, you might place that table in a Web user control and store the response for that control in cache. This technique is called fragment caching.

What are the steps to follow to cache parts of web form?
To cache part of a Web form, follow these steps:
1. Place the controls and content that you want to cache in a Web user control.
2. Set the caching attributes for that Web user control.
3. Create an instance of the Web user control on the Web form.

What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control’s class declaration to enable fragment caching.

What are the OutputCache directive attributes that apply only to user controls?
Shared
Cache a single response from a user control for use on multiple Web forms. By default, ASP.NET caches a separate response for each Web form that uses a cached user control. This attribute is only available in the .NET Framework version 1.1 or later.

VaryByControl
Cache multiple responses for a single user control based on the value of one or more controls contained in the user control. Can you cache multiple versions of a user control?Yes, You can cache multiple versions of a user control based on the value of controls contained in a user control (VaryByControl) or based on a custom string (VaryByCustom).

If a user control is read from the cache, can you access its members from code?
No, In general, cached controls are used to present data such as queries from a database, rather than as interactive components. However, if you do need to access a cached control from code, you must first check that the control exists. If the control is read from the cache, you can’t access its members from code. Control members are available only when the control is not read from the cache, such as when the control is first instantiated and when it is reloaded after its cache duration has expired.

When caching is set at both the Web form and user control levels, How does the cache settings interact?
The cache location is determined by the Web form setting. Location settings on a user control have no affect.
If the Web form’s cache duration is longer than the user control’s, both the Web form response and the user control response will expire using the Web form setting.


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.


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, a compile time error 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.


Managed and Unmanaged Code-


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.

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.


Tracing-


What is an exception log?
An exception log is a list of handled exceptions that occur while your application is running. Reviewing the exception log periodically helps you verify that exceptions are being handled correctly, are not occurring too frequently, and are not preventing users from accomplishing tasks with your application.

What is Tracing and what are the adavantages of using tracing to log exceptions?
Tracing is a technique for recording events, such as exceptions, in an application. There have always been ways to record errors in an application - usually by opening a file and writing error messages to it. But tracing offers the following significant advantages:
Standardization:Building tracing into the .NET Framework ensures that programming techniques are the same across all the applications you develop with the .NET Framework.
Built-in Web support:ASP.NET extends the .NET Framework tools by including information related to the performance and behavior of Web requests.
Configuration:You can turn tracing on and off using settings in your application’s configuration file. You don’t have to recompile your application to enable or disable tracing.
Performance:While disabled, tracing statements do not affect application performance.

How do you turn tracing on and off for an ASP.NET web application?
Tracing can be turned on or off for an entire Web application or for an individual page in the application:
1. To turn tracing on for an entire application, in the application’s Web.config file, set the trace element’s Enabled attribute to True.
Or
2. To turn tracing on for a single page, set the DOCUMENT object’s Trace property to True in the Visual Studio .NET Properties window. This sets the @ Page directive’s Trace attribute to True in the Web form’s HTML.

Where is the trace output displayed by default?
By default, trace output is displayed at the end of each Web page.

While this is fine for debugging purposes, you’ll generally want to write trace output to a log file when you start testing your completed application. To write trace messages to a log file for an entire application, in the application’s Web.config file, set the trace element’s PageOutput attribute to False. ASP.NET then writes trace output to the Trace.axd file in your application’s root folder.

How do you specify, how many page requets should be written to the trace log?
The element's RequestLimit attribute can be used to specify how many page requests to write to the trace log. For example, the following line from a Web.config file turns on tracing for the application and writes the first 10 requests to the Trace.axd file:

How do you write trace messages to a log file for only selected pages in an application?
To write trace messages to a log file for only selected pages in an application, follow these steps:
In the application’s Web.config file, set the trace element’s Enabled attribute to True and PageOutput attribute to False.
For each Web page you want to exclude from tracing, set the @ Page directive’s Trace attribute to False.

What is the difference between Trace.Write() and Trace.Warn() methods of a trace object?
The Trace object provides the Write and Warn methods to allow you to write messages to a request’s trace information. The two methods are identical with one difference: messages written with Trace.Write are displayed in black, whereas messages written with Trace.Warn are displayed in red.

How do you programatically check if tracing is enabled?
The Trace object’s IsEnabled property can be used to programatically check if tracing is enabled.

How do you prevent from trace output being written at the bottom of the web page?
You can prevent from trace output being written at the bottom of the web page by setting the trace element’s PageOutput attribute to False in the Web.config file.

What is the name of the file to which trace log is written?
Trace.axd

Can you view Trace.axd from a remote machine?
No, by default, you can view Trace.axd only from the local server running the application. If you want to view the trace log from a remote machine, set the trace element’s LocalOnly attribute to False in the Web.config file


Session State and Application State-


What is a Session?
A Session is a unique instance of the browser. A single user can have multiple instances of the browser running on his or her machine. If each instance visits your Web application, each instance has a unique session.A session starts when a user accesses a page on a Web site for the first time, at which time they are assigned a unique session ID. The server stores the user's session ID in the Session.SessionID property.

What is the default session timeout period?
20 minutes.

Where do you generally specify the Session Timeout?
You specify the Session Timeout setting in the web.config file.

Can you specify Session Timeout in a code behind file?
Yes, can specify the Session.Timeout property as shown below in a code behind file.
Session.Timeout = 10;

How do you end a user session?
You can call the Session.Abandon() method to end a user session. If a user then tries to access a page the server will assign them a new session ID and it will clear all the previous session variables. You'll typically use Session.Abandon() on log-out pages.

What type of data can you store in Application State and Session State variables?
Application State and Session State variables are used to store data that you want to keep for the lifetime of an application or for the lifetime of a session. You can store any type of data in the Application or Session state, including objects.

Are Application State or Session State variables type safe?
No, Application and Session state variables are created on the fly, without variable name or type checking.

Do maintaining Session state affects performance?
Yes

Can you turn of Session state?
Yes, Session state can be turned off at the application and page levels.

Are Application state variables available throughout the current process?
Yes, Application state variables are available throughout the current process, but not across processes. If an application is scaled to run on multiple servers or on multiple processors within a server, each process has its own Application state.

How do you disable Session state for a Web form?
To turn Session state off for a Web form set EnableSessionState property of the Page to False.

How do you turn Session state off for an entire web application?
In the Web.config file, set the sessionstate tag to False.

What are Application State variables?
Application State variables are global variables that are available from anywhere in the application. All Sessions can access Application State variables.

How to add and remove data to Application State Variables?
//Code to add data to Application State
Application.Add("AppName", "Sample");

//Code to remove data from Application State
Application.Remove("AppName");

How do you remove all Application State Variables data?
//Code to remove all Application State Variables data
Application.RemoveAll();


Transaction-


What is a transaction?
A transaction is a group of commands that change the data stored in a database. The transaction, which is treated as a single unit, assures that the commands are handled in an all-or-nothing fashion. if one of the commands fails, all of the commands fail, and any data that was written to the database by the commands is backed out. In this way, transactions maintain the integrity of data in a database. ADO.NET lets you group database operations into transactions.

What is the main purpose of database transactions?
The main purpose of database transactions is to maintain the integrity of data in a database.

How do you determine which SQL commands are part of a transaction?
You can determine what database commands belong in a transaction by using the ACID test. Commands must be atomic, consistent, isolated, and durable.

Commands belong in a transaction if they are:
Atomic:In other words, they make up a single unit of work. For example, if a customer moves, you want your data entry operator to change all of the customer’s address fields as a single unit, rather than changing street, then city, then state, and so on.
Consistent:All the relationships between data in a database are maintained correctly. For example, if customer information uses a tax rate from a state tax table, the state entered for the customer must exist in the state tax table. Isolated:Changes made by other clients can’t affect the current changes. For example, if two data entry operators try to make a change to the same customer at the same time, one of two things occurs: either one operator’s changes are accepted and the other is notified that the changes weren’t made, or both operators are notified that their changes were not made. In either case, the customer data is not left in an indeterminate state.
Durable:Once a change is made, it is permanent. If a system error or power failure occurs before a set of commands is complete, those commands are undone and the data is restored to its original state once the system begins running again.

Why is transaction processing very important for web applications?
Transaction processing is very important for Web applications that use data access, because Web applications are distributed among many different clients. In a Web application, databases are a shared resource, and having many different clients distributed over a wide area can present the below key problems.
Contention for resources:Several clients might try to change the same record at the same time. This problem gets worse the more clients you have.
Unexpected failures:The Internet is not the most reliable network around, even if your Web application and Web server are 100 percent reliable. Clients can be unexpectedly disconnected by their service providers, by their modems, or by power failures.
Web application life cycle:Web applications don’t follow the same life cycle as Windows applications—Web forms live for only an instant, and a client can leave your application at any point by simply typing a new address in his or her browser.

List the steps in order to process a transaction?
1.Begin a transaction.
2.Process database commands.
3.Check for errors.
4.If errors occurred, restore the database to its state at the beginning of the transaction. If no errors occurred, commit the transaction to the database.

Explain how a DataSet provides transaction processing?
DataSet provide transaction processing through the RejectChanges and Update methods. DataSet also provide an AcceptChanges method that resets the state of records in a data set to Unchanged. Data sets provide implicit transaction processing, because changes to a data set are not made in the database until you invoke the Update method on the data adapter object. This lets you perform a set of commands on the data and then choose a point at which to make the changes permanent in the database.

If an error occurs during the Update method, none of the changes from the data set is made in the database. At that point, you can either attempt to correct the error and try the Update method again or undo the changes pending in the data set using the data set’s RejectChanges method.

Give an example to show how DataSets provide transaction processing?
Let us assume we have a DataGrid that displays employee information. Every row also has a delete button, which when you click will delete that row. On this page we also have a Restore and Commit buttons. When you click the Restore button you should be able to restore the data to its previous state. When you click the Commit button you should be able to update the database with the deletions made in the DataSet.


The code for Commit and Restore buttons is shown below.
private void butRestore_Click(object sender, System.EventArgs e)
{
// Restore the data set to its original state.
dsContacts.RejectChanges();
// Refresh the data grid.
grdContacts.DataBind();
}

private void butCommit_Click(object sender, System.EventArgs e)
{
int intRows;
// Update the database from the data set.
intRows = adptContacts.Update(dsContacts);
// Save changes to state variable.
Session["dsContacts"] = dsContacts;
// Refresh the data grid.
grdContacts.DataBind();
}
The RejectChanges method in the preceding butRestore_Click event procedure returns the data set to its state before the row was deleted. The data set’s AcceptChanges method is the inverse of RejectChanges—it resets the DataRowState property for all the changed rows in a data set to Unchanged and removes any deleted rows.

The AcceptChanges method prevents the Update method from making those changes in the database, however, because Update uses the rows’ DataRowState property to determine which rows to modify in the database. For this reason, the AcceptChanges method is useful only when you do not intend to update a database from the data set.

What are the 3 types of transaction objects available in ADO.NET?
As we have 3 types of database connections in ADO.NET, there are also 3 types of transaction objects:
SqlTransaction
OracleTransaction
OleDbTransaction

What are the steps involved in using a transaction object in ADO.NET?
1.Open a database connection.
2.Create the transaction object using the database connection object’s BeginTransaction method.
3.Create command objects to track with this transaction, assigning the Transaction property of each command object to the name of the transaction object created in step 2.
4.Execute the commands. Because the purpose of transaction processing is to detect and correct errors before data is written to the database, this is usually done as part of an error-handling structure.
5.Commit the changes to the database or restore the database state, depending on the success of the commands.
Close the database connection.

What property of a transaction object determines how concurrent changes to a database are handled?
IsolationLevel property of the transaction object is used to determine how concurrent changes to a database are handled.

What are different isolation levels of a transaction object in ADO.NET?
ReadUncommitted:
Does not lock the records being read. This means that an uncommitted change can be read and then rolled back by another client, resulting in a local copy of a record that is not consistent with what is stored in the database. This is called a dirty read because the data is inconsistent.
Chaos:Behaves the same way as ReadUncommitted, but checks the isolation level of other pending transactions during a write operation so that transactions with more restrictive isolation levels are not overwritten.
ReadCommitted:Locks the records being read and immediately frees the lock as soon as the records have been read. This prevents any changes from being read before they are committed, but it does not prevent records from being added, deleted, or changed by other clients during the transaction. This is the default isolation level.
RepeatableRead:Locks the records being read and keeps the lock until the transaction completes. This ensures that the data being read does not change during the transaction.
Serializable:Locks the entire data set being read and keeps the lock until the transaction completes. This ensures that the data and its order within the database do not change during the transaction.

What is the default isolation level in a transaction?
ReadCommitted

What is a Save Point in a transaction in ADO.NET?
SqlConnection object provide one transaction capability that is unavailable for OLE database connections: the ability to create save points within a transaction. Save points let you restore the database state to a specific position within the current transaction. To set a save point within a SQL transaction, use the Save method as shown below.
TransactionObject.Save("FirstStep");

How do you restore a SQL transaction to a specific save point?
To restore a SQL transaction to a save point, specify the name of the save point in the Rollback method as shown below.
TransactionObject.Rollback("FirstStep");


User Controls-


What are ASP.NET Custom controls?
Custom controls extend the tools available to Web developers. Using custom controls, you can encapsulate key aspects of the visual interface and program logic that you want to reuse throughout your application, or throughout your organization.

What are the 3 types of custom controls in ASP.NET?
Microsoft Visual Studio .NET provides three types of custom control for use on Web forms.
1. Web user controls
These combine existing server and HTML controls by using the Visual Studio .NET Designer to create functional units that encapsulate some aspect of the user interface. User controls reside in content files, which must be included in the project in which the controls are used.
2. Composite custom controls
These create new controls from existing server and HTML controls. Although similar to user controls, composite controls are created in code rather than visually, and therefore they can be compiled into an assembly (.dll), which can be shared between multiple applications and used from the Toolbox in Visual Studio .NET.
3. Rendered custom controls
These create entirely new controls by rendering HTML directly rather than using composition. These controls are compiled and can be used from the Toolbox, just like composite controls, but you must write extra code to handle tasks that are performed automatically in composite controls.

What are the limitations of user controls in ASP.NET?
As the user controls are not compiled into assemblies, they have the following limitations:
1. A copy of the control must exist in each Web application project in which the control is used.
2. User controls can’t be loaded in the Visual Studio .NET Toolbox; instead, you must create them by dragging the control from Solution Explorer to the Web form.
3. User control code is initialized after the Web form loads, which means that user control property values are not updated until after the Web form’s Load event.

What are the steps to follow for creating and using a user control in a Web application?
1. Add a Web user control page (.ascx) to your project.
2. Draw the visual interface of the control in the designer.
3. Write code to create the control’s properties, methods, and events.
4. Use the control on a Web form by dragging it from Solution Explorer to the Web form on which you want to include it.
5. Use the control from a Web form’s code by declaring the control at the module level and then using the control’s methods, properties, and events as needed within the Web form.

How do you identify user controls?
User controls are identified by their .ascx file extensions.

What is the base class from which user controls derive?
User controls derive from System.Web.UI.UserControl base class. This base class provides the base set of properties and methods you use to create the control.

What are the steps to follow to create properties and methods for the user control that you can use from a Web form?
To create properties and methods for the user control that you can use from a Web form, follow these steps:
1. Create the public property or method that you want to make available on the containing Web form.
2. Write code to respond to events that occur for the controls contained within the user control. These event procedures do the bulk of the work for the user control.
3. If the property or method needs to retain a setting between page displays, write code to save and restore settings from the control’s ViewState.

What happens when you drag a user control from solution explorer and drop it on a web form?
When you drag a user control from solution explorer and drop it on a web form, Visual Studio .NET generates a @Register directive and HTML tags to create the control on the Web form.


Custom Controls-


What are composite custom controls?
Composite custom controls combine one or more server or HTML controls within a single control class, which can be compiled along with other control classes to create an assembly (.dll) that contains a custom control library. Once created, the custom control library can be loaded into Visual Studio .NET and used in the same way as the standard server and HTML controls.

Composite custom controls are functionally similar to user controls, but they reside in their own assemblies, so you can share the same control among multiple projects without having to copy the control to each project, as you must do with user controls. However, composite controls are somewhat more difficult to create because you can’t draw them visually using the Visual Studio .NET Designer.

What are the steps to follow create and use a custom control in a Web application?
1. Create a solution containing a custom control project.
2. Add a Web application project to the solution, and set it as the startup project. You will use the Web application project to test the custom control during development.
3. Add a project reference from the Web application to the custom control project, and add an HTML @Register directive and control element to use the custom control on a Web form.
4. Create the custom control’s visual interface by adding existing controls to it through the custom control’s CreateChildControls method.
5. Add the properties, methods, and events that the custom control provides.
6. Build and test the custom control.

In general what is the base class for every composite custom control?
System.Web.UI.WebControls.WebControl

Which directive is used to add a custom control to a Web form?
Register directive.

What are the 3 Register directive's attributes?
TagPrefix
This name identifies the group that the user control belongs to. For example, the tag prefix for ASP.NET server controls is “asp”. You use this prefix to create a naming convention to organize your custom controls.
Namespace
This is the project name and namespace within the custom control assembly that contains the controls to register. Microsoft Visual Basic .NET uses the project name as an implicit namespace, so for controls written in Visual Basic .NET, use the project name.
Assembly
This is the name of the assembly (.dll) containing the custom controls. The control assembly must be referenced by the Web application. Referencing the assembly maintains a copy of it in the Web application’s /bin directory.

What are the differences between User Controls and Custom Controls?

1. User Controls are easy to create where as Custom Controls are difficult to create.

2. User Controls cannot be compiled into an assembly, where as Custom Controls can be compiled into an assembly.
3. User Controls cannot be added to tool box, where as Custom controls can be added to the toolbox.
4. You need to have a copy of user control in every project where you want to use it, where as this is not the case with custom controls. You can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.
5. User controls are used for reusing existing user interface elements and code, but are not useful for developing reusable components for multiple web applications.