HI WELCOME TO SIRIS

asp.net interview questions part 3

Leave a Comment

ASP.NET Interview Questions on 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.
<body dir="rtl"> 

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.

C# Interview Questions - 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);
}
}
}
}



XML Interview Questions - Validating XML documents



What determines the validity of an XML document? 
Document Type Definition(DTD) or an XML Schema determines the validity of an XML document.

What is a valid XML document?XML documents are compared to rules that are specified in a DTD or schema. A well-formed XML document that meets all of the requirements of one or more specifications is called a valid XML Document.

What are the 2 types of XML parsers? 
Nonvalidating Parsers - Parsers that don’t support validation
Validating Parsers - Parsers that support validation

Can you combine both Schema and DTD references in a single XML document?

Yes

Are DTD's well-formed XML documents? 
No, DTDs are not well-formed XML documents. This is because they follow DTD syntax rules rather than XML document syntax.

Are XML schema's well-formed XML documents?

Yes.

What is the difference between an XML schema and a DTD? 
The XML Schema is the officially sanctioned Schema definition. Unlike DTDs, the format of XML Schemas follows the rules of well-formed XML documents. The Schema also allows for much more granular control over the data that is being described. Because of the XML format and the detailed format controls, Schemas tend to be very complex and often much longer than the XML documents that they are describing. Schemas are often much more easy for developers to read and follow,due to the less cryptic nature of the references in Schemas versus DTDs.

How do you define references to schemas in an XML document?

References to schemas are defined by creating an instance of the XMLSchemainstance namespace. An example is shown below.
<rootelement xmlns:xsi=”http://www.w3.org/2001/XMLSchemainstance” xsi:noNamespaceSchemaLocation=”schemafile.xsd”> 

The namespace declaration reference to http://www.w3.org/2001/XMLSchemainstance resolves to an actual document at that location, which is a brief description of the way that the W3C Schema should be referenced. The noNamespaceSchemaLocation value tells us that there is no predefined namespace for the Schema. This means that all of the elements in the XML document should be validated against the schema specified. The location of the Schema is schemafile.xsd. Because there is no path defined, the file containing the schema should be located in the same directory as the XML file to be validated by the Schema.

You can also define the schema location, and map it to a specific namespace by using the schemaLocation attribute declaration instead of noNamespace SchemaLocation. If you do so, you have to declare a namespace that matches the schemaLocation attribute value. The declaration must be made before you reference the schema in a schemaLocation attribute assignment.

XML related Interview Questions


What Is XML? 
XML stands for Extensible Markup Language, and it is used to describe documents and data in a standardized, text-based format that can be easily transported via standard Internet protocols. XML, like HTML, is based on, Standard Generalized Markup Language (SGML).

What are Well-formed XML documents?
XML
, is very strict about a small core of format requirements that make the difference between a text document containing a bunch of tags and an actual XML document. XML documents that meet W3C XML document formatting recommendations are described as being well-formed XML documents. Well-formed XML documents can contain elements, attributes, and text.

What is an empty XML element? 
Elements with no attributes or text are called as empty XML element. Empty XML elements can be represented in an XML document as shown below:
<element/> 

What is meant by XML document declaration?

Most XML documents start with an <?xml?> element at the top of the page. This is called an XML document declaration. An XML document declaration is an optional element that is useful to determine the version of XML and the encoding type of the source data. It is not a required element for an XML document to be well formed. Most common XML document declaration is shown below:
<?xml version=”1.0” encoding=”UTF-8”?>

What does UTF stands for? 
UTF stands for Universal Character Set Transformation Format.

Should every XML document have a root element?

Yes.

Can an XML document contain multiple root level elements? 
No, an XML document can contain only one root level element.

What is the use of XML attributes?XML attributes are used for adding more information and descriptions to the values of elements,and the text associated with elements.

Is XML case sensitive? 
Yes

How do you comment lines in XML?

You can comment lines in XML as shown below.
<! -- This is commented line in an XML document -->

