Thursday, 16 May 2013

ASP.NET Interview Questions


Hi friends,

Its time of interview :) :) so that i am posting new article on ASP.NET  Interview Questions



What is different between ASP State Management and ASP.NET State Management? 
State management is the process by which you maintain state and page information over multiple requests for the same or different pages. As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site. Furthermore, pages are destroyed and recreated with each round trip to the server; therefore page information will not exist beyond the life cycle of a single page.

Client-Side Method State Management Summary
The following table summarizes client-side state management options and when you should consider using them.
Method
Use when
View state
You need to store small amounts of information for a page that will post back to itself. Use of the ViewState property provides functionality with basic security.
Hidden fields
You need to store small amounts of information for a page that will post back to itself or another page, and security is not an issue.
Note   You can use a hidden field only on pages that are submitted to the server.
Cookies
You need to store small amounts of information on the client and security is not an issue.
Query string
You are transferring small amounts of information from one page to another and security is not an issue.
Note   You can use query strings only if you are requesting the same page, or another page via a link.

Server-Side Method State Management Summary
The following table summarizes server-side state management options and when you should consider using them.
Method
Use when
Application state
You are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session state
You are storing short-lived information that is specific to an individual session, and security is an issue. Do not store large quantities of information in session state. Be aware that a session state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Database support
You are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.

User State with Session Key-Pair collection
  • SessionId has larger Hash code then traditional ASP
  • Session can be created even if Client side cookie is disabled.
  • More Session level events are available so as getting more control over events.

Application State with Appliation object
  • Application Object is accessible to all resources (ASP.NET page and web services) within our web application

Transient Application State (Cache)
  • In addition to application object we have cache object which is accessible globaly to whole application. Cache, however provides callbacks and expiration which means at any time if the source changes the cache object updates itself also we can set expiration time for object.

Static Variables
  • Static variable contains value which can't be changed and is shared through out the application. retains its value .
 
What is the difference between Request.QueryString(“field”) and Request.Form("field")?
Request.Form("name") retrieves the form element name from the Request object. Use the Form property to retrieve form data from the Request object sent by the Post method.

Request.QueryString("address") retrieves the address field from a query string use. Use the QueryString method of the Request object to retrieve the query string sent by a Get method.
 
How can we pass information between 2 asp.net pages? 
Using State Management.
 
What is the difference between Web User Control and Web Custom Control?
Web User controls are web controls provided in class library and Web Custom controls are the classes we inherit form user controls with additional funtionality and to use them we take objects of these classes. The main difference between the two controls lies in ease of creation vs. ease of use at design time. The main differences between the two types are outlined in this table:

Web user controls
Web custom controls
Easier to create
Harder to create
Limited support for consumers who use a visual design tool
Full visual design tool support for consumers
A separate copy of the control is required in each application
Only a single copy of the control is required, in the global assembly cache
Cannot be added to the Toolbox in Visual Studio
Can be added to the Toolbox in Visual Studio

 The ASP.NET server controls provide a great deal of functionality, but they cannot cover every situation. Web user controls enable you to easily define controls as you need them for your applications, using the same programming techniques that you use to write Web Forms pages. You can even convert a Web Forms page into a Web user control with a few modifications. To make sure that a user control cannot be run as a standalone Web Forms page, user controls are identified by the file name extension .ascx.

You design Web user controls in much the same way that you design Web Forms pages. You can use the same HTML elements and Web controls on a user control  that you do on a standard Web Forms page. However, the user control does not have <HTML>, <BODY>, and <FORM> elements in it, and the file name extension must be .ascx. The following example shows a simple user control that you might use as a menu. The four menu choices are implemented as Hyperlink Web server controls:
<!-- Visual Basic -->
<%@ Control Language="vb" AutoEventWireup="false" Codebehind="menu.ascx.vb" Inherits="myProj.menu"     TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<P>
<asp:HyperLink id="lnkLogin" runat="server" NavigateURL="Login.aspx">Login</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkAddToCart" runat="server" NavigateURL="Cart.aspx">Add to Cart</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkTechSupport" runat="server" NavigateURL="TechSupport.aspx">Technical Support</asp:HyperLink>
&nbsp; |
<asp:HyperLink id="lnkAbout" runat="server" NavigateURL="AboutUs.aspx">About Us</asp:HyperLink>
</P>
Web custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox. There are several ways that you can create Web custom controls:
  • You can compile a control that combines the functionality of two or more existing controls. For example, if you need a control that encapsulates a button and a text box, you can create it by compiling the existing controls together.
  • If an existing server control almost meets your requirements but lacks some required features, you can customize the control by deriving from it and overriding its properties, methods, and events.
  • If none of the existing Web server controls (or their combinations) meet your requirements, you can create a custom control by deriving from one of the base control classes. These classes provide all the basic functionality of Web server controls, so you can focus on programming the features you need.
 
I've 2 buttons on an asp.net page (.aspx). How can I execute same routine clicking on 2 buttons?
Override the subroutine that is attached with the button. 
 
What is a Viewstate?
ViewState is encrypted information about all the data in web controls in a page. When a form is submitted in ASP.NET, the form reappears in the browser window together with all form values. This is because ASP.NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you don’t want to maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.

The Control.ViewState property is associated with each server control in your web form and provides a dictionary object for retaining values between such multiple requests for the same page. This is the method that the page uses to preserve page and control property values between round trips. When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.

When a page is re-loaded, two methods pertaining to ViewState are called: LoadViewState and SaveViewState. You can validate that these work as claimed by analyzing the information presented if you turn on tracing for a page containing the above elements. You will see that on postback, and assuming ViewState is enabled, that the LoadViewState method is executed after the Init method of the Page class has been completed. SaveViewState is called after PreRender and prior to actual page rendering.
 
What is the life cycle of an asp.net page?
  1. Instantiate
  2. Initialize
  3. TrackViewState
  4. LoadViewState (postback)
  5. Load postback data (postback, IPostBackDatahandler.LoadPostdata)
  6. Load
  7. Load postback data for dynamical controls added on Page_Load
  8. Raise Changed Events (postback, IPostBackDatahandler.RaisePostDataChanged)
  9. Raise postback event (postback, IPostBackEventHandler.RaisePostBackEvent)
  10. PreRender
  11. SaveViewState
  12. Render
  13. Unload
  14. Dispose

From MSDN Site:

The following table provides a high-level overview of the phases in the lifecycle of a control.
Phase
What a control needs to do
Method or event to override
Initialize
Initialize settings needed during the lifetime of the incoming Web request.
Init event (OnInit method)
Load view state
At the end of this phase, the ViewState property of a control is automatically populated. A control can override the default implementation of the LoadViewState method to customize state restoration.
LoadViewState method
Process postback data
Process incoming form data and update properties accordingly.
Note   Only controls that process postback data participate in this phase.
LoadPostData method
(if IPostBackDataHandler is
 implemented)
Load
Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data.
Load event
(OnLoad method)
Send postback
change notifications


Raise change events in response to state changes between the current and previous postbacks.
Note   Only controls that raise postback change events participate in this phase.
RaisePostDataChangedEvent method
(if IPostBackDataHandler is
implemented)
Handle postback
events
Handle the client-side event that caused the postback and raise appropriate events on the server.
Note   Only controls that process postback events participate in this phase.
RaisePostBackEvent method
(if IPostBackEventHandler is
implemented)
PreRender
Perform any updates before the output is rendered. Any changes made to the state of the control in the PreRender phase can be saved, while changes made in the rendering phase are lost.
PreRender event
(OnPreRender method)
Save state
The ViewState property of a control is automatically persisted to a string object after this stage. This string object is sent to the client and back as a hidden variable. For improving efficiency, a control can override the SaveViewState method to modify the ViewState property.
SaveViewState method
Render
Generate output to be rendered to the client.
Render method
Dispose
Perform any final cleanup before the control is torn down. References to expensive resources such as database connections must be released in this phase.
Dispose method
Unload
Perform any final cleanup before the control is torn down. Control authors generally perform cleanup in Dispose and do not handle this event.
UnLoad event (On UnLoad
method)

 
Explain about .NET Architecture.
  • Enterprise Architecture
  • Application Architecture
  • System Architecture
 
HTML Server controls vs. ASP.NET Web Server controls.
HTML server controls: HTML server controls are HTML elements containing attributes that make them visible to - and programmable on - the server. By default, HTML elements on a Web Forms page are not available to the server; they are treated as opaque text that is passed through to the browser. However, by converting HTML elements to HTML server controls, you expose them as elements you can program on the server.

The object model for HTML server controls maps closely to that of the corresponding elements. For example, HTML attributes are exposed in HTML server controls as properties.

Any HTML element on a page can be converted to an HTML server control. Conversion is a simple process involving just a few attributes. As a minimum, an HTML element is converted to a control by the addition of the attribute RUNAT="SERVER". This alerts the ASP.NET page framework during parsing that it should create an instance of the control to use during server-side page processing. If you want to reference the control as a member within your code, you should also assign an ID attribute to the control.

Web server controls: Controls with more built-in features than HTML server controls. Web server controls include not only form-type controls such as buttons and text boxes, but also special-purpose controls such as a calendar. Web server controls are more abstract than HTML server controls in that their object model does not necessarily reflect HTML syntax.

Web server controls are a second set of controls designed with a different emphasis. They do not map one-to-one to HTML server controls. Instead, they are defined as abstract controls in which the actual HTML rendered by the control can be quite different from the model that you program against. For example, a RadioButtonList Web server control might be rendered in a table or as inline text with other HTML.

Web server controls include traditional form controls such as buttons and text boxes as well as complex controls such as tables. They also include controls that provide commonly used form functionality such as displaying data in a grid, choosing dates, and so on.

When the Web Forms page runs, the Web server control is rendered on the page using appropriate HTML, which often depends not only on the browser type but also on settings that you have made for the control. For example, a TextBox control might render as an <INPUT> tag or a <TEXTAREA> tag, depending on its properties.
 
What is .NET?
Microsoft .NET is Microsoft's new Internet strategy. .NET was originally called Internet-based platform of NGWS (Next Generation Windows Services)

The Microsoft.NET strategy was presented by Microsoft officials (in June 2000) as:

  • .NET is Microsoft's new Internet and Web strategy
  • .NET is NOT a new operating system
  • .NET is a new Internet and Web based infrastructure
  • .NET delivers software as Web Services
  • .NET is a framework for universal services
  • .NET is a server centric computing model
  • .NET will run in any browser on any platform
  • .NET is based on the newest Web standards

.NET is built on the following Internet standards:
  • HTTP, the communication protocol between Internet Applications
  • XML, the format for exchanging data between Internet Applications
  • SOAP, the standard format for requesting Web Services
  • UDDI, the standard to search and discover Web Services
 
How can you control Validation Error Message Display for ASP.NET Server Controls?
Use ValidationSummary control included with Validation controls. You can use this control to summarize all the errors at the top of the page, or anywhere else.
 
What is the difference between Server.Transfer and Response.Redirect?
Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like: Response.Redirect("WebForm2.aspx") to send the user to another page.
Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer("WebForm2.aspx").

However, the Server.Transfer statement has a number of distinct advantages and disadvantages.

  • Transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster. But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.
  • Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.
  • The Server.Transfer method also has a second parameter - "preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to. For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").

So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and allows you to transfer the query string and form variables.
 
What base class do all Web Forms inherit from?
All Web Forms inherit from System.Web.UI.Page base class.
All .NET Objects inherit from System.Object base class.
 
What method do you use to explicitly kill a user session?
Session.Abandon: If a user requests a new page after the Abandon method is called, he or she is treated as a new user. The user is assigned a new session ID and all the items in session state previously associated with that user are removed from memory. The Abandon method is often used with sign-out pages.

If user stops surfacing in application, then session will terminate after 20 minutes (default time). We can change setting using Session.TimeOut property to any time.
 
How do you turn off cookies for one page in your site?
Sessions rely on cookies by default. Although all modern Web browsers support cookies, users may choose to turn off cookie support, or the client device (such as a WAP phone) may not support cookies. In these cases, the Session object will not work. You can work around this problem by embedding the Session ID in each URL. This technique is used widely by many Web sites, such as Amazon.com. ASP.NET now supports this "cookieless" method for supporting Sessions. To enable cookieless sessions, edit your application's web.config file and set the cookieless attribute to "true":
<sessionState mode="Inproc" cookieless="true" timeout="20" />

After altering the web.config file, when you load Webform1.aspx, the URL will look similar to the following (the URL is a single line):
http://localhost/StateManagement/(ymqpoo45lyfih455lcf2kvfp)/WebForm1.aspx

Note that the Session ID is now embedded within the URL, enclosed in parentheses. To request Webform2.aspx, change the URL to (all on one line):
http://localhost/StateManagement/(ymqpoo45lyfih455lcf2kvfp)/WebForm2.aspx

You should see the time in which Webform1.aspx is requested. However, if you request Webform2.aspx without the embedded Session ID (http://localhost/StateManagement/WebForm2.aspx), the state is lost and the ASP.NET framework issues a new Session Id.
 
How do you create a permanent cookie?
By creating a persistent cookie. A persistent cookie is similar to session cookie except the fact that a persistent cookie has a definite expiration date. To add a persistent cookie that will last the maximum amount of time, you can use the following statements:

Dim objCookie As New HttpCookie(“myPersistentCookie”, “Hello User!”)
objCookie.Expires = DateTime.MaxValue
Response.Cookies.Add(objCookie)
 
Which method do you use to redirect the user to another page without performing a round trip to the client?
Server.Transfer

When the ASP engine encounters a Response.Redirect method, it stops the processing of the current page and sends an HTTP redirection header (302 Redirect) to the client, informing it that the page it requested has moved and can be found at a different URL. When this response is sent to the browser, the browser requests the new URL and the ASP engine sends the new page to the client. Thus, the redirection of a page using Response.Redirect requires an extra client/server round trip.

Server.Transfer works differently than Response.Redirect. When the ASP engine encounters a Server.Transfer method on the page, it stops processing the page and sends the new page to the client in the response. That is, Server.Transfer substitutes the request for one page with another without involving an extra round trip between the server and the browser. In fact, as far as the browser is concerned, it received the page it originally requested.
 
Which control would you use if you needed to make sure the values in two different controls matched?
CompareValidator

Generally used for form validations, CompareValidator evaluates the value of an input control against a constant value or the value of another input control to determine whether the two values match the relationship specified by a comparison operator (less than, equal to, greater than, and so on).
 
What is a .NET DLL?
A dynamic-link library (DLL) is an executable file that acts as a shared library of functions. Dynamic linking provides a way for a process to call a function that is not part of its executable code. The executable code for the function is located in a DLL, which contains one or more functions that are compiled, linked, and stored separately from the processes that use them. DLLs also facilitate the sharing of data and resources. Multiple applications can simultaneously access the contents of a single copy of a DLL in memory.

Dynamic linking differs from static linking in that it allows an executable module (either a .dll or .exe file) to include only the information needed at run time to locate the executable code for a DLL function. In static linking, the linker gets all of the referenced functions from the static link library and places it with your code into your executable.

Using dynamic linking instead of static linking offers several advantages. DLLs save memory, reduce swapping, save disk space, upgrade easier, provide after-market support, provide a mechanism to extend the MFC library classes, support Multilanguage programs, and ease the creation of international versions.
 
How many classes can a single .NET DLL contain?
(a) One and only one  (b) Not more than 2  (c) Many
Many
 
Should validation (did the user enter a real date) occur server-side or client-side? Why?
“Did the user enter a real date” validation occurs client-side only because you can obtain date from client machine.

In general, ASP.NET Validation Controls automatically generate both client-side and server-side code. If a browser is capable of supporting JavaScript, client-side validation scripts are automatically sent to the browser. If a browser is incapable of supporting JavaScript, the validation routines are automatically implemented in server-side code.
 
What does the "EnableViewState" property do? Why would I want it on or off?
Automatic persistence of data is called ViewState. EnableViewState property gets or sets a value indicating whether the server control persist its view state, and the view state of any child controls it contains, to the requesting client.

On:
  • ViewState doesn’t require any server resources for its operation.
  • Form validation. Someone makes an error in the form and submits the form; you can display the error while redisplaying all the form info that the user has already entered.

Off:
  • When you don’t want to load lot of data in the hidden _VIEWSTATE form field that can significantly slow down the rendering of the page.
  • When you want to automatically reinitialize a control every time a page is loaded. E.g. <%@ Page EnableViewState="false" Language="vb" %>
  • You shouldn’t store any important data in the ViewState, as it is passed as plain text to the client, so anybody can tamper with the data.

Although ViewState is freely accessible in a hidden field called __VIEWSTATE, the view state information is not clear text. By default, a machine-specific authentication code is calculated on the data and appended to the view state string. The resulting text is then Base64 encoded only, but not encrypted. In order to make the view state more secure, the ASP.NET @Page directive supports an attribute called EnableViewStateMac whose only purpose is detecting any possible attempt at corrupting original data.
 
Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
There are events that fire in a certain order when a Web Form initializes and loads. There are also events that fire in response to user interaction in the browser with the rendered page. When you think about how a standard ASP or HTML is created and sent to a browser, you assume that everything is processed in a very linear, top-down fashion. A Web Form goes through the standard Load, Draw (Render), and Unload types of events. Throughout this process, different procedures within the class module are called. When a page is requested from a client browser; a DLL that encapsulates both the tags in the ASPX page, as well as the page code, is loaded and then processed.

The Global.asax file is similar to the Global.asa file in ASP, albeit that there are many more events available in ASP.NET. Also, Global.asax is compiled instead of interpreted as it is in ASP. You still have event procedures that fire within the Global.asax file when certain events happen on your Web site.

Application_Start:      Fires when the first user hits your web site.
Session_Start:            Fires when any new user hits your web site.

The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object.
 
What are ASP.NET Web Forms? How is this technology different than what is available though ASP (1.0-3.0)?
Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio® .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.
Web Forms are made up of two components: the visual portion (the ASPX file), and the code behind the form, which resides in a separate class file.
introwebforms_01

Web Forms and ASP.NET were created to overcome some of the limitations of ASP. These new strengths include:
  • Separation of HTML interface from application logic
  • A rich set of server-side controls that can detect the browser and send out appropriate markup language such as HTML
  • Less code to write due to the data binding capabilities of the new server-side .NET controls
  • Event-based programming model that is familiar to Microsoft Visual Basic® programmers
  • Compiled code and support for multiple languages, as opposed to ASP which was interpreted as Microsoft VB Scripting or Microsoft Jscript
  • Allows third parties to create controls that provide additional functionality
 
What is an assembly?
Assemblies are a fundamental part of programming with the .NET Framework. An assembly performs the following functions:
  • It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main).
  • It forms a security boundary. An assembly is the unit at which permissions are requested and granted.
  • It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly.
  • It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends.
  • It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies.
  • It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded.
  • It is the unit at which side-by-side execution is supported.

Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies.
 
Describe the difference between inline and code behind - which is best in a loosely coupled solution
Inline-code executes a statement or series of statements within the text contents of your ASP.NET page. This type of code begins with the characters <% and ends with the characters %>.

Code-behind is a method of dividing presentation content from the application logic. The code-behind file (application logic file) inherits from the Page class and the presentation file (.aspx file) inherits from the code-behind file. Because this hierarchy of inheritance exists, all the properties, methods, and events of the Page class are available in the code-behind file and all the properties, methods, and events of the code-behind file are available to the presentation file.

Code-behind will work best in a loosely coupled solution.
 
What is MSIL?
When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT compilers for each supported computer architecture, the same set of MSIL can be JIT-compiled and run on any supported architecture.

When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. This file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images. The presence of metadata in the file along with the MSIL enables your code to describe itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The runtime locates and extracts the metadata from the file as needed during execution.
 
What are some .Net options for maintaining session state? 
The different modes for maintaining <sessionState> element in the web.config file are:

Off
Indicates that session state is not enabled.
Inproc
Indicates that session state is stored locally in the server.
StateServer
Indicates that session state is stored in a state service process located remotely or potentially locally.
SqlServer
Indicates that session state is stored on the SQL Server database.

<sessionState> configures session state settings for the current application.
 
What are the .Net web authentication options and which one would generally be used for a secured/public site?
<authentication mode="Windows|Forms|Passport|None">
   <forms name="name"
                      loginUrl="url"
                      protection="All|None|Encryption|Validation"
                      timeout="30" path="/" >
                      requireSSL="true|false"
                      slidingExpiration="true|false">
      <credentials passwordFormat="Clear|SHA1|MD5">
         <user name="username" password="password"/>
      </credentials>
                 </forms>
   <passport redirectUrl="internal"/>
</authentication>

.NET Authentication options:
Attribute
Option
Description
mode
   
Controls the default authentication mode for an application.
   
Windows
Specifies Windows authentication as the default authentication mode. Use this mode when using any form of Microsoft Internet Information Services (IIS) authentication: Basic, Digest, Integrated Windows authentication (NTLM/Kerberos), or certificates.
   
Forms
Specifies ASP.NET forms-based authentication as the default authentication mode.
   
Passport
Specifies Microsoft Passport authentication as the default authentication mode.
   
None
Specifies no authentication. Only anonymous users are expected or applications can handle events to provide their own authentication.
 
 
How many languages .NET is supporting now?
When .Net was introduced it came with some 16 languages. VB.NET, C#, COBOL and PERL etc.
 
How .NET is able to support multiple languages?
A language should comply with the Common Language Runtime (CLR) standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call / use a function written in another language because CLR provides a common set of data types, that all languages use. So no matter what language you're in, an integer has the same meaning.
 
Can the validation be done in the server side? Or this can be done only in the client side?
The Validation controls automatically generate both client-side and server-side code. If a browser is capable of supporting JavaScript, client-side validation scripts are automatically sent to the browser. If a browser is incapable of supporting JavaScript, the validation routines are automatically implemented in server-side code.
 
How ASP .NET different from ASP?

Feature
ASP
ASP.NET
Objects Support
6 objects: (Response, Request, Server, Application, Session, ObjectContext) which are components that make web-development dynamic. The objects are interface based, not object based so are often called components.

Can be extended with COM objects or COM+ (including transactions) that can interact with ASP objects. Supports default interface COM programming, not multiple interfaces. COM and COM+ objects tend to need GUI tools that automate their creation.

Can consume COM and COM+ objects. Can be used to create objects that support interfaces and inheritance. Languages can inherit and override methods of objects created in different languages. These can be built with text editors and GUIs are a convenience, not a necessity.

Can make its components into SOAP listeners and proxies with trivial amounts of work by just setting a few attributes. The "guts" of the component glue and framework are not tied to Intel or Windows. The first release is Windows but porting to other computing environments is feasible.
Language Support
2 built-in script languages (Vbscript, Jscript) that are not compiled. Some 3rd party languages: Perl script, Python are also supported but not so robust and actually tend to crash the server.
3 built in compiled languages (have no scripting languages): VB.NET, C# and JS.NET.

 
Database Support
Database support via ADO which communicates with ODBC and OLEDB databases. Most database display is done through Recordsets and loops. Most database manipulation requires code coupled to back-end database that may fail if drivers are switched and needs to be written carefully.
Database support via ADO.NET which communicates with: ODBC and OLEDB databases, XML Streams, Binary Streams, but is loosely coupled so differences between database vendors do not ever affect programming model.
Database display never involves loops. Templates, grouped controls, Grids and many other declarative structures eliminate need for loops and flexibility is provided so programmer can control all interaction between templates declaratively.
Scalability
Scalability without work is limited because 2 of the core objects (session, application) don't scale on web-farms. Those objects must be replaced with home-brewed or commercial objects if that functionality is wanted on web farm. Scalability, multi-tier application building and transactional applications are possible to build but the programmer has few tools to make the task simple. It is just hard work and the programmer must have experience building such systems in the past to build an effective one today.
Sessions and all features were built with web-farms and supports "web gardens" (one computer with multiple CPUs) as assumed environment.

Several kinds of caching that reduce database access and code execution dramatically without requiring page-level changes.

Third Party Support
Some essential COM components that are needed to build websites (browser detection, etc.) -- Simple but useful. Most sites with complex needs will have to build or buy many COM components to complete tasks.
The .NET Framework can be hosted by unmanaged components that load the common language runtime into their processes and initiate the execution of managed code, thereby creating a software environment that can exploit both managed and unmanaged features. The .NET Framework not only provides several runtime hosts, but also supports the development of third-party runtime hosts.

The various Microsoft and third-party language compilers generate managed code that conforms to the CTS. This means that managed code can consume other managed types and instances, while strictly enforcing type fidelity and type safety.

The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object-oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components can integrate seamlessly with classes in the .NET Framework.
Browser Support
Browser Neutral.
Validators and built-in components use detection to render GUIs that behave consistently on a variety of browsers. ASP.NET has lots of facilities so that controls can detects the browser and renders the GUI very differently depending on what browser requests the page without having to expose this sensing to higher level callers.
Execution Environment
Tightly coupled to IIS.
The ASP engine is undocumented so that it cannot easily be extended and only low-level ISAPI filters can be created to accomplish tasks that ASP will not support easily.
 In "classic ASP" the first person to access a script compiles it but if the compiled script cache fills scripts are removed and if a machine physically restarts or a service restarts the compilation process is triggered by first user access.
Loosely coupled to IIS to ensure that it runs on any web server without requiring any IIS infrastructure.
Extremely extensible and high-level utilities called HTTP Handlers can accomplish the most complex of tasks without inheriting the entire ASP+ infrastructure or bloat.
Components and scripts have their compiled image written to disk so that compilation persists.

Deployment
Once an application is created its settings reside in the Windows Registry, Binary Metabase, MTS catalogs, and IIS settings. Transferring/copying an application from server is a complex tedious job with few automatic tools. Component registration is done via a variety of software packages all of which require a system administrator.
Huge complex applications store their settings and components in ASCII files and copying these ASCII files from server to server will result in a perfectly deployed application with no effort. There are no component registration tools because components do not make any registry entries nor do they need to be compiled before being copied to server. All configuration/security options rely in ASCII/XML files.
Versioning Approach
New versions of components required stopping and starting the server.
Once new component versions were deployed, old versions were replaced.
If a component is rewritten to have a new version, the next user accessing a page that accesses the new version runs on a new thread. The previous versions and new versions co-exist in memory since a fully running component live on a thread. Of course the ASP.NET worker process will eventually finish all user requests communicating with old component and quietly quit wasting memory on it.
ASPX or any programs can target any version of an assembly since side-by-side execution is supported.
Stability
Environment assumes code and libraries are written carefully and debugged and stress tested. Flaws in codes or component or memory leaks cause system deterioration and may require soft and hard reboots.
ASP+ worker process assumes all components and code are likely to crash, leak memory and have bad code (infinite loops, forgetting to advance Recordsets). The ASP+ worker process notices bad code and then isolates the thread the code is on, allows no new code to run on same thread and then destroys the thread and all bad code. If code leaks memory, ASP+ worker can create a new instance of itself to run requests and tear down the previous instance that has memory leaks without ever rebooting. 
Debugging
No debugging tools unless Visual Interdev is editor. Debugging tools are crude and have limits on how deep they can examine the system. 
Error trapping in all languages has severe limits. Vbscript has ON ERROR RESUME NEXT and not ON ERROR GOTO. Only JavaScript on server has TRY/CATCH.
Powerful debugging, millisecond timing and profiling are built-in. These can be done without GUIs.
All current page requests can be logged and inspected after the fact. Debugging can also be done with GUI tools that are not married to any editor specifically.
Error trapping at code level is easy because there are many error trapping directives (about 8 x as many as Classic ASP). Most languages support TRY/CATCH and several other robust error trapping styles.

 
How do you validate the controls in an ASP.NET page?
Validation controls:   Controls that incorporate logic to allow you to test a user's input. You attach a validation control to an input control to test what the user enters for that input control. Validation controls are provided to allow you to check for a required field, to test against a specific value or pattern of characters, to verify that a value lies within a range, and so on.

The syntax for creating a Validation server control is:
<asp:control_name id="some_id" runat="server" />

Validation Server Control
Description
CompareValidator
Compares the value of one input control to the value of another input control or to a fixed value
CustomValidator
Allows you to write a method to handle the validation of the value entered
RangeValidator
Checks that the user enters a value that falls between two values
RegularExpressionValidator
Ensures that the value of an input control matches a specified pattern
RequiredFieldValidator
Makes an input control a required field
ValidationSummary
Displays a report of all validation errors occurred in a Web page

 
What are HTML controls, Web controls, and server controls?

ASP.NET server controls derive directly or indirectly from System.Web.UI.Control. This base class belongs to the System.Web.UI namespace, which contains the elements common to all ASP.NET server controls. Three commonly used controls belong to System.Web.UI — Page, UserControl, and LiteralControl. While Page is important because every ASP.NET page is compiled to a Page control by the ASP.NET page framework, control developers generally do not instantiate Page or derive from Page. Control developers also generally do not work with UserControl. User controls are developed using the same programming model as ASP.NET pages and are saved as .ascx text files. Control developers use LiteralControl extensively, as it allows text to be encapsulated as a control.
The ASP.NET server controls that provide a user interface are organized into two namespaces — System.Web.UI.HtmlControls and System.Web.UI.WebControls. The HTML server controls map directly to HTML elements, while the Web server controls are richer and more abstract.
The following illustration shows the namespaces that contain ASP.NET server controls.

1

HTML server controls derive directly or indirectly from the base class System.Web.UI.HtmlControls.HtmlControl and map directly to HTML elements. HTML server controls are especially useful for migrating ASP applications to ASP.NET applications.

The following illustration shows the hierarchy of ASP.NET server controls in the System.Web.UI.HtmlControls namespace. These controls are called HTML server controls.

3

Most Web server controls derive directly or indirectly from the base class System.Web.UI.WebControls.WebControl. However, the four controls in the upper-right corner (Literal, PlaceHolder, Repeater, and Xml) derive from System.Web.UI.Control. The controls on the left map to HTML elements. The controls in the center are for validating form input. Also in the center are controls that provide rich functionality, such as the Calendar and the AdRotator controls. The controls that provide data-binding support are on the right.
You can develop a custom Web server control by extending an existing Web server control, by combining existing Web server controls, or by creating a control that derives from the base class System.Web.UI.WebControls.WebControl.

The following illustration shows the hierarchy of controls in the System.Web.UI.WebControls namespace. Controls in this namespace are called Web server controls.


2

 
How to manage pagination in an ASP.NET page?
You can manage pagination/paging by using DataGrid control. The DataGrid control has built-in support for paging through the records of a data source. You enable paging for a DataGrid by enabling the AllowPaging property and creating a subroutine to change the current page. The number of records displayed in a page is determined by the DataGrid control’s PageSize property. By default, this property has the value 10.

P.S. You can only allow paging only if a DataGrid control’s data source implements the ICollection interface. A DataReader doesn’t implement this interface, so you must use a DataTable instead.
 
Can the action attribute of a server-side <form> tag be set to a value and if not how can you possibly pass data from a form page to a subsequent page?
One of the biggest changes from ASP to ASP.NET is the postback process. By design, ASP.NET pages post form data back to themselves for processing. For most situations, this is an acceptable process. But if a page must post form data to another site or another ASP.NET page, this is impractical. The current ASP.NET postback process supports lots of ways to manage this process.

  • Use Server.Transfer() to send posted fields to another page. This has the unfortunate side effect of not changing the user's URL.
  • Pass the items on a querystring, bundling them manually and using Response.Redirect() to send the new querystring to another page. The querystring has both security and length issues.
  • Pass the items on a post. Create a custom function to read the current items and send them via an HTTP post.
  • Use an HTML form instead of a web form. Remove the runat="server" attribute from the Form tag. Unfortunately, the validator controls can no longer be used, and that is the main reason I decided to use a JavaScript solution.
  • Use a simple JavaScript function to alter the page behavior on the client.

The last technique using a simple client-side JavaScript is described here. The advantage of this is that it is quick and simple, especially for developers just starting out with ASP.NET or for simple applications. The one downside is that users can choose to operate their browser without JavaScript, thus negating this technique. If this is a serious concern for you, look into the third option listed above.

There are two problems to overcome when using JavaScript to change the posting behavior of ASP.NET. The first problem is the self-postback. JavaScript allows the action attribute of the HTML Form tag to be changed on the client. It is the content of the post that causes ASP.NET to have the most serious problems. When an ASP.NET page receives a post, it checks for a field called __VIEWSTATE (that's 2 underscore symbols) in the post. But, one thing the __VIEWSTATE field does contain is internal validation for ASP.NET. If you simply post the __VIEWSTATE field to a different ASP.NET page, than the page that filled the __VIEWSTATE field, ASP.NET will throw an exception: "The ViewState is invalid for this page and might be corrupted."

If we attempt to remove the data from the __VIEWSTATE field prior to a post with JavaScript, the same exception is thrown. So, in order to post to another ASP.NET page, the __VIEWSTATE field cannot be passed to the next ASP.NET page. JavaScript allows us to rename the __VIEWSTATE field and change the action attribute of the form tag.

In the HTML portion of our ASP.NET page, we need to include the JavaScript function, NoPostBack. It could reside in a separate file, but is included here in the page for simplicity.
<script language="javascript">
function noPostBack(sNewFormAction)
{ document.forms[0].action = sNewFormAction;
document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';}
</script>
The first line sets the form's action attribute to a new location that is passed to the function. The second line renames the __VIEWSTATE field. It can be called anything other than its original name or the name of your other form items. If you are trying to save bandwidth, you could also set the value of the __VIEWSTATE field to "". In the ASP.NET Page_Load function, only one line of code is necessary:
private void Page_Load(object sender, System.EventArgs e)
{ Submit.Attributes.Add("onclick", "noPostBack('secondform.aspx');"); }
This adds an onclick attribute to the Submit button, and in this attribute we are specifying the new page or location for the post. When the button is clicked, it calls the JavaScript function before the form post occurs, changing the default location from the page itself to somewhere else. If the data is posted to another ASP.NET form, simply handle the form items using Request.Form syntax:
private void Page_Load(object sender, System.EventArgs e)
{ Result.Text = Request.Form["SomeText"].ToString(); }

When dealing with Netscape 4 and a CSS-based layout, the JavaScript needs to adapt slightly. Each <div> is considered a layer, so you must address the layer specifically in the JavaScript. Assume the form is contained inside of a <div> named Content:
<div id="Content" name="Content"><
<form method="post" id="Form1" runat="server">
</form>
</div>
The JavaScript now needs to differentiate between Netscape 4 and the other DOM aware browsers. Check for document.layers to identify Netscape 4, and simply use the syntax appropriate for that browser:
<script language="JavaScript">
<!—
function noPostBack(sNewFormAction)
{ if(document.layers) //The browser is Netscape 4
{ document.layers['Content'].document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
document.layers['Content'].document.forms[0].action =  sNewFormAction; }
else //It is some other browser that understands the DOM
{ document.forms[0].action = sNewFormAction;
document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE'; } }
-->
</script>

 
Briefly describe the role of Global.asax.
Every ASP.NET application can contain a single-file named Global.asax in its root directory. This special file can be used to handle application wide events and declare application wide objects. The Global.asax file is not used to display content. If you request this file, you receive an error.

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules. The Global.asax file resides in the root directory of an ASP.NET-based application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class. The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it.

The ASP.NET Global.asax file can coexist with the ASP Global.asax file. You can create a Global.asax file either in a WYSIWYG designer, in Notepad, or as a compiled class that you deploy in your application's \Bin directory as an assembly. However, in the latter case, you still need a Global.asax file that refers to the assembly. The Global.asax file is optional. If you do not define the file, the ASP.NET page framework assumes that you have not defined any application or session event handlers.

When you save changes to an active Global.asax file, the ASP.NET page framework detects that the file has been changed. It completes all current requests for the application, sends the Application_OnEnd event to any listeners, and restarts the application domain. In effect, this reboots the application, closing all browser sessions and flushing all state information. When the next incoming request from a browser arrives, the ASP.NET page framework reparses and recompiles the Global.asax file and raises the Application_OnStart event.
 
What is the correct language to code ASP.NET pages with? Why?
C#
 
How would ASP and ASP.NET apps run at the same time on the same server?
Yes. But, ASP 3.0 applications are processed by the asp.dll ISAPI extension and ASP.NET pages are handled by aspnet_isapi.dll. An important consideration is that the two environments are separate. Session and Application state variables are not shared. ASP.NET and ASP 3.0 can exist side by side in a single web application. But, information must be manually passed between the two environments.
 
What do Option Explicit and Option Strict refer to?
Option Explicit Statement
By default, the Visual Basic .NET compiler enforces explicit variable declaration, which requires that you declare every variable before you use it. You can change the default values of Option Explicit and Option Strict on per project type basis, to ON or OFF.

Option Strict Statement
By default, the Visual Basic .NET compiler does not enforce strict data typing. Option Strict restricts implicit data type conversions to only widening conversions. Widening conversions explicitly do not permit any data type conversions in which data loss may occur and any conversion between numeric types and strings.

When you use the Option Strict statement, the statement must appear before any other code. In Visual Basic .NET, you can typically convert any data type to any other data type implicitly. Data loss can occur when the value of one data type is converted to a data type with less precision or with a smaller capacity. However, you receive a run-time error message if data will be lost in such a conversion. Option Strict notifies you of these types of conversions at compile time so that you can avoid them.

Option Strict also generates an error message in the following scenarios:
  • For any undeclared variable. This is because Option Strict also implies Option Explicit.
  • Late binding.

 
What's the difference between String and System.String?
String variables hold groups of Unicode characters.  A string can contain up to about 2 billion (2^31) Unicode characters.  We can assign string to a variable using double quotes. A string object is allocated on the heap.  When we assign one string variable to another string, we get two references to the same string in memory.

 System.String is a class that is specially designed to store a string, and allow a large number operation the string.  Because of the importance of this data type, C# has its own keyword and associated syntax to make it particularly easy to manipulate string using this class. CTS (Common Type System) have the System.String class which is a reference type.
 
How to do use unmanaged code in .NET?
The common language runtime (CLR) promotes the interaction of managed code with COM components, COM+ services, the Win32® API, and other types of unmanaged code. Data types, error-handling mechanisms, creation and destruction rules, and design guidelines vary between managed and unmanaged object models. To simplify interoperation between managed and unmanaged code and to ease the migration path, the CLR interoperation layer conceals the differences between these object models from both clients and servers.

Interoperability is bidirectional, which makes it possible to:
Call into unmanaged APIs from managed code
This can be done for both flat APIs (static DLL exports, such as the Win32 API, which is exposed from DLLs like kernel32.dll and user32.dll) and COM APIs (object models such as those exposed by Microsoft® Word, Excel, Internet Explorer, ActiveX® Data Objects (ADO) and so forth).

Expose managed APIs to unmanaged code
Examples of doing this include creating an add-in for a COM-based application like Windows Media® Player or embedding a managed Windows Forms control on an MFC form.

Three complementary technologies enable these managed/unmanaged interactions:
  • Platform Invoke (sometimes referred to as P/Invoke) enables calling any function in any unmanaged language as long as its signature is re-declared in managed source code. This is similar to the functionality that was provided by the Declare statement in Visual Basic® 6.0.

  • COM interop enables calling into COM components in any managed language in a manner similar to using normal managed components, and vice versa. COM interop is comprised of core services provided by the CLR, plus some tools and APIs in the System.Runtime.InteropServices namespace.

  • C++ interop (sometimes referred to as It Just Works (IJW)) is a C++-specific feature, which enables flat APIs and COM APIs to be used directly, as they have always been used. This is more powerful than COM interop, but it requires much more care. Make sure that you check the C++ resources before you use this technology.
 
What's the difference between dispose and finalize method?
VB.NET
Before releasing objects, the CLR automatically calls the Finalize method for objects that define a Sub Finalize procedure. The Finalize method can contain code that needs to execute just before an object is destroyed, such as closing files and saving state information. There is a slight performance penalty for executing Sub Finalize, so you should define a Sub Finalize method only when you need to release objects explicitly.

The Finalize destructor is a protected method that can be called only from the class it belongs to, or from derived classes. The system calls Finalize automatically when an object is destroyed, so you should not explicitly call Finalize from outside of a derived class's Finalize implementation. Unlike Class_Terminate, which executed as soon as an object was set to nothing, there is usually a delay between when an object loses scope and when Visual Basic .NET calls the Finalize destructor.

Visual Basic .NET allows for a second kind of destructor, named Dispose, which can be explicitly called at any time to release resources immediately. Class instances often control resources not managed by the CLR, such as Windows handles and database connections. To supplement garbage collection, your classes can provide a mechanism to actively manage system resources if they implement the IDisposable interface. IDisposable has one method, Dispose, which clients should call when they finish using an object. You can use the implementation of Dispose to release resources and perform tasks such as closing files and database connections. Unlike the Finalize destructor, the Dispose method is not called automatically. Clients of a class must explicitly call Dispose when you want to release resources.
 
Give overview of Garbage Collection and Finalize method in .NET.
The .NET Framework uses a system called reference-tracing garbage collection that periodically releases unused resources. Previous versions of Visual Basic use a different system called reference counting to manage resources. Although both systems perform the same function automatically, there are a few important differences.

The CLR periodically destroys objects when the system determines that such objects are no longer needed. Objects are released more quickly when system resources are in short supply, and less frequently otherwise. The delay between when an object loses scope and when the CLR releases it means that, unlike with objects in previous versions of Visual Basic, you cannot determine exactly when the object will be destroyed. In such a situation, objects are said to have non-deterministic lifetime. In most cases, non-deterministic lifetime does not change how you write applications, as long as you remember that the Finalize destructor may not execute immediately when an object loses scope.

Another difference between the garbage collection systems involves the use of ‘Nothing’. To take advantage of reference counting, programmers using previous versions of Visual Basic sometimes assign ‘Nothing’ to object variables in order to release the references those variables hold. If the variable holds the last reference to the object, the object's resources are released immediately. In Visual Basic .NET, while there may be cases in which this procedure is still valuable, performing it never causes the referenced object to release its resources immediately. The only time you should set a variable to ‘Nothing’ is when its lifetime is long relative to how long it takes the garbage collector to detect orphaned objects.
 
Does Global.asax page have code-behind file?
Yes



 Happy Programming ! !

If you have any query mail me to Sujeet.bhujbal@gmail.com     


Regards

Sujeet Bhujbal

------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------

0 comments :

Post a Comment