.NET Interview Questions by Abhishek Goenka - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

ASP.Net Interview Questions

 

From constructor to destructor (taking into consideration Dispose() and the concept of non-deterministic finalization), what are the events fired as part of the ASP.NET System.Web.UI.Page lifecycle. Why are they important? What interesting things can you do at each?

As all of us know a request comes from Client (Browser) and sends to Server (we call it as Web server) in turn server process the request and sends response back to the client in according to the client request. But internally in the web server there is quite interesting process that happens. To get aware of that process we should first of all know about the architecture of the IIS It mainly consists of 3 Parts/Files

  • Inetinfo.exec
  • ISAPI Filer (Container for Internet Server Application Interface dlls),
  • Worker Process (aspnet_wp.exe)

Inetinfo.exe is the ASP.Net request handler that handles the requests from the client .If it's for static resources like HTML files or image files inetinfo.exe process the request and sent to client. If the request is with extension aspx/asp, inetinfo.exe processes the request to API filter. ISAPI filter will have several runtime modules called as ISAPI extensions. To process the request ISAPI filter takes the help of these runtime modules. The runtime module loaded for ASP page is asp.dll. And for ASP.NET page it's ASPNET_ISAPI.dll. From here the request is processed to the "worker process". Worker Process will have several application domains.

Worker process sends the request to HTTPPIPE line.(HTTP Pipeline is nonetheless collection of .net framework classes). HTTP Pipeline compiles the request into a library and makes a call to HTTP runtime and runtime creates an instance of page class

public class File : System.Web.UI.Page

{}

ASP.Net web page is a class derived from page class, this page class resides in system.web.dll After creating instance pf page class HTTP Runtime immediately invokes process request method of page class

Page Req = new Page();

Req.ProcessRequest();

img1.png

img2.png

Although both Init and Load recursively occur on each control, they happen in reverse order. The Init event (and also the Unload event) for each child control occur before the corresponding event is raised for its container (bottom-up). However the Load event for a container occurs before the Load events for its child controls (top-down). Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events.

What is EnableViewStateMAC?

Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error – Validation of viewstate MAC failed.

Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.

But this has a side effect: it also prevents multiple servers from processing the same ViewState. One solution is to force every server in your farm to use the same key-- generate a hex encoded 64-bit or 128-bit <machineKey> and put that in each server's machine.config :

<!-- validation="[SHA1|MD5|3DES]" -->

<machineKey validation="SHA1"

validationKey="F3690E7A3143C185A6A8B4D81FD55DD7A69EEAA3B32A6AE813ECEEC" />

What is the difference between asp:Label and asp:Literal control?

asp:Label control

asp:Label control is used to write text on the page with different formatting options like bold, italic, underlined etc

asp:Literal control

Ideally Literal control is the rarely used control which is used to put static text on the web page. When it is rendered on the page, it is implemented just as a simple text.

Unlike asp:Label control, there is no property like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. of Literal control. That makes it more powerful, you can even put a pure HTML contents into it.

What’s a SESSION and APPLICATION object?

Viewstate - Viewstate is a hidden fields in an ASP.NET page, contains state of those controls on a page whose "EnableViewstate" property is "true".

You can also explicitly add values in it, on an ASP.NET page like: Viewstate.Add( "TotalStudents", "87" ); Viewstate should be used when you want to save a value between different roundtrips of a single page as Viewstate of a page is not accessible by another page. Because Viewstate renders with the page, it consumes bandwidth, so be careful to use it in applications to be run on low bandwidth.

 Session Variable - Session variables are usually the most commonly used. When a user visits a site, it's sessions starts and when the user become idle or leave the site, the session ends. Session variables should be used to save and retrieve user specific information required on multiple pages. Session variables consumes server memory, so if your may have a huge amount visitors, use session very carefully and instead of put large values in it try to put IDs and references

Application variables - Application variables are shared variables among all users of a web application. Application variables behave like static variables and they are substitute of static variables as static variables are stateless in web applications. Only shared values should be persisted in Application variables, and as soon as they are not in use they should be removed explicitly.

Cache - Cache is probably the least used state feature of ASP.NET. Cache is basically a resource specific state persistence feature, means unlike session it stick with resource instead of user, for instance: pages, controls etc. Cache should be used or frequently used pages, controls, and data structures. Data cache can be used to cache frequently used list of values e.g. list of products

Cookies - Cookies are some values saved in browsers by the website to retrievable and use afterwards. Usually cookies are used to help dynamic websites to identify visitors and retrieve their saved preferences. Cookies are also used to facilitate auto login by persisting user id in a cookie save in user's browser. Because cookies have been saved at client side, they do not create performance issues but may create security issues as they can be hacked from browser.

What are the different types of caching?

CachingOutput Caching - We can use Page output for those page which content are relatively static. So rather than generating the page on each user request we can cached the page using Page output caching so that it can be access from cache itself. So, Instead of pages can be generated once and then cached for subsequent request. Page output caching allows the entire content of a given page to be stored in the cache.

<%@ Page Language="C#" %>

<%@ OutputCache Duration='300' VaryByParam='none' %>

Fragment caching - ASP.NET provides a mechanism for caching portions of pages, called page fragment caching. To cache a portion of a page, you must first encapsulate the portion of the page you want to cache into a user control. In the user control source file, add an OutputCache directive specifying the Duration and VaryByParam attributes. When that user control is loaded into a page at runtime, it is cached, and all subsequent pages that reference that same user control will retrieve it from the cache.

<!— UserControl.ascx —>

<%@ OutputCache Duration='60'

VaryByParam='none' %>

<%@ Control Language="'C#'" %>

Data Caching - Caching of data can dramatically improve the performance of an application by reducing database contention and roundtrips. Simply data caching store the required data in cache so that web server did not send request to DB server every time for each and every request which increase the web site performance.

There are three Different ways to add data or object into cache. But based upon the situation we have to access it. These methods are Cache[], Cache.add(), cache.insert(). The following table will show you the clear difference of these methods.

img3.png

Is it possible to prevent a browser from caching an ASPX page?

Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here:

img4.png

What does AspCompat="true" mean and when should I use it?

The AspCompat attribute forces the page to execute in STA mode. The runtime throws an exception if the compatibility tag is omitted and an STA component is referenced on the page. If you convert the STA component to an assembly using Tlbimp.exe, the runtime does not detect that the component uses the STA model and does not throw an exception, but your application can suffer from poor performance.

<%@Page AspCompat=true Language = VB%>

What are the main event handlers in Global.asax?

ASP.NET provides several modules that participate in each request and expose events you can handle in Global.asax. You can customize and extend these modules as you like, or develop completely new custom modules to process information for and about HTTP requests made to your ASP.NET-based application. Following are important events catered for in the Global.asax file.

  • Application_Init: Fires when the application initializes for the first time.
  • Application_Start: Fires the first time an application starts.
  • Session_Start: Fires the first time when a user’s session is started.
  • Application_BeginRequest: Fires each time a new request comes in.
  • Application_EndRequest: Fires when the request ends.
  • Application_AuthenticateRequest: Indicates that a request is ready to be authenticated.
  • Application_Error: Fires when an unhandled error occurs within the application.
  • Session_End: Fires whenever a single user Session ends or times out.
  • Application_End: Fires when the application ends or times out (Typically used for application cleanup logic).

What are different types of directives in .NET?

@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>

@Control: Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %>

@Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @ Import Namespace="System.web" %>

@Implements: Indicates that the current page or user control implements the specified .NET framework interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>

@Register: Associates aliases with namespaces and class names for concise notation in custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>

@Assembly: Links an assembly to the current page during compilation, making all the assembly's classes and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %><%@ Assembly Src="MySource.vb" %>

@OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page<%@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server | None" Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring" VaryByHeader="headers" VaryByParam="parametername" %>

@Reference: Declaratively indicates that another user control or page source file should be dynamically compiled and linked against the page in which this directive is declared.

What are ASHX files? What are HttpHandlers? Where can they be configured?

ASP.NET programming supports the creation of custom HttpHandler components, which provide a flexible and efficient way to process requests that don't return standard HTML-based pages. For example, HttpHandler components are great for situations in which you want to return simple text, XML, or binary data to the user.

The easiest way to create a custom HttpHandler component is to create a source file with an .ashx extension. You must then add a @WebHandler directive to the top of the .ashx file, along with a class definition that implements the IHttpHandler interface. Any class that implements the IHttpHandler interface must provide an implementation of the IsReusable method and the ProcessRequest method.

<%@ Assembly Name="Microsoft.SharePoint, [full assembly name]" %>

<%@ WebHandler Language="C#" Class="HelloHttpHandler" %>

using System;

using System.Web;

using Microsoft.SharePoint;

 

public class HelloHttpHandler : IHttpHandler {

  public bool IsReusable {

    get { return false; }

  }

  public void ProcessRequest(HttpContext context) {

    SPSite siteColl = SPContext.Current.Site;

    SPWeb site = SPContext.Current.Web;

    context.Response.ContentType = "text/plain"

    context.Response.Write("Hello HttpHandler from the site " +

                           site.Title +

                           " at " +

                           site.Url);  

  }

}

After you deploy your .ashx file within a directory nested within the \LAYOUTS directory, it is accessible to any site in the farm by using a site-relative path.

http://MyWebServer/sites/Sales/_layouts/Litware/HelloHttpHandler.ashx

What is needed to configure a new extension for use in ASP.NET? For example, what if I wanted my system to serve ASPX files with a *.jsp extension?

It is possible to configure new extension for use in ASP.Net. This as to be configured in IIS actually in order for IIS to route your pages to the proper ISAPI

Follow this: http://blogs.msdn.com/gduthie/archive/2007/03/14/custom-file-extensions-in-asp-net-2-0.aspx

What events fire when binding data to a data grid? What are they good for?

ItemCreated: The ItemCreated event is fired when an item in a DataGrid control is created. This means that at the time the event is fired, the DataGrid does not yet know about the data that will be bound to it. So, if the logic of your method depends on this data being available to the control, you’re better off using the ItemDataBound event. Other than that, the ItemCreate event differentiates itself in one other way from the ItemDataBound event: the ItemCreated event is raised when data is bound to the control and during roundtrips (postbacks). These qualities make the event especially well-suited to add custom attributes to a DataRow (such as onmouseover or other javascript events) or to control the appearance in ways that do not depend on the data within the DataRow (such as making every 10th row a different color).

ItemDataBound: The ItemDataBound event is fired after after an item in a DataGrid control is bound. This means that (unlike the ItemCreated event) you can add special formatting to a DataRow that is dependent upon the data contained within that row. Since ItemDataBound is fired after the ItemCreated event, it is within this event that you are presented with the final opportunity to access the data before it is rendered to the client. These qualities make the event well-suited for changing the appearance of a row or cell based on the data within that row or cell (such as highlighting outliers or other important information).Example:

Assume we have the following DataGrid declared on our .aspx page:

<asp:DataGrid ID="MainDataGrid"

    runat="server"

    AutoGenerateColumns="true"

    OnItemDataBound="MainDataGrid_ItemDataBound"

    OnItemCreated="MainDataGrid_ItemCreated" />

On the code behind page then, we can create the following two methods to handle adding titles to header row, to specify more descriptive headers, and to change the row background color based on an employee’s salary:

protected void MainDataGrid_ItemCreated(object sender, DataGridItemEventArgs e)

{

    //If the item is in the header

    if (e.Item.ItemType == ListItemType.Header)

    {

        //Iterate through each cell

        foreach(TableCell item in e.Item.Cells)

        {

            //Add the title attribute — we could just as easily

            //add a javascript onmouseover event here

            item.Attributes.Add("title", item.Text);

        } 

        //Since the header values are set before we have access

        //to the data, we can modify the third column header to

        //be a bit more descriptive

        e.Item.Cells[2].Text = "Salary (in US$)";

    }

}

 

protected void MainDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)

{

    //Since DataGrid differentiates between Items and AlternatingItems, you sometimes

have to check

    //for one *or* the other

   

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.Alternating

Item)

    {

        //Here we will modify the row color based on the salary

        //We can only do this within ItemDataBound since it relies

        //on the data being available from the data source

        if (Convert.ToInt32(e.Item.Cells[2].Text) < 10000)

        {

            e.Item.BackColor = System.Drawing.Color.LightPink;

        }

        else if (Convert.ToInt32(e.Item.Cells[2].Text) < 1000000)

        {

            e.Item.BackColor = System.Drawing.Color.LightBlue;

        }

        else

        {

            e.Item.BackColor = System.Drawing.Color.LightGreen;

        }

    }