What are XML namespaces? 
Namespaces are a method for separating and identifying duplicate XML element names in an XML document. Namespaces can also be used as identifiers to describe data types and other information. Namespace declarations can be compared to defining a short variable name for a long variable (such as pi=3.14159....) in programming languages. In XML, the variable assignment is defined by an attribute declaration. The variable name is the attribute name, and the variable value is the attribute value. In order to identify namespace declarations versus other types of attribute declarations, a reserved xmlns: prefix is used when declaring a namespace name and value. The attribute name after the xmlns: prefix identifies the name for the defined namespace. The value of the attribute provides the unique identifier for the namespace. Once the namespace is declared, the namespace name can be used as a prefix in element names.

Why is it a good idea to use a URL as the XML namespace value? 
Although the namespace declaration value does not need to be a URL or resolve to an actual URL destination, it is a good idea to use a URL anyway, and to choose a URL that could resolve to an actual destination, just in case developers want to add documentation for the namespace to the URL in the future.

When to use namespaces?

Namespaces are optional components of basic XML documents. However, namespace declarations are recommended if your XML documents have any current or future potential of being shared with other XML documents that may share the same element names. Also, newer XML-based technologies such as XML Schemas,SOAP, and WSDL make heavy use of XML namespaces to identify data encoding types and important elements of their structure.

ASP.NET Interview Questions on caching application data


Which object can be 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.

ASP.NET Interview Questions on fragment caching


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.

SP.NET Interview Questions on 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.


ASP.NET Interview Questions on web farm and web garden



What does the term Scalability mean?

Web applications that serve a large number of users or that present large amounts of data need to able to add capacity as users’ demands increase. The ability to add capacity to an application is called scalability. ASP.NET Web applications support this concept through their ability to run in multiple processes and to have those processes distributed across multiple CPUs and/or multiple servers.

What is the difference between a web farm and a web garden?
A Web application running on a single server that has multiple CPUs is called a Web garden in the ASP.NET documentation. A Web application running on multiple servers is called a Web farm.

If your web server has multiple processors, how can you specify that ASP.NET runs on all or some of the CPUs?
If your server has multiple processors, you can specify that ASP.NET runs on all or some of the CPUs by setting the webGardenattribute of the processModel element in the server’s Machine.config file

What are the implications on Application and Session state variables in a web farm or a web garden?
In both a Web garden and a Web farm, client requests are directed to the ASP.NET process that is currently least busy. That means that a single client can interact with different CPUs or servers over the course of his or her session. This has the following implications for Application and Session state variables:

Application state variables are unique to each separate instance of the Web application.
Clients can share information through Application state if the Web application is running on a Web garden or a Web farm.

Session state variables are stored in-process by default.
To enable Session state in a Web garden or Web farm, you need to specify a Session state provider.

How can you share Application State in a web farm or a web garden?
To share data across multiple sessions in a Web garden or Web farm, you must save and restore the information using a resource that is available to all the processes. This can be done through an XML file, a database, or some other resource using the standard file or database access methods.

What are the two built-in ways provided by ASP.NET to share Session state information across a Web garden or Web farm?
ASP.NET provides two built-in ways to share Session state information across a Web garden or Web farm. You can share Session state using:

A state server, as specified by a network location
This technique is simple to implement and doesn’t require you to install Microsoft SQL Server.
A SQL database, as specified by a SQL connection
This technique provides the best performance for storing and retrieving state information.

What are the steps to follow to share Session state information using a state server?
To share Session state information using a state server, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and stateConnectionString attributes.
2. Run the aspnet_state.exe utility on the Session state server. The aspnet_state.exe utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional or Visual Studio .NET Enterprise Architect editions.

What are the steps to follow to share Session state information using a SQL database?
To share Session state information using a SQL database, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and sqlConnectionString attributes.
2. Run the InstallSqlState.sql utility on the Session state server. This utility installs the SQL database that shares Session state information across processes. The InstallSqlState.sql utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional, Visual Studio .NET Enterprise Developer, or Visual Studio .NET Enterprise Architect editions.

Web application maintainance related ASP.NET Interview Questions


Why is it important to monitor a deployed a Web application?
After you have deployed a Web application, you need to monitor how it performs on the server. Many issues can crop up at this point because of
1. The number of users accessing the application.
2. The unpredictable nature of user interaction.
3. The possibility of malicious attack.

What are the 3 major steps invloved in maintaining a deployed web application?
Maintaining a deployed application is an ongoing task that involves three major steps:
1. Monitoring the application for error, performance, and security issues.
2. Repairing the application as issues are discovered.
3. Tuning the application to respond to user traffic.

What are the MMC snap-ins provided by windows for monitoring security, performance, and error events?
The Event Viewer snap-in : Lists application, system, and security events as they occur on the system. Use this tool to see what is currently happening on the server and to get specific information about a particular event.
The Performance snap-in : Lets you create new events to display in the Event Viewer and allows you to track event counters over time for display graphically or in report form.

How do you run the Event Viewer to view application, system, and security events as they happen?
To run the Event Viewer, choose Event Viewer from the Administrative Tools submenu on the Windows Start menu. (You can show the Administrative Tools menu in Windows XP Professional by opening the Start button’s Properties dialog box and clicking the Customize button on the Start Menu tab. The Administrative Tools option is located on the Advanced tab of the Customize Start Menu dialog box.) After clicking the Event Viewer shortcut, Windows displays the Event Viewer snap-in in the MMC.

What are the 3 levels at which the Event Viewer snap-in displays general application, system, and security events?
1. Informational events.
2. Warning events.
3. Error events.

Can you repair a deployed web application in place without restarting the server or IIS?
Yes, to repair a deployed Web application, copy the new assembly (.dll) and/or content files (.aspx, .ascx, and so on) to the application folder on the server. ASP.NET automatically restarts the application when you replace the assembly. You do not need to install or register the assembly on the server.

What is ASP.NET Process recycling?
ASP.NET Web applications have a limited ability to repair themselves through process recycling. Process recycling is the technique of shutting down and restarting an ASP.NET worker process (aspnet_wp.exe) that has become inactive or is consuming excessive resources. You can control how ASP.NET processes are recycled through attributes in the processModel element in the Machine.config file.

Describes the processModel attributes found in machine.config that relate to process recycling?
1. timeout attribute :The amount of time (hh:mm:ss) before the process is shut down and restarted. Use this setting to automatically recycle a process after a certain number of requests as a preventive measure.
2. shutDownTimeOut attribute : How much time each process has to shut itself down. After this amount of time, the process is terminated by the system if it still running.
3. requestLimit attribute : The number of queued requests to serve before the process is shut down and restarted. Use this setting the same way you use the timeout attribute.
4. restartQueueLimit attribute : The number of queued requests to retain while the process is shut down and restarted.
5. memoryLimit attribute : The percentage of physical memory the ASP.NET process is allowed to consume before that process is shut down and a new process is started. This setting helps prevent memory leaks from degrading the server.
6. responseRestart­ - DeadlockInterval : The amount of time to wait before restarting a process that was shut down because it was deadlocked. This setting is usually several minutes to prevent applications with serious errors from degrading the server.
7. responseDeadlockInterval : The amount of time to wait before restarting a process that is deadlocked. The process is restarted if there are queued requests and the process has not responded within this time limit.

What is the use of processModel element apart from providing process recycling?
The processModel element in the server’s Machine.config file provides attributes that control certain performance aspects, such as
1. The maximum number of requests to be queued.
2. How long to wait before checking whether a client is connected.
3. How many threads to allow per processor.

Describe the processModel attributes that relate to performance tuning?
requestQueueLimit 
The number of queued requests allowed before ASP.NET returns response code 503 (Server too busy) to new requests
clientConnectedCheck 
The amount of time (hh:mm:ss) to wait before checking whether a client is still connected
maxWorkerThreads 
The maximum number of threads per processor
maxIOThreads 
The maximum number of I/O threads per processor

In general, lowering these settings allows your server to handle fewer clients more quickly. Increasing these settings permits more clients and more queued requests, but slows response times.

How do you turn off Session state?
To turn off Session state, in the application’s Web.config file, set the sessionState element’s mode attribute to Off.

If you turn of Session State, can you use Session state variables in code anywhere in the application?
No

What is Optimization?
Optimization usually refers to writing code in a way that executes more quickly or consumes fewer resources. In general, optimizations simply reflect the good programming practices.

List some of the common steps to follow to optimize a web application for performance?
Turn off debugging for deployed applications.
Code that has been compiled with release options runs faster than code compiled with debug options.
Avoid round-trips between the client and server.
ASP.NET uses postbacks to process server events on a page. Try to design Web forms so that the data on the Web form is complete before the user posts the data to the server. You can use the validation controls to ensure that data is complete on the client side before the page is submitted.
Turn off Session state if it isn’t needed.
In some cases, you can design your code to use other techniques, such as cookies, to store client data.
Turn off ViewState for server controls that do not need to retain their values.
Saving ViewState information adds to the amount of data that must be transmitted back to the server with each request.
Use stored procedures with databases.
Stored procedures execute more quickly than ad hoc queries.
Use SqlDataReader rather than data sets for read-forward data retrieval.
Using SqlDataReader is faster and consumes less memory than creating a data set.

ASP.NET ViewState related Interview Questions

What is ViewState?

 Web forms have very short lifetimes.In ASP.NET, the data that is entered in controls is encoded and stored in a hidden field. This encoded data is then sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load event.The data that ASP.NET preserves between requests is called the Web form’s view state.

How do you enable or disable a ViewState for a control on the page? 

Every ASP.NET control has a property called EnableViewState. If EnableViewState is set to true ViewState is enabled for the control. If EnableViewState is set to false ViewState is disabled for the control.How do you enable or disable a ViewState at the page level?At the page level you can enable or disable ViewState using EnableViewState property of the page.

What is the name of the hidden form field in which ViewState of the page is saved? 
__ViewState
What are the performance implications of ViewState?
ViewState is usually good to retain the state of the controls on the webform across postbacks. If you have a huge DataGrid with tons of data being loaded on every page load. It is a good idea to disable the ViewState of the DataGrid for the page to load faster. If the ViewState of a large DataGrid is not disabled, ViewState can easily get very large, on the order of tens of kilobytes. Not only does the __ViewState form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.

When does ViewState restoration happens? 
During the Page_Init event


What are the disadvantages of using ViewState?
1. On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __ViewState form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.

2. The __ViewState hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __ViewState form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.

Is ViewState encoded? 
Yes, ViewState is base-64 encoded.
Can you encrypt ViewState of Page?Yes, we can use the LosFormatter class to encrypt ViewState of Page

Can the HTML controls retian State accross postbacks? 

No, by default HTML controls donot retain state accross postbacks.

Can you make HTML controls retain State accross postbacks?
Yes, HTML controls can retain State accross postbacks, if you convert HTML controls to Server Controls. There are 2 ways to convert HTML control to Server Controls.

1. Right click on the HTML Control and then click "Run As Server Control"
Or
2. Set runat="server" attribute for the Control.

Is ViewState supported in classic ASP? 
No,ViewState is introduced in asp.net, it was not in classic asp.

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.

When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server.
Is ViewState of one page available to another page?No, ViewState of a Page is available only in that page. You cannot access ViewState of one page from another page.

Can you programatically store and retrieve data from ViewState? 
Yes. In ASP.NET you can programatically store and retrieve data from ViewState.See the example below

//Save the value in ViewState object
ViewState("SomeVar") = txtFirstName.text; 
//Retrieve the value from ViewState object
String strFirstName = ViewState("SomeVar").ToString();
Can someone view the Page HTML source and read ViewState? 
No. ViewState is base-64 encoded. Hence you cannot read ViewState. If you right click on the Page and View Source you will find __ViewState is base-64 encoded.

What happens during the Page_Init event?
The server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.

Interview Questions on ASP.NET Validation controls

What are ASP.NET Validation controls?
ASP.NET provides validation controls to help you check Web form data entries before the data is accepted and saved in the Database. Validation controls can be used to address the following questions.
1. Did the user enter anything?
2. Is the entry the appropriate kind of data (For example, Date of Birth should be a valid Date, Name should be a string etc.)?
3. Is the data within a required range?(For example age cannot be greater than 100 years)
The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server.Most validity problems can be caught and corrected by the user without a round-trip to the server.

Where do the ASP.NET validation controls validate data, on the Client or on the Web Server?
ASP.NET validation controls validate data first on the client and then on the web server. If a client disables javascript on the browser then, client side validations are bypassed and validations are performed on the web server.

Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Validation controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been circumvented.

What are the 6 different validation controls provided by ASP.NET? 
RequiredFieldValidator:Checks whether a control contains data
CompareValidator:Checks whether an entered item matches an entry in another control
RangeValidator:Checks whether an entered item is between two values
RegularExpressionValidator:Checks whether an entered item matches a specified format
CustomValidator:Checks the validity of an entered item using a client-side script or a server-side code, or both
ValidationSummary:Displays validation errors in a central location or display a general validation error description


What property of the validation control is used to specify which control to validate?ControlToValidate property.

Explain in simple steps how to use validation controls? 
1.Draw a validation control on a Web form and set its ControlToValidate property to the control you want to validate. 

2.If you’re using the CompareValidator control, you also need to specify the ControlToCompare property.
3.Set the validation control’s ErrorMessage property to the error message you want displayed if the control’s data is not valid.
4.Set the validation control’s Text property if you want the validation control to display a message other than the message in the ErrorMessage property when an error occurs. Setting the Text property lets you briefly indicate where the error occurred on the form and display the longer ErrorMessage property in a ValidationSummary control.
5.Draw a ValidationSummary control on the Web form to display the error messages from the validation controls in one place.
6.Provide a control that triggers a postback event. Although validation occurs on the client side, validation doesn’t start until a postback is requested.

Are the validation controls fired on the client side if javascript is disabled on the client browser?

No, validation controls are not fired on the client side if javascript is disabled on the client browser.

What is the use of CausesValidation property of an ASP.NET button control? 
CausesValidation property of an ASP.NET button control is used to determine if the validation controls should be fired when the button is clicked. If CausesValidation property is set to true, then validation is performed and if the CausesValidation property is set to false then validation is not done.

Give an example of real time scenario where you might use CausesValidation property of an ASP.NET button control?
Let us assume we have a Page that collects user information like name, age, date of birth, gender with a submit and reset buttons. When I click the submit button the information filled on the form should be validated and saved to the database. If I click the reset button then all the controls on the webform should default to their initial values without validation happening.So you have to set the CausesValidation property of the reset button to false for the validation to be bypassed. Other wise you will not be able to post back the page to the server.
What is ASP.NET Custom Validator used for?
ASP.NET Custom Validator is used to perform complex types of validation not provided by the standard validation control, use a CustomValidator control and write code to perform the validation on the server side and optionally on the client side.

How do you programatically check, if the client side validation is not bypassed by disabling the javascript on the client browser? 
We use Page.IsValid property to determine if all the validations have succeeded. For this property to return true, all validation server controls in the current validation group must validate successfully.

How do you programatically invoke all validation controls on a page?
Call Page.Validate() method. When this method is invoked, it iterates through the validation controls contained in the ValidatorCollection object associated with the Page.Validators property and invokes the validation logic for each validation control in the current validation group.

What is a validation group? 
Validation groups allow you to group validation controls on a page as a set. Each validation group can perform validation independently from other validation groups on the page.
How do you create a validation group?You create a validation group by setting the ValidationGroup property to the same name for all the controls you want to group. You can assign any name to a validation group, but you must use the same name for all members of the group.

Explain how a validation group works when the Page is posted by clicking a button? 
During postback, the Page class's IsValid property is set based only on the validation controls in the current validation group. The current validation group is determined by the control that caused validation to occur. For example, if a button control with a validation group of LoginGroup is clicked, then the IsValid property will return true if all validation controls whose ValidationGroup property is set to LoginGroup are valid.

Can a DropDownList fire validation controls?
Yes, DropDownList control can also fire validation if the control's CausesValidation property is set to true and the AutoPostBack property is set to true.

How do you programatically force all validation controls in a particular validation group to be fired? 
Call the Page.Validate(string GroupName) method and pass the name of the validation group. This will fire only the validation controls in that validation group

.What is SetFocusOnError property of a validation control used for?
Use the SetFocusOnError property to specify whether focus is automatically set to the control specified by the ControlToValidate property when this validation control fails. This allows the user to quickly update the appropriate control.

If multiple validation controls fail and this property is set to true, the control specified in the ControlToValidate property for the first validation control receives focus.

What is InitialValue property of a RequiredFieldValidator?
Use this property to specify the initial value of the input control.Validation fails only if the value of the associated input control matches this InitialValue upon losing focus.

Transactions related ASP.NET Interview Questions

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");

ASP.NET Interview Questions on 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 <trace> 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

Techniques to send data from one web form to another web form


What are the different techniques to send data from one web form to another web form?
 1. Query strings :Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the user, so they should not contain secure information such as passwords.

2. Cookies :
Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that possibility.

3. Session state :
Use Session state variables to store items that you want keep local to the current session (single user).

4. Application state :
Use Application state variables to store items that you want be available to all users of the application.

ASP.NET Session State and Application State Interview Questions


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();

ASP.NET Interview Questions on web application Security


What is the difference between Authentication and Authorization? 
Authentication is the process of identifying users. Authorization is the process of granting access to those users based on identity. Together, authentication and authorization provide the means to keeping your Web application secure from intruders.

What is Anonymous access?
Anonymous access is the way most public Web sites work. Sites containing public information allow anyone to see that information, so they don’t authenticate users. ASP.NET Web applications provide anonymous access to resources on the server by impersonation. Impersonation is the process of assigning a user account to an unknown user.

What is the account that is associated with Anonymous access? 
By default, the anonymous access account is named IUSER_machinename. You use that account to control anonymous users’ access to resources on the server.

What is the default user account under which an ASP.NET web application run on a web server?
Under the default settings, ASP.NET uses the ASPNET account to run the Web application. This means that if the application attempts to perform any tasks that are not included in the ASPNET account’s privileges, a security exception will occur and access will be denied.

How do you restrict the access of anonymous users? 
You restrict the access of anonymous users by setting Windows file permissions. To be secure, your server must use the Microsoft Windows NT file system (NTFS). The earlier FAT or FAT32 file systems do not provide file-level security.

What are the 3 major ways to authenticate and authorize users within an ASP.NET Web application?
Windows authentication : 
Identifies and authorizes users based on the server’s user list. Access to resources on the server is then granted or denied based on the user account’s privileges. This works the same way as regular Windows network security.
Forms authentication : Directs users to a logon Web form that collects user name and password information, and then authenticates the user against a user list or database that the application maintains.
Passport authentication : Directs new users to a site hosted by Microsoft so that they can register a single user name and password that will authorize their access to multiple Web sites. Existing users are prompted for their Microsoft Passport user name and password, which the application then authenticates from the Passport user list.

What is the namespace where all security related classes are present? 
System.Web.Security

What type of authentication can be used for Public Internet Web application?
Anonymous access. This is the common access method for most Web sites. No logon is required, and you secure restricted resources using NTFS file permissions.

What type of authentication can be used for Intranet Web application? 
Windows authentication. Windows authentication authenticates network users through the domain controller. Network users have access to Web application resources as determined by their user privileges on the server.

What type of authentication can be used for Private corporate Web application?
Windows authentication. Corporate users can access the Web application using their corporate network user names and passwords. User accounts are administered using the Windows network security tools.

What type of authentication can be used for Commercial Web application? 
Forms authentication. Applications that need to collect shipping and billing information should implement Forms authentication to gather and store customer information.

What type of authentication can be used for Multiple commercial Web applications?Passport authentication. Passport authentication allows users to sign in once through a central authority. The user’s identity is then available to any application using the Passport SDK. Customer information is maintained in a Passport profile, rather than in a local database.

Can you use ASP.NET Authentication with HTM and HTML Files? 
The three ASP.NET authentication modes apply to files that are part of the Web application. That includes Web forms (.aspx), modules (.asax), and other resources that are processed through the Web application’s executable. It does not automatically include HTML pages (.htm or .html). Those pages are handled by Internet Information Services (IIS), rather than ASP.NET. If you want to authenticate users who access HTML pages from within your Web application using Windows, Forms, or Passport authentication modes, you must map those files to the ASP.NET executable.

How do map .htm and .html files to the ASP.NET executable using the IIS snap-in? 
To map .htm and .html files to the ASP.NET executable using the IIS snap-in, follow these steps:
1. In the IIS snap-in, select the folder containing your Web application, and then choose Properties from the Action menu. IIS displays the Properties dialog box.
2. Click the Home Directory or Virtual Directory tab, and then click Configuration. IIS displays the Application Configuration dialog box, as shown in the diagram below.

3. Click Add. IIS displays the Add/Edit Application Extension Mapping dialog box, as shown in the diagram below.

4. Click Browse, and select the aspnet_isapi.dll file. That file is stored in the Windows Microsoft .NET Framework directory; the path will be something like C:\Windows\Microsoft.NET\Framework\versionnumber\aspnet_isapi.dll.
5. Type .htm in the File Extension box, and click OK.
6. Repeat steps 3 through 5 for the .html file extension. Click OK to close the IIS dialog boxes when you’ve finished.

Interview Questions on Query Strings in ASP.NET


Give an example of using querystrings to send data from one page to another?
Query strings are a very simple and popular technique to pass data from one Web page to the next. You send data as part of the URL. In the below example FName and LName are sent as part of the URL. In the page load of QueryStrings2.aspx we use Request.QueryString to read the values. As we are sending more than one query string we use the & symbol to seperate query strings.
//Code to send query strings FName and LName as part of the URLQueryStrings2.aspx?FName=David&LName=Boon protected void Page_Load(object sender, EventArgs e)
{
//Code to read Query String values
string FirstName = Request.QueryString["FName"];
string LastName = Request.QueryString["LName"];
Response.Write("Data from QueryStrings1.aspx : " + FirstName + ", " + LastName);


Give an example to send Query Strings from code? 
You can send query strings from server side code using the Response.Redirect() method as shown below.
Response.Redirect("QueryStrings2.aspx?FName=David&LName=Boon");
What are the advantages of using Query Strings?
1.
 Query strings are easy to implement.
2. Browser support for passing values in a query string is nearly universal.
3. Query strings are contained in the HTTP request for a specific URL and do not require server resources.

What are the disadvantages of using querystrings to send data from one page to another?
1.
 Query strings are insecure because the information in the query string is directly visible to the user on the address line in the browser.
2. Many browsers impose a 255 URL character limit which can limit their flexibility.

Interview Questions on ASP.NET Page navigation techniques


What are different page navigation techniques in ASP.NET? 
Hyperlink control : Navigate to another page.
Response.Redirect : Navigate to another page from code. This is equivalent to clicking a hyperlink.
Server.Transfer : End the current Web form and begin executing a new Web form. This method works only when navigating to a Web Forms page (.aspx).
Server.Execute : Begin executing a new Web form while still displaying the current Web form. The contents of both forms are combined. This method works only when navigating to a Web Forms page (.aspx).
Window.Open script method : Display a page in a new browser window on the client.

What is the difference between Response.Redirect and Server.Transfer?
1.
 When we use Server.Transfer the redirection happens on the server where as when we use Response.Redirect the redirection happens from the browser.
2. Server.Transfer is faster as there is no round trip involved while navigating from one webform to another webform.
Response.Redirect is slower than Server.Transfer as there is round trip from the server to the client browser.
3. Server.Transfer works only with .aspx files where as Response.Redirect works with .aspx and .Htm pages.
4. Server.Transfer will work with files on the same web server. You can't use Server.Transfer to send the user to an external site where as Response.Redirect can do that.
5. Server.Transfer does not update the URL in the browser. For example when you navigate from WebForm1.aspx to WebForm2.aspx using Server.Transfer the URL in the browser still shows WebForm1.aspx while you are actually looking at WebForm2.aspx. Response.Redirect updates the URL in the browser.


What is the use of Server.Execute method?
Server.Execute method is used to process a second Web form without leaving the first Web form. This technique lets you direct the results from a Web form to a region on the current page.

Is it possible to send a webform's QueryString, ViewState, and event procedure information to another webform? 
Yes, we can use Server.Transfer or Server.Execute to send a webform's QueryString, ViewState, and event procedure information to another webform.

For this to work you have to set the preserveForm argument to True.To be able to read one Web form’s ViewState from another, you must first set the EnableViewStateMac attribute in the Web form’s Page directive to False. By default, ASP.NET hashes ViewState information, and setting this attribute to False disables that hashing so that the information can be read on the subsequent Web form.

0 comments:

Post a Comment

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