67
Master of Computer Application (MCA) – Semester V MC0081 – DOT Net Technologies Assignment Set – 1 1. Write about the Common Language Runtime Library of Dot Net. Answer: Common Language Runtime (CLR): The CLR is described as the "execution engine" of .NET. It provides the environment within which the programs run. It's this CLR that manages the execution of programs and provides core services, such as code compilation, memory allocation; thread management, and garbage collection. Through the Common Type System (CTS), it enforces strict type safety, and it ensures that the code is executed in a safe environment by enforcing code access security. The software version of .NET is actually the CLR version. Working of the CLR When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language (MSIL), which is a low-level set of instructions understood by the common language run time. This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL. Feature of the Common Language Runtime. The common language runtime manages memory; thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime. With regards to security, managed components are awarded varying degrees of trust, depending on a number of factors that include their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it is being used in the same active application. The runtime enforces code access security. For example, users can trust that an executable embedded in a Web page can play an animation on screen or sing a song, but cannot access their personal data, file system, or network. The security features of the runtime thus enable legitimate Internet-deployed software to be exceptionally featuring rich. The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self-describing. The

MC0081 - Answer

Embed Size (px)

Citation preview

Page 1: MC0081 - Answer

Master of Computer Application (MCA) – Semester V

MC0081 – DOT Net Technologies

Assignment Set – 1

1. Write about the Common Language Runtime Library of Dot Net.Answer: Common Language Runtime (CLR):The CLR is described as the "execution engine" of .NET. It provides the environment within which the programs run. It's this CLR that manages the execution of programs and provides core services, such as code compilation, memory allocation; thread management, and garbage collection. Through the Common Type System (CTS), it enforces strict type safety, and it ensures that the code is executed in a safe environment by enforcing code access security. The software version of .NET is actually the CLR version. Working of the CLR When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language (MSIL), which is a low-level set of instructions understood by the common language run time. This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL. Feature of the Common Language Runtime.The common language runtime manages memory; thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime. With regards to security, managed components are awarded varying degrees of trust, depending on a number of factors that include their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it is being used in the same active application. The runtime enforces code access security. For example, users can trust that an executable embedded in a Web page can play an animation on screen or sing a song, but cannot access their personal data, file system, or network. The security features of the runtime thus enable legitimate Internet-deployed software to be exceptionally featuring rich. The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self-describing. 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. In addition, the managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common application errors, memory leaks and invalid memory references.

The runtime also accelerates developer productivity. For example, programmers can write applications in their development language of choice, yet take full advantage of the runtime, the class library, and components written in other languages by other developers. Any compiler vendor who chooses to target the runtime can do so. Language compilers that target the .NET Framework make the features of the .NET Framework available to existing code written in that

Page 2: MC0081 - Answer

language, greatly easing the migration process for existing applications. While the runtime is designed for the software of the future, it also supports software of today and yesterday. Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs. The runtime is designed to enhance performance. Although the common language runtime provides many standard runtime services, managed code is never interpreted. A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it is executing. Meanwhile, the memory manager removes the possibilities of fragmented memory and increases memory locality-of-reference to further increase performance.

Finally, the runtime can be hosted by high-performance, server-side applications, such as Microsoft® SQL Server™ and Internet Information Services (IIS). This infrastructure enables you to use managed code to write your business logic, while still enjoying the superior performance of the industry's best enterprise servers that support runtime hosting.

2. With the help of a suitable example, explain the steps in compiling and running a C# program.

Answer:The “Hello C#” Program:

using System;class Hello{

public static void Main(){

Console.WriteLine(“Hello C#”);}

}

After entering the above code in an editor, you have to perform the following steps

Save the file as “Hello.cs”. “cs” is an extension to indicate C-Sharp like .java for a Java source file. You have to supply this extension while saving your file, otherwise the code will not compile correctly. The saved file will be of the extension .cs.txt.

Compile the code by giving the following command at the command prompt:

csc Hello.cs

If there are compile errors you will be prompted accordingly. Otherwise, you will be viewing a command prompt along with the copyright information as shown in below figure.

As a final step, you have to execute the program in order to view the final output. For that purpose, you have to simply give a command as shown below at the command prompt. See above figure. If everything goes on well, then you can be able to view the message “Hello C#” as shown in the figure above.

3. With the help of a suitable example explain the creation of a simple windows form based application.

Answer:

Page 3: MC0081 - Answer

To create a Windows Form: Start Visual Studio Create a Windows application called HelloWorld. From the Toolbox, drag a button control onto the form Click the button on select it. In the Properties window, set the Textproperty to SayHello.

To write the code for your application

Double-click the button to add an event handler for the Click event. The code Editor will open with the insertion point placed within the event handler.

Insert the following code:

VB C# C++ F# Jscript Copy

MessageBox.Show(“Hello, World!”);

VBC#C++F#Jscript Copy

This language is not supported or no code example is available.

J# Copy

MessageBox.Show("Hello, World!");

VBC# C++ F# JScript  Copy 

This language is not supported or no code example is available.

To test your application

Press F5 to run the application When your application is running, click the button and verify that “Hello, World!” is

shown. Close the Windows Form to return to Visual Studio.

4. Describe ASP.NET Architecture.Answer:

This section provides an overview of the ASP.NET infrastructure and subsystem relationships, as they relate to the subject of security. The following illustration shows the relationships among the security systems in ASP.NET

As the illustration shows, all Web clients communicate with ASP.NET applications through IIS. IIS deciphers and optionally authenticates the request. If allow Anonymous is turned on, no authentication occurs. IIS also finds the requested resource ( such as an ASP.NET application ), and, if the client is authorized, returns the appropriate resource.In addition to the built-in ASP.NET security features, an ASP.NET application can use the low-level security features of the .NET framework.Integrating with IIS

Page 4: MC0081 - Answer

This release of ASP.NET uses IIS 5.0 as the primary host environment. When considering ASP.NET authentication, you should understand the interaction with IIS authentication services.IIS always assumes that a set of credentials maps to a Windows NT account and uses them to authenticate a user. There are three different kinds of authentication available in IIS 5.0: basic, digest, and Integrated Windows Authentication (NTLM or Kerberos). You can select the type of authentication to use in the IIS administrative services. For more information on IIS authentication, see the IIS documentation.

If you request a URL containing an ASP.NET application, the request and authentication information are handed off to the application. ASP.NET provides the two additional types of authentication described in the following table.

ASP.NET authentication provider

Description

Forms authentication A system by which unauthenticated requests are redirected to an HTML form using HTTP client-side redirection. The user provides credentials and submits the form. If the application authenticates the request, the system issues a form that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the form in the request headers; they are authenticated and authorized by an ASP.NET handler using whatever validation method the application developer specifies.

Passport authentication

Centralized authentication service provided by Microsoft that offers a single log on and core profile services for member sites.

Using ASP.NET Configuration Files

ASP.NET configuration, of which security is a part, has a hierarchical architecture. All configuration information for ASP.NET is contained in files named Web.config and Machine.config. Web.config can be placed in the same directories as the application files. The Machine.config file is in the Config directory of the install root. Subdirectories inherit a directory's settings unless overridden by a Web.config file in the subdirectory. In a Web.config file, there are sections for each major category of ASP.NET functionality. To see an example of the way in which the hierarchical configuration system works for security see Hierarchical Configuration Architecture

The security section of a Web.config file is organized as follows:

<authentication mode = " [ Windows/Forms/Passport/None ] "> <forms name = " [ name ] " loginUrl = " [ url ] " > <credentials passwordFormat = " [ Clear, SHA1, MD5 ] "> <user name = " [ UserName ] " password = " [ password ] " /> </credentials> </forms> <passport redirectUrl = "internal" /></authentication>

<authorization> <allow users = " [ comma separated list of users ] " roles = " [ comma separated list of roles ] " /> <deny users = " [ comma separated list of users ] " roles = " [ comma separated list of roles ] " /></authorization>

Page 5: MC0081 - Answer

<identity impersonate = " [ true/false ] " />

The default settings for these elements are shown in the following table.

Default Value Comment<allow roles= > No default value<allow users = "*"> All<authentication mode = "Windows"> The authentication mode cannot be set

at a level below the application root directory.

<credentials passwordFormat = "SHA1">

The hashing algorithm to be used on passwords.

<deny roles = ""> Empty<deny users = ""> Empty<forms loginUrl = "login.aspx"> If you set the mode to forms, and if

the request does not have a valid form, this is the URL to which the request is directed for a forms-based logon.

<forms name = ".ASPXAUTH"> Forms name.<forms path = "/"> Path.<forms protection = "type"> Type= [ All|None|Encryption|

Validation ] <forms timeout = "30"> Timeout in seconds.<forms validation = "?"> True or false.<identity impersonate = "false"> Impersonation is disabled by default.<passport redirectUrl = "internal" If you set the mode to passport, and if

the requested page requires authentication but the user has not logged on with Passport, then the user will be redirected to this URL.

<user name = ""> Empty<user password = ""> Empty

There are three major subsections: authentication, authorization, and identity. The values for each of the elements are usually set by overriding this section of the computer-level configuration file with a similar section in an application configuration file placed in the application root. All subdirectories automatically inherit those settings. However, subdirectories can have their own configuration files that override other settings

5. Describe the anatomy of an ASP.NET Application. Create a new ASP.Net Web Application. This creates an application with a Default.aspx

page, a standard web.config file, and adds the initial references to the project.

Add references to System.Web.Abstractions.dll, System.Web.Routing.dll and System.Web.Mvc.dll, all of them can be found at c:\Program Files\Microsoft ASP.NET\ASP.NET MVC Beta\Assemblies folder.

Use the MvcHttpHandler to handle MVC requests. Open the code-behind file of Default.aspx (default.aspx.cs) and in the Page_Load method, process the request in MVC style:

Page 6: MC0081 - Answer

protected void Page_Load(object sender, EventArgs e){

  HttpContext.Current.RewritePath(Request.ApplicationPath);  IHttpHandler httpHandler = new MvcHttpHandler();  httpHandler.ProcessRequest(HttpContext.Current);

}

Add a Global Application Class (global.asax), and in the Application_Start method, map the route to the home controller.

protected void Application_Start(object sender, EventArgs e){

RouteTable.Routes.MapRoute("Default Route","{controller}/{action}",new{controller = "Default", action="Index" });

} In order to use the MapRoute and IgnoreRoute methods, you should add a using directive

to use the namespace System.Web.Mvc, since those are extension methods. The MapRoute method takes a name of a route as the first parameter, a URI template as the second, and default values as the third. Notice that the default values object should have properties that correspond the names of the properties in the URI template. The route above maps an incoming Url to a combination of a controller and an action.

Create a default controller. Add a class to the web application under a Controllers folder and name it DefaultController. Notice the naming convention for it: Default comes from the route default value and the controller is just a suffix in the convention

This class should inherit from System.Web.Mvc.Controller class, and should contain a public method with a name the corresponds to an action. Since the default action is Index (taken from the default route), then the class should look like this:

public class DefaultController : Controller{

public string Index(){

return "Hello, world";}

}

Run the application, and navigate to the application directory ( “/” ), what you should get is the response “hello, world”.

Page 7: MC0081 - Answer

But, If you try to navigate to the Index action in the Default controller (/Default/Index), you will get an error.

Add the Url Routing Module. Open the web.config, and locate the <httpModules> tab in the system.web section. There, register the Url Routing Module:

<httpModules><add name="UrlRoutingModule"

type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /></httpModules>

Run the application and navigate to the Index action in the Default Controller. Now, you should get the same response as earlier

Return a view as the result of the Index action. Change the return value of the Index method in the default controller to be of type ActionResult. There are several types of results we can return (such as JosnResult, ContentResult etc.) but in this sample we will return a ViewResult, by calling the View method.

Page 8: MC0081 - Answer

public ActionResult Index(){

return View();}

Create a view that corresponds to this action. When called parameterless, the View method will look for a view whose name is equals to the name of the action, inside a folder the corresponds to the name of the controller. Create a new ASP.Net Form called Index.aspx inside Views\Default\ folder.

In order to make this an MVC View, open the code behind file (Index.aspx.cs) and change the class to inherit from System.Web.Mvc.ViewPage.

Edit the page (in design mode or source mode) and add a greeting message:

<body><form id="form1" runat="server">

<div><h1>Hello, world</h1>

</div></form>

</body>

Run the application and you should receive the response from the View we’ve just created. The routing engine called the Index action in the Default controller, which returned the Index.aspx view.

Display data in the View. Open the controller, and in the Index method, add data to the ViewData dictionary:public ActionResult Index(){

ViewData["name"] = "Guy";return View();

}Now, in the view markup, use that data in the greeting line:<body>

<form id="form1" runat="server"><div>

<h1>Hello, <%= ViewData["name"] %></h1></div>

</form></body>

Run the application and receive a greeting message bounded to the data that the controller has added to the dictionary.

Page 9: MC0081 - Answer

In this post I build an ASP.Net MVC application from scratch in order to understand the anatomy of an ASP.Net MVC application and the magic behind this framework. This understanding can help me with adding MVC capabilities to my existing web applications as well

6. Describe State Management in ASP.NETAnswer:

Types of State ManagementThere are 2 types State Management:

1. Client – Side State Management

This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:

A. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

B. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

C. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

D. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

E. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL

2. Server – Side State Management

A. Application State - Application State information is available to all pages, regardless of which user requests a page.

B. Session State – Session State information is available to all pages opened by a user during a single visit. Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties

Implementation ProcedureClient – Side State Management

Page 10: MC0081 - Answer

View State: The View State property provides a dictionary object for retaining values between multiple requests for the same page. When an ASP.NET 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. If the data is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields. The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" />

Encrypting of the View State: You can enable view state encryption to make it more difficult for attackers and malicious users to directly read view state information. Though this adds processing overhead to the Web server, it supports in storing confidential information in view state. To configure view state encryption for an application does the following

<Configuration> <system.web>

<pages viewStateEncryptionMode="Always"/> </system.web> </configuration>

Alternatively, you can enable view state encryption for a specific page by setting the value in the page directive, as the following sample demonstrates:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ViewStateEncryptionMode="Always"%>

View State is enabled by default, but if you can disable it by setting the EnableViewState property for each web control to false. This reduces the server processing time and decreases page size. Reading and Writing Custom View State Data: If you have a value that you’d like to keep track of while the user is visiting a single ASP.NET Web page, adding a custom value to ViewState is the most efficient and secure way to do that. However, ViewState is lost if the user visits a different Web page, so it is useful only for temporarily storing values. Example: Determine the time of last visit to the page

// Check if View State object exists, and display it if it does

If (ViewState ["lastVisit"]!= null)

Label1.Text = (string)ViewState["lastVisit"]; else

Label1.Text = "lastVisit ViewState not defined.";

// Define the ViewState object for the next page view ViewState.Add("lastVisit", DateTime.Now.ToString());

Control State: If you create a custom control that requires ViewState, you can use the ControlState property to store state information for your control. ControlState allows you to persist property information that is specific to a control and cannot be turned off like the ViewState

Page 11: MC0081 - Answer

property. To use control state in a custom control, your control must override the OnInit method and call the Register-RequiresControlState method during initialization and then override the SaveControl-State and LoadControlState methods.

Hidden fields: ViewState stores information in the Web page using hidden fields. Hidden fields are sent back to the server when the user submits a form; however, the information is never displayed by the Web browser (unless the user chooses to view the page source). ASP.NET allows you to create your own custom hidden fields and store values that are submitted with other form data. A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. You can use hidden fields only to store information for a single page, so it is not useful for storing session data. If you use hidden fields, you must submit your pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which happens if the user clicks a link). Unlike view state data, hidden fields have no built-in compression, encryption, hashing, or chunking, so users can view or modify data stored in hidden fields.

Cookies: Web applications can store small pieces of data in the client’s Web browser by using cookies. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary). The most common use of cookies is to identify a single user as he or she visits multiple Web pages.

Reading and Writing Cookies:

A Web application creates a cookie by sending it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request.

Create a cookie -> add a value to the Response. Cookies HttpCookieCollection.

Read a cookie -> read values in Request.Cookies.

Example:

// Check if cookie exists, and display it if it does

if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains client-side script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);

else Label1.Text = "No value defined";

// Define the cookie for the next visit

Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

If you do not define the Expires property, the browser stores it in memory and the cookie is lost if the user closes his or her browser.

To delete a cookie, overwrite the cookie and set an expiration date in the past. You can’t directly delete cookies because they are stored on the client’s computer.

Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site with a different hostname. You can control a cookie’s scope to either limit the scope to a specific folder on

Page 12: MC0081 - Answer

the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates:

Example:

Response.Cookies["lastVisit"].Path = "/Application1";

Through this the scope is limited to the “/Application1” folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement:

Example: Response.Cookies[“lastVisit”].Domain = “Contoso”;

Storing Multiple Values in a Cookie:

Though it depends on the browser, you typically can’t store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates:

Example:

Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();

Response.Cookies["info"]["firstName"].Value = "Tony";

Response.Cookies["info"]["border"].Value = "blue";

Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);

Running the code in this example sends a cookie with the following value to the Web browser:

(visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue)

Query Strings: Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. A typical query string might look like the following real-world example:

http://support.microsoft.com/Default.aspx?kbid=315233

In this example, the URL identifies the Default.aspx page. The query string (which starts with a question mark [?]) contains a single parameter named “kbid,” and a value for that parameter, “315233.” Query strings can also have multiple parameters, such as the following real-world URL, which specifies a language and query when searching the Microsoft.com Web site:

http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=hello+world

Limitations for Query Strings:

A. Some Browsers and client devices impose a 2083 – character limit on the length of the URL.B. You must submit the page using an HTTP GET command in order for query string values to be

available during page processing. Therefore, you shouldn’t add query strings to button targets in forms.

Page 13: MC0081 - Answer

C. You must manually add query string values to every hyperlink that the user might click.

Example:

Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) +

", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) +

", Page: " + Server.HtmlEncode(Request.QueryString["page"]);

Server - Side State Management:

Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted.

ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:

Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.

Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.

Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.

Session State: ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary.

You can use session state to accomplish the following tasks: Uniquely identify browser or client-device requests and map them to individual session

instances on the server. This allows you to track which pages a user saw on your site during a specific visit.

Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information.

Raise appropriate session management events. In addition, you can write application code leveraging these events.

ASP.NET session state supports several different storage options for session data:

A. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer.

B. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state

Page 14: MC0081 - Answer

available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.

C. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.

D. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider.

E. Off Disables session state. You should disable session state if you are not using it to improve performance.

Advantages

Advantages of Client – Side State Management: Better Scalability: With server-side state management, each client that connects to the Web

server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management: Better security: Client-side state management information can be captured (either in transit

or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server

7. Describe the following:Answer:

Importance of ADO.Net o ADO.NET is a set of computer software components that programmers can use to

access data and data services. It is a part of the base class library that is included with the Microsoft .NET Framework. It is commonly used by programmers to access and modify data stored in relational database systems, though it can also access data in non-relational sources. ADO.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology, but was changed so extensively that it can be considered an entirely new product.

Page 15: MC0081 - Answer

o Functionality exists in the Visual Studio IDE to create specialized subclasses of the DataSet classes for a particular database schema, allowing convenient access to each field through strongly-typed properties. This helps catch more programming errors at compile-time and makes the IDE's Intellisense feature more beneficial.

Entity Framework

o ADO.NET Entity Framework is a set of data-access APIs for the Microsoft .NET Framework, similar to the Java Persistence API, targeting the version of ADO.NET that ships with .NET Framework 4.0. ADO.NET Entity Framework is included with .NET Framework 4.0 Service Pack 1 and Visual Studio 2010, released on January 2010. An Entity Framework Entity is an object which has a key representing the primary key of a logical datastore entity. A conceptual Entity Data Model (Entity-relationship model) is mapped to a datastore schema model. Using the Entity Data Model, the Entity Framework allows data to be treated as entities independently of their underlying datastore representations.

o Entity SQL, a SQL-like language, serves for querying the Entity Data Model (instead of the underlying datastore). Similarly, LINQ extension LINQ to Entities provides typed querying on the Entity Data Model. Entity SQL and LINQ to Entities queries are converted internally into a Canonical Query Tree which is then converted into a query understandable to the underlying datastore (e.g. into SQL in the case of a relational database). The entities can use their relationships, with their changes committed back to the datastore.

Data Access Scenarios

Following are five data access scenarios that are more complex than simple Select queries. Each one is discussed in a succeeding topic. First, an RDO approach to the problem is shown, followed by the ADO solution so that you can compare how each is accomplished.

Executing a Parameter Query Performing a Parameter-Driven Stored Procedure Running a Stored Procedure That Returns Multiple Resultsets Performing an Action Query Running an Optimistic Batch Query

Executing a Parameter Query

RDO

The procedure below illustrates a method for performing a parameterized Select query: that is, a SELECT statement that requires one or more parameters. This process is done in two steps:

1. Build a query that expects a parameter, pass in the first parameter, then perform the query.

2. Perform the query again with new parameters.

The first time the query is called, RDO attempts to create a new RDO query object. Since the object is appended to the rdoConnection object’s rdoQueries collection, you can reference it each time the procedure is called. Each subsequent time the procedure is called, the Refresh method re-executes the query. This technique builds a temporary stored procedure (SP) behind the scenes that is referenced by the Requery method. The temporary SP is dropped when the connection is closed.

Private Sub ParmQueryButton_Click()

Dim Qy As New rdoQueryDim rs As rdoResultsetStatic FirstTime As BooleanIf cn.rdoQueries.Count = 0 Then

Page 16: MC0081 - Answer

FirstTime = True sql = "select * from authors where year_born = ?" Set Qy = cn.CreateQuery("Pq", sql) End If

Qy(0) = QueryParam.Text If FirstTime Then Set rs = Qy.OpenResultset() FirstTime = False Else rs.Requery End If rdoGrid1.ShowData rs rs.Close End Sub

ADO

This procedure is designed to perform a table-access query that accepts a parameter. You use the "?" character (as in the previous RDO example) to indicate where the parameter is to be placed. In this case, though, you don't create an rdoQuery object that is kept in a collection off the rdoConnection object; you instead use a stand-alone ADO Command object created (and scoped) earlier. The first time through, you set up the Command properties, and each time thereafter, you simply execute the command after having changed the parameter.

ADO gives you a lot of flexibility here—more, in some cases than RDO. If you tell ADO everything it needs to know about a query, it won't have to perform informational queries against the database to get missing information, so queries run faster.

Note   You don’t have to build the ADO Parameters collection in code, since it's automatically created for you just like when you use RDO. However, it is possible to do so, and doing so can improve performance, at the cost of a little code complexity. If you elect to do it, make sure that the Command is associated with an open connection so ADO can query the service provider (and the server) for the parameter's description.

To run the query and create the resultset, use the Execute method on the Command object.

Private Sub ParmQueryButton_Click()if Cmd.CommandText = "" Then

Cmd.ActiveConnection = cn With Cmd .CommandText = "select * from authors where year_born = ?" .CommandType = adCmdText .CommandTimeout = 15 End With

‘The following section of code is not required,'but can make execution faster. It eliminates the need'for ADO to fetch the parameter metrics from the server.

With Parm .Type = adInteger .Size = 4 .Direction = adParamInput .Value = QueryParam.Text Cmd.Parameters.Append Parm End With End If

Cmd.Parameters(0).Value = QueryParam.Text Set rs = Cmd.Execute() ADOGrid1.ShowData rs rs.Close

Page 17: MC0081 - Answer

End Sub

Performing a Parameter-Driven Stored Procedure

RDO

Since many client/server applications depend heavily on stored procedures (SP), a data access interface should be able to perform them quickly and efficiently. Stored procedures, however, can be tricky to handle. In some cases, stored procedures require management of OUTPUT and return status values and other, more conventional arguments. In addition, an SP can return several complex resultsets, including PRINT or RAISERROR statement return values. In some cases, it's better to create complex SPs, while in others it’s better and easier to keep SPs simpler and more modular and use Visual Basic to tie them together.

The code below shows the RDO approach to these problems. First, it performs a simple parameter-based SP and shows the results in the grid. Some accommodations are made to the subsequent ADO design, and these are noted. It uses the same connections established in the earlier examples.

Note that the code requires us to include a correct ODBC "Call" statement. Again, this is not necessary in the UserConnection designer, but it’s essential in the RDO code-based approach. Here, you use the stand-alone rdoQuery object and assign the already open Connection to it. The rdoQuery object can then be used in subsequent calls to handle a parameter query.

Note also that the code does not attempt to refer to the return status argument. This value is not available until the resultset is fully populated; only then does SQL Server return this value.

Private Sub RunSPButton_Click() Dim Qy As New rdoQuery Dim rs As rdoResultset sql = "{? = Call AuthorByYearBorn (?,?)}" Set Qy.ActiveConnection = cn Qy.sql = sql Qy.rdoParameters(0).Direction = rdParamReturnValue Qy(1) = "1947" Qy(2) = "1948" Set rs = Qy.OpenResultset() rdoGrid1.ShowData rs ShowRows = rs.RowCount rs.CloseEnd Sub

ADO

ADO has a lot of flexibility when it comes to performing stored procedures. But this flexibility comes at the cost of more code. As with the previous example ("Performing a Parameter Query"), it's possible to build your own ADODB Parameters collection. In this case, you’re performing a simple two-argument SP, "AuthorByYearBorn", that returns a small resultset. Note that although ADO allows you to create your own parameters, it's not necessary to do so.

Note   ADO collections are 0-based to match DAO. RDO collections are 1-based.

Private Sub RunSPButton_Click() Dim Qy As New ADODB.Command Dim Parm As New ADODB.Parameter Dim Parm2 As New ADODB.Parameter

Set Qy.ActiveConnection = cn Qy(0)="1947" Qy(1)="1948"

Page 18: MC0081 - Answer

Qy.CommandType = adCmdStoredProc Qy.CommandText = "AuthorByYearBorn"

Set rs = Qy.Execute(ShowRows) ADOGrid1.ShowData rsEnd Sub

Running a Stored Procedure That Returns Multiple Resultsets

RDO

This example illustrates how to perform a query that returns more than one resultset. It’s common for a stored procedure to return more than a single set of rows or a resultset that contains results from an action query. As a result, your code must deal with each of the resultsets individually, or else you won’t be able to use the product of your query. In RDO, you use the MoreResults method to step through the resultsets one at a time. Each call to MoreResults closes the current resultset and moves to the next (if there is one).

Private Sub MultipleRSButton_Click() sql = "Select * from Authors Where year_born is not null; " _ & "Select * from Authors where year_born is null" Set rs = cn.OpenResultset(sql) rdoGrid1.ShowData rs

i = MsgBox("Ready for next results?", vbYesNoCancel) If i = vbYes Then If rs.MoreResults Then rdoGrid1.ShowData rs End If End IfEnd Sub

ADO

The following code illustrates how to handle SPs that return multiple resultsets in ADO. ADO’s approach is different from the RDO approach in that ADO uses the NextRecordset method in which you assign the next recordset in the batch to an ADO Recordset object. The next recordset read doesn't overwrite the first one, as it does in RDO. ADO also allows for multiple recordsets, if the data provider supports it.

Private Sub MultipleRSButton_Click() Dim rs As New ADODB.Recordset sql = "Select * from Authors Where year_born is not null; " _ & "Select * from Authors where year_born is null" rs.Open sql, cn Do i = MsgBox("Ready for results?", vbYesNoCancel) If i = vbYes Then ADOGrid1.ShowData rs Set rs = rs.NextRecordset End If Loop Until rs.State = adStateClosedEnd Sub

Page 19: MC0081 - Answer

Performing an Action Query

RDO

In case your application needs to manipulate tables directly, or perform a maintenance operation (like SQL Server’s DBCC functions), you can use the Execute method to run the query directly. In this case, you don’t need ODBC or SQL Server to create a temporary SP to run the query as it’s only being done once. (If this were a regular operation, it would be more efficient to create an SP to do it.) Note that you can use the RowsAffected property to find out the number of rows affected by this query.

Private Sub ExecuteButton_Click() sql = "Begin Transaction " _ & " Update Authors " _ & " set Year_Born = 1900 where year_born is null" _ & " rollback transaction" Screen.MousePointer = vbHourglass cn.Execute sql, rdExecDirect ShowRows = cn.RowsAffected Screen.MousePointer = vbDefaultEnd Sub

ADO

When you need to perform an action query, you can take advantage of the Execute method in ADO. In this case, you have to set a few more properties than you do in RDO, but these properties improve data access performance. This is because ADO doesn’t have to poll the server to determine what to do, or how to handle the query. Note that the new output argument for the Execute method returns the number of rows affected. Generally, you don’t see Visual Basic using arguments passed back to the application; just arguments passed to the object interface.

Private Sub ExecuteButton_Click() Dim Qy As New ADODB.Command Dim Rows As Long sql = "Begin Transaction " _ & " Update Authors " _ & " set Year_Born = 1900 where year_born is null" _ & " rollback transaction" Qy.ActiveConnection = cn Qy.CommandText = sql Qy.CommandType = adCmdText Qy.Execute Rows MsgBox Rows & " rows would have been affected", vbInformationEnd Sub

Running an Optimistic Batch Query

RDO

The following code demonstrates a query that can be used to drive a subsequent "optimistic batch update" operation. In this case, you fetch a resultset using the ClientBatch cursor library and save the bookmarks for each row fetched. When the user chooses a row in the grid (where the rows are displayed), the code prompts the user for a new value and writes it to the resultset. The changes are not made to the data, however, until you perform the BatchUpdate method.

Private Sub BatchOpsButton_Click() Dim rs As rdoResultset sql = "Select * from Authors where year_born is null" rdoEnvironment.CursorDriver = rdUseClientBatch

Page 20: MC0081 - Answer

cnB.QueryTimeout = 45 Set rs = cnB.OpenResultset(sql, rdOpenStatic, rdConcurBatch) rs.MoveLast: rs.MoveFirst ReDim bms(rs.RowCount + 1) As Variant Do Until rs.EOF bms(i) = rs.Bookmark i = i + 1 rs.MoveNext Loop rs.MoveFirst rdoGrid1.ShowData rsEnd Sub

Performing an Update Operation Based on User Input

The following code demonstrates how to gather user input (in this case, author age), and then use this information to update the database in a batch update operation:

Private Sub rdoGrid1_Click() Dim rs As rdoResultset Dim NewValue As Integer NewValue = InputBox("Enter new age -- 1900 to 1997", "Author Age", _ "1960") rs.Bookmark = bms(rdoGrid1.Row) rs.Edit rs!Year_Born = NewValue rs.Update Changes = Changes + 1 i = MsgBox("Commit all " & Changes & " changes?", vbYesNoCancel) Select Case i Case vbYes rs.BatchUpdate Changes = 0 Case vbNo Exit Sub Case vbCancel Changes = 0 i = MsgBox("Cancel just this change (Yes) or all " & Changes & _ " made so far (No)?", vbYesNo) If i = vbYes Then rs.CancelBatch (True) Else rs.CancelBatch End If End SelectEnd Sub

ADO

In this batch operation, note that the routine used to change the chosen row in the R/W resultset doesn't require starting an "Edit" session. To achieve the same effect as the previous RDO example, simply change the contents of a field and use the Update method to make the changes to the database.

Private Sub BatchOpsButton_Click() sql = "Select * from Authors where year_born is null" rs.Open sql, cnB, adOpenStatic, adLockBatchOptimistic rs.MoveLast: rs.MoveFirst ReDim bms(rs.RecordCount + 1) As Variant Do Until rs.EOF

Page 21: MC0081 - Answer

bms(i) = rs.Bookmark i = i + 1 rs.MoveNext Loop rs.MoveFirst ADOGrid1.ShowData rs rs.CloseEnd Sub

Private Sub ADOGrid1_Click() Dim NewValue As Integer NewValue = InputBox("Enter new age -- 1900 to 1997", "Author Age", _ "1960") rs.Bookmark = bms(ADOGrid1.Row) rs!Year_Born = NewValue rs.Update Changes = Changes + 1 i = MsgBox("Commit all " & Changes & " changes?", vbYesNoCancel) Select Case i Case vbYes rs.UpdateBatch Changes = 0 Case vbNo Exit Sub Case vbCancel Changes = 0 i = MsgBox("Cancel just this change (Yes) or all " & Changes & _ " made so far (No)?", vbYesNo) If i = vbYes Then rs.CancelBatch (True) Else rs.CancelBatch End If End SelectEnd Sub

Disconnected ArchitecturesAccording to ADO.net, Dataset is said to be disconnected module and datareader is said to be connected module.In disconnected module, the whole data is obtained at one stretch and the modification is doen to the local table. In connected module, Only one row is obtained each time from the database.

ADO and ADO.NET are different in several ways:o ADO works with connected data. This means that when you access data, such as viewing

and updating data, it is real-time, with a connection being used all the time. This is barring, of course, you programming special routines to pull all your data into temporary tables.

o ADO.NET uses data in a disconnected fashion. When you access data, ADO.NET makes a copy of the data using XML. ADO.NET only holds the connection open long enough to either pull down the data or to make any requested updates. This makes ADO.NET efficient to use for Web applications. It's also decent for desktop applications.

o ADO has one main object that is used to reference data, called the Recordset object. This object basically gives you a single table view of your data, although you can join tables to create a new set of records. With ADO.NET, you have various objects that allow you to access data in various ways. The DataSet object will actually allow you to store the relational model of your database. This allows you to pull up customers and their orders, accessing/updating the data in each related table individually.

o ADO allows you to create client-side cursors only, whereas ADO.NET gives you the choice of either using client-side or server-side cursors. In ADO.NET, classes actually handle the

Page 22: MC0081 - Answer

work of cursors. This allows the developer to decide which is best. For Internet development, this is crucial in creating efficient applications.

o Whereas ADO allows you to persist records in XML format, ADO.NET allows you to manipulate your data using XML as the primary means. This is nice when you are working with other business applications and also helps when you are working with firewalls because data is passed as HTML and XML

8. Describe the ASP.NET Security Model.Answer:

ASP.NET SecurityFigure 2 shows the relationship between IIS and ASP.NET. When IIS receives a request for a file

registered to ASP.NET (for example, an ASPX file), it hands the request off to an ISAPI DLL named

Aspnet_isapi.dll. Aspnet_isapi.dll runs in the same process as IIS—that is, inside Inetinfo.exe.

ASP.NET applications run in a separate process named Aspnet_wp.exe. Aspnet_isapi.dll forwards

requests to Aspnet_wp.exe using a named pipe. When the request reaches the worker process, it is

assigned to a specific application executing in a specific AppDomain. Once inside an AppDomain,

the request travels through the ASP.NET HTTP pipeline, where it is examined by various HTTP

modules and ultimately processed by the HTTP handler that corresponds to the resource type

requested. Machine.config contains the master list that maps file types to HTTP handlers.

Figure 2 Relationship between IIS and ASP

      The architecture in Figure 2 changes somewhat when ASP.NET is paired with IIS 6.0. Slated for

release in 2002 with Windows Server 2003, IIS 6.0 will feature a more robust security model that

gives IIS administrators the ability to segregate applications into surrogate processes very much

like Aspnet_wp.exe. In IIS 6.0, there is no Aspnet_wp.exe; instead, IIS provides the worker process.

At the time of this writing, Microsoft plans to connect Inetinfo.exe to worker processes using Local

Procedures Calls (LPCs) rather than named pipes.

What does all of this have to do with security? When Aspnet_isapi.dll forwards an HTTP request to

Aspnet_wp.exe, it also forwards the access token that it obtained from IIS. That access token is

typically one of the following: an IUSR_machinename token representing an unauthenticated user,

or a token representing an authenticated security principal (for example, Bob).Before processing

the request by sending it through the targeted application's HTTP pipeline, Aspnet_wp.exe does the

following:

It performs an ACL check on the requested resource using the access token presented to it. If,

for example, the request is a GET command asking for Foo.aspx, the access token represents

Bob, and Foo.aspx has an ACL that denies read permission to Bob, then ASP.NET fails the

request with an access denied error. ASP.NET performs this ACL check regardless of whether

impersonation is enabled in ASP.NET.

It makes the access token available to the application that handles the request so that, if

desired, the application can impersonate the caller and protect resources guarded by ACLs from

code executed during the request.

Page 23: MC0081 - Answer

The importance of these actions cannot be overstated. The ACL check that ASP.NET performs before

processing the request means you can deny Bob access to an ASPX file simply by tagging that file with

an ACL that denies Bob read access. The fact that ASP.NET makes the caller's access token available

for impersonation purposes means you, the developer, have some latitude in deciding what identity to

use when processing the request. The right choice depends on what the application is designed to do

and how it's designed to do it. I'll provide some background to enrich your understanding.By default,

Aspnet_wp.exe runs as ASPNET, a special account that's set up when ASP.NET is installed. ASPNET is a

member of the Users group, which means it's privileged enough to perform most of the actions a

legitimate application might want to perform, but restricted enough to prevent certain kinds of

attacks. Unless you specify otherwise, requests executed by ASP.NET use Aspnet_wp.exe's identity.

Therefore, by default, requests run as ASPNET. Among other things, this means that barring

configuration changes, there are certain actions an ASP.NET application can't perform, such as

modifying entries in the HKEY_LOCAL_MACHINE section of the registry.

The other option is to execute the request using the access token provided by IIS, a technique known

as impersonation. Impersonation is enabled by including the following statement in the

<system.web> section of a top-level Web.config file or modifying the <identity> element already

present in Machine.config:

<identity impersonate="true" />

If IIS assigns a request the identity of IUSR_machinename, impersonation won't buy you much

because IUSR_machinename is a weak account that enjoys few privileges on the host machine. But if

Windows authentication is enabled and IIS presents ASP.NET with a token representing the actual

requestor, impersonation ensures that the application can't do anything on the Web server that the

requestor isn't allowed to do.

To further complicate matters, Aspnet_wp.exe can be configured to run as a principal other than

ASPNET. Suppose you write an ASP.NET application that must have wider-ranging permissions than

those afforded ASPNET—for example, the freedom to write to any part of the registry. You can

configure Aspnet_wp.exe to run as SYSTEM by changing the statement

<processModel userName="machine" ... />

in Machine.config to read:

<processModel userName="SYSTEM" ... />

This enables your application to do almost anything it wants on the host machine, but it also makes

ASP.NET less resistant to attacks. SYSTEM was the default when ASP.NET was in beta, but that was

changed shortly before the product shipped.Another possible complication arises from the fact that in

IIS 6.0, ASP.NET requests will default to Network Service rather than ASPNET. If you use ACLs to allow

access to the ASPNET account while denying access to other security principals and find that requests

mysteriously fail with access denied errors after you install IIS 6.0, modify your ACLs to allow access to

Network Service rather than ASPNET.

Clearly, the identities assigned to the ASP.NET worker process and to the requests that it executes

play crucial roles in determining how successful an application is in carrying out its appointed mission.

If your head is spinning right now trying to make sense of it all, don't fret; ASP.NET security will be far

easier to grasp once you've experienced it firsthand. In the meantime, here are some guidelines to

help you sort through the options and figure out which of them really matter for a given deployment

scenario:

Page 24: MC0081 - Answer

If your application requires no special protection—if all of its pages can be freely browsed by

anyone and none are personalized for individual users—you needn't bother with application-

level security. Just grant Everyone access to the application's files and be done with it.

If you're building an intranet application or any application whose permissions are based on

mapping incoming requests to Windows accounts on your server, you'll probably use Windows

authentication and ACL authorization. In that case, you'll use operating system ACLs to restrict

access to pages that aren't intended for everyone. You may or may not enable impersonation,

depending on the needs of the application.

If you're building an Internet application that serves the general public but want to secure

access to certain pages, you'll most likely use forms authentication and URL authorization. In

that case, you'll leave impersonation disabled and rely on credentials entered in login forms as

the basis for authorizations. Many of the aforementioned issues regarding IIS and access

tokens fall by the wayside in this scenario because you grant Everyone access to the

application's files and rely on URL authorizations in Web.config to protect them.

A final thought to keep in mind is that if you use ACLs to limit access to files and directories in an ASP.NET

application, always grant the ASPNET account—or whatever account Aspnet_wp.exe runs as—read access

to them. Otherwise, ASP.NET itself will be unable to read them and you'll experience all kinds of access

denied errors that you probably didn't expect

Master of Computer Application (MCA) – Semester V

MC0081 – DOT Net Technologies

Assignment Set – 2

1. Write about Assemblies in Dot Net.

The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET

assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or

dynamic link library (DLL) file. All the .NET assemblies contain the definition of types, versioning

information for the type, meta-data, and manifest. The designers of .NET have worked a lot on the

component (assembly) resolution.There are two kind of assemblies in .NET; private and shared. Private

assemblies are simple and copied with each calling assemblies in the calling assemblies folder. Shared

assemblies (also called strong named assemblies) are copied to a single location (usually the Global

assembly cache). For all calling assemblies within the same application, the same copy of the shared

assembly is used from its original location. Hence, shared assemblies are not copied in the private

folders of each calling assembly. Each shared assembly has a four part name including its face name,

version, public key token and culture information. The public key token and version information makes

it almost impossible for two different assemblies with the same name or for two similar assemblies with

different version to mix with each other.

An assembly can be a single file or it may consist of the multiple files. In case of multi-file, there is one

master module containing the manifest while other assemblies exist as non-manifest modules. A

Page 25: MC0081 - Answer

module in .NET is a sub part of a multi-file .NET assembly. Assembly is one of the most interesting and

extremely useful areas of .NET architecture along with reflections and attributes, but unfortunately

very few people take interest in learning such theoretical looking topics.

What is an assembly?

An Assembly is a  logical unit of code

Assembly physically exist as DLLs or EXEs

One assembly can contain one or more files

The constituent files can include any file types like image files, text files etc. along with DLLs or

EXEs

When you compile your source code by default the exe/dll generated is actually an assembly

Unless your code is bundled as assembly it can not be used in any other application

When you talk about version of a component you are actually talking about version of the assembly

to which the component belongs.

Every assembly file contains information about itself. This information is called as Assembly

Manifest.

What is assembly manifest?

Assembly manifest is a data structure which stores information about an assembly

This information is stored within the assembly file(DLL/EXE) itself

The information includes version information, list of constituent files etc.

What is private and shared assembly?

The assembly which is used only by a single application is called as private assembly. Suppose you

created a DLL which encapsulates your business logic. This DLL will be used by your client application

only and not by any other application. In order to run the application properly your DLL must reside in

the same folder in which the client application is installed. Thus the assembly is private to your

application.

Suppose that you are creating a general purpose DLL which provides functionality which will be used

by variety of applications. Now, instead of each client application having its own copy of DLL you can

place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.

What is Global Assembly Cache?

Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept.

It is located under <drive>:\WinNT\Assembly folder.

Page 26: MC0081 - Answer

How assemblies avoid DLL Hell?

As stated earlier most of the assemblies are private. Hence each client application refers assemblies

from its own installation folder. So, even though there are multiple versions of same assembly they will

not conflict with each other. Consider following example :

You created assembly Assembly1

You also created a client application which uses Assembly1 say Client1

You installed the client in C:\MyApp1 and also placed Assembly1 in this folder

After some days you changed Assembly1

You now created another application Client2 which uses this changed Assembly1

You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder

Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly

Now consider the case when you develop assembly that is shared one. In this case it is important to

know how assemblies are versioned. All assemblies has a version number in the form:

major.minor.build.revision

If you change the original assembly the changed version will be considered compatible with existing

one if the major and minor versions of both the assemblies match.When the client application requests

assembly the requested version number is matched against available versions and the version

matching major and minor version numbers and having most latest build and revision number are

supplied.

How do I create shared assemblies?

Following steps are involved in creating shared assemblies :

Create your DLL/EXE source code

Generate unique assembly name using SN utility

Sign your DLL/EXE with the private key by modifying AssemblyInfo file

Compile your DLL/EXE

Place the resultant DLL/EXE in global assembly cache using AL utility

Page 27: MC0081 - Answer

How do I create unique assembly name?

Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys are

generated using a utility called SN.exe (SN stands for shared name). The most common syntax of is :

sn -k mykeyfile.key

Where k represents that we want to generate a key and the file name followed is the file in which the

keys will be stored.

How do I sign my DLL/EXE?

Before placing the assembly into shared cache you need to sign it using the keys we just generated.

You mention the signing information in a special file called AssemblyInfo. Open the file from VS.NET

solution explorer and change it to include following lines :

[assembly:AssemblyKeyFile("file_path")]

Now recompile the project and the assembly will be signed for you.

How do I place the assembly in shared cache?

Microsoft has provided a utility called AL.exe to actually place your assembly in shared cache.

AL /i:my_dll.dll

Now your dll will be placed at proper location by the utility.

Now, that we have understood the basics of assemblies let us apply our knowledge by developing a

simple shared assembly.

In this example we will create a VB.NET component called SampleGAC ( GAC stands for Global

Assembly Cache). We will also create a key file named sample.key. We will sign our component with

this key file and place it in Global Assembly Cache.

Step 1 : Creating our sample component

Here is the code for the component. It just includes one method which returns a string.

imports system

namespace BAJComponents

public class Sample

public function GetData() as string

return "hello world"

end function

end class

Page 28: MC0081 - Answer

end namespace

Step 2 : Generate a key file

To generate the key file issue following command at command prompt.

sn -k sample.key

This will generate the key file in the same folder

Step 3 : Sign your component with the key

Now, wee will sign the assembly with the key file we just created.

vbc sampleGAC.vb /t:library /a.keyfile:sample.key

Step 4 : Host the signed assembly in Global Assembly Cache

We will use AL utility to place the assembly in Global Assembly Cache.

AL /i:sampleGAC.dll

After hosting  the assembly just go to WINNT\Assembly folder and you will find your assembly listed

there. Note how the assembly folder is treated differently that normal folders. 

Step 5 : Test that our assembly works

Now, we will create a sample client application which uses our shared assembly. Just create a

sample code as listed below :

imports system

imports BAJComponents

public class SampleTest

shared sub main()

dim x as new sample

dim s as string="x".getdata()

console.writeline(s)

end sub

end class

Compile above code using :

vbc sampletest.vb /t:exe /r:<assembly_dll_path_here>

Now, copy the resulting EXE in any other folder and run it. It will display "Hello World" indicating that it is using our shared assembly

2. Write a C# program to perform basic arithmetic operations Answer:

A program to store the details of employees. Depending upon the post of the employee, there would be various fields associated with it. A department head, for example, would have a property denoting the department he heads, etc. We use conditional branching in such a scenario.

C# provides the following conditional constructs:-

if .. else

Syntax:-if ( < condition > ){statements

Page 29: MC0081 - Answer

}else{statements}

The else part is optional and can be omitted. The working of if .. else construct is very simple and follows the pattern - If this is true I’ll do that or else I’ll do something else. The statements included within the if block are executed when the condition specified in if, is true, otherwise the statements inside the else block are executed. In case, there is no else statement, the execution flow continues to the proceeding statements.

Here’s an example:-

CODEConsole.WriteLine("Enter your age:");int Age = Convert.ToInt32(Console.ReadLine());if (Age < 18){    Console.WriteLine("You are not permitted in here.");}else{    Console.WriteLine("You may come in.");}

Lets step through the code. Line 1 displays a message Enter your age. At line 2, the age entered by the user is read using ReadLine() (as a string) and converted to an integer using the ToInt32 function. Finally the value is stored in the integer variable Age. When the execution reaches line 3, the expression inside if is evaluated. If the user supplied an age less than 18, the execution flow would move to line 5 - Console.WriteLine("You are not permitted in here."); and the message You are not permitted in here would be displayed. In the other scenario, when the age would be either equal to or greater than 18, line 7 would be executed and the message You may come in will be displayed.

The condition inside the if statement can be composed of a complex expression chained by the logical operators. For Example:-

CODEConsole.WriteLine("Enter your age:");int Age = Convert.ToInt32(Console.ReadLine());Console.WriteLine("Are you with your guardian? (True/False)");bool WithGuardian = Convert.ToBoolean(Console.ReadLine());if ((Age < 18 ) && (WithGuardian = false)){    Console.WriteLine("You are not permitted in here.");}else{    Console.WriteLine("You may come in.");}

At line 4 the user's response of whether he/she is with a guardian would be stored inside the boolean variable WithGuardian. Notice that ToBoolean function is used to convert the input to boolean

Page 30: MC0081 - Answer

(True/False) value. At line 5, the complex expression will be evaluated. The expression is made up of two sub-expressions: Age < 18 and WithGuardian = false. These two expressions are joined with the logical AND operator (&&). Therefore, when both of the expressions amount to true, the entire expression would evaluate to true and the message - You are not permitted in here will be displayed. For any other combination, the final expression would be equivalent to false and the message - You may come in will be displayed.

A number of conditions can be chained by using else if as follows:-

CODEConsole.WriteLine("Enter your salary");int Salary = Convert.ToInt32(Console.ReadLine());if (Salary > 250000){    Console.WriteLine("Welcome Mr. CEO");}else if (Salary > 200000){    Console.WriteLine("Welcome Mr. Chairman");}else if (Salary > 0){    Console.WriteLine("Welcome Programmer");}else{    Console.WriteLine("Welcome dear Customer");}

In this case, if the salary supplied by the user is greater than 250000, the message - Welcome Mr. CEO will be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message - Welcome Programmer will be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customer will be the output.

switch .. case ConstructSwitch case facilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a case construct.

Syntax:-switch (< expression >){case Expression_1;statementsbreak;

case Expression_2;statementsbreak;

….

Page 31: MC0081 - Answer

}

break is a C# keyword, which is used to exit the body of a switch, for or while loop. Equivalent to the else construct is the default case. Statements within the default case are executed when no other condition holds true.

Example:-

CODEConsole.WriteLine("Enter the month (mm)");int Month = Convert.ToInt32(Console.ReadLine());switch (Month){    case 1:        Console.WriteLine("January");        break;

    case 2:        Console.WriteLine("February");        break;

    case 3:        Console.WriteLine("March");        break;

    case 4:        Console.WriteLine("April");        break;

    case 5:        Console.WriteLine("May");        break;

    case 6:        Console.WriteLine("June");        break;

    case 7:        Console.WriteLine("July");        break;

    case 8:        Console.WriteLine("August");        break;

    case 9:        Console.WriteLine("September");        break;

    case 10:        Console.WriteLine("October");        break;

Page 32: MC0081 - Answer

    case 11:        Console.WriteLine("November");        break;

    case 12:        Console.WriteLine("December");        break;

    default:        Console.WriteLine("There are only 12 Months.");        break;}

Depending on the value entered by the user (1-12), the appropriate month will be displayed. For any other value, the default case will be executed and the message There are only 12 Months. will be displayed.

Multiple Values can be made to lead to the same block of statements by excluding the break statement.

CODEConsole.WriteLine("Enter a number  (1-10)");int Num = Convert.ToInt32(Console.ReadLine());switch (Num){    case 2:    case 3:    case 5:    case 7:        Console.WriteLine("The number is prime.");        break;    case 1:    case 9:        Console.WriteLine("The number is odd.");        break;    case 4:    case 6:    case 8:        Console.WriteLine("The number is Even");        break;    default:        Console.WriteLine("The number is not in range.");        break;}

Looping

A Set of instructions that are repeated is called a loop. Suppose you want to print numbers from 1 - 10. You could do that using Console.WriteLine statement for each of the 10 numbers. But, what if you had to print numbers from 1 - 1000? Using the computer’s iterative power is a much better approach.

C# supports 3 kinds of loops which are discussed below:-

Page 33: MC0081 - Answer

The for loopThis loop is generally used for arithmetic operations, where we are aware of the starting and end point of the loop. Syntax of for loop is as follows:-

for(< initialization >;< condition >;< increment/decrement >){statements}

To print numbers within a range, say 1 - 1000, we declare a counter variable (preferably single character variable like I), initialize it to the starting number (1) and keep incrementing its value by 1 until the number exceeds the end point (1000). Off course, we would have the body of the loop where the operation would be done, in this case, displaying the numbers on screen.

CODEfor(int I = 1; I <= 1000; I++){    Console.WriteLine(I);}

Lets break the for statement down:-Initialization: int I = 1Condition: I <= 1000Increment: I++

All the parts here are optional and can be left out. So, you can initialize the variable I, above the for statement and leave out the initialization block. The code would look like this (; I <= 1000; I++). Similarly, you could remove the condition part to make the loop infinite or you can include the increment statement within the body of the for statement itself (inside the { and } brackets).

Another variation of a for statement is the empty loop which does not contain any body: for(int I = 1; I <= 1000; I++);

Such a for statement is followed by the semicolon.

The while loopThe for loop cannot be used when the range of the loop is unknown (Well, actually it can, but the approach would not be logical). Say, you want to continue inputting values from the user as long he wishes to. This can be easily implemented by the while statement.

Syntax:-while(< condition >){statements}

We don’t have initialization and increment/decrement slot over here. These need to be implemented additionally. Take a look at the code snippet below.

CODE

Page 34: MC0081 - Answer

bool Continue = true;while(Continue == true){    int A;    Console.WriteLine("Please Enter a Number");    A = Convert.ToInt32(Console.ReadLine());    Console.WriteLine("Continue (True/False)");    Continue = Convert.ToBoolean(Console.ReadLine());}

We have declared a boolean variable Continue which we use to check whether to continue repeating the process. It has been initialized to true, so that the loop is executed for the first time. The user’s choice of whether to continue with the loop or not, is stored in Continue. As long as the user enters true, the statements within the body of the while loop would keep on executing.

Anything that can be implemented using for loop, can also be done using the while loop. Below is the code to print numbers from 1 - 1000 using while.

CODEint I = 1;while(I <= 1000){    Console.WriteLine(I);    I++;}

The do while loopThe do while loop is a variation of the while loop in which the condition is evaluated at the end of the loop. Thus, the loop is executed at least once. Recall the first while program we did. The bool variable continue stores the user’s choice. However, for the first iteration, it does not store the choice. In such a scenario, we had to initialize continue with the value true so that the loop is executed for the first time. A better approach would be to use the do while loop and check the condition at the end. The code for which is given below.

CODEbool Continue;do{    int A;    Console.WriteLine("Please Enter a Number");    A = Convert.ToInt32(Console.ReadLine());    Console.WriteLine("Continue (True/False)");    Continue = Convert.ToBoolean(Console.ReadLine());}while(Continue == true);

Note: The while part in the do while loop needs to be terminated with the semicolon.

Although, either of the three types of loops can be used to do an iteration, one needs to use the appropriate loop for the job. Use the for loop for arithmetic operations, while loop for non-arithmetic ones and the do-while loop when the loop must execute at least once.

3. Describe the Web form life cycle. Every request for a page made from a web server causes a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins

Page 35: MC0081 - Answer

with a request for the page, which causes the server to load it. When the request is complete, the page is unloaded. From one end of the life cycle to the other, the goal is to renderappropriate HTML output back to the requesting browser. The life cycle of a page is marked by the following events, each of which you can handle yourself or leave to default handling by the ASP.NET server:

Initialize:Initialize is the first phase in the life cycle for any page or control. It is here that you initialize any settings needed for the duration of the incoming request.

Load View State:The ViewState property of the control is populated. The ViewState information comes from a hidden variable on the control, used to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the ViewState property is set. This can be modified via the LoadViewState() method. This allows ASP.NET to manage the state of your control across page loads so that each control is not reset to its default state each time the page is posted.

Process Postback Data:During this phase, the data sent to the server in the posting is processed. If any of this data results in a requirement to update the ViewState, that update is performed via the LoadPostData() method.

Load:CreateChildControls() is called, if necessary, to create and initialize server controls in the control tree. State is restored, and the form controls show client-side data. You can modify the load phase by handling the Load event with the OnLoad method.

Send Postback Change Modifications:If there are any state changes between the current state and the previous state, change events are raised via the RaisePostDataChangedEvent() method.

Handle Postback Events:The client-side event that caused the postback is handled.

PreRender:This is the phase just before the output is rendered to the browser. It is essentially your last chance to modify the output prior to rendering using the OnPreRender() method.

Save State:Near the beginning of the life cycle, the persisted view state was loaded from the hidden variable. Now it is saved back to the hidden variable, persisting as a string object that will complete the round trip to the client. You can override this using the SaveViewState() method.

Render:This is where the output to be sent back to the client browser is generated. You can override it using the Render method. CreateChildControls() is called, if necessary, to create and initialize server controls in the control tree.

Dispose:This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connections. You can modify it using the Dispose() method.

4. Write about the creation of Master Pages in ASP.Net applications

Master Page Framework Development:

Every thing starts with a use case in Object Oriented Software Engineering. One of the use cases while we develop web application is that

User needs a consistent look and feel, through out, period.

Page 36: MC0081 - Answer

Apart from some CSS style-sheet for consistency, what else we need, a framework, Master-Page Framework, which should be extendible, easy to use, pluggable and modifiable visually! (Sounds great! what a wish :)) There is no such thing existing in ASP.NET(Whidbey, does have one, but still long way to go).

I started looking around the web and found some interesting articles:

Master Your Site Design with Visual Inheritance and Page Templates by Fritz Onion. ASP.NET Page Templates - Using Inheritance by Peter Provost.

These articles are very good starting points, so I took the entire valuable advises from them and went further, since, I was looking for something like a reusable/extendible Framework. I took the responsibility of redesigning the whole wheel that never existed, in the first place, how is that.The approach I took, what I devised is, Pattern Oriented Architecture and Design (POAD), not design patterns, they are different. I call it POAD because my application has a peculiar look and feel that it follows a pattern. POAD means you have entire prototypic pattern, your application will follow, but will be overridden later for concrete structure of it (the concept needs a whole article and I would write later, with some examples, hopefully next month). So the Master-page has header, footer, navigator, menus/submenus, and content place-holders that would be filled in later as needed for concrete pages, How�s that, sounds good. Let's move further! Here are the steps involved in designing the POAD based softwares.

Draw the whole abstract pattern your framework would provide. Find Objects responsible for doing the job.

Find relationships between them.

Find design patterns needed.

Elaborate Objects while designing them, and find functionality for them.

Write test cases.

Page 37: MC0081 - Answer

Steps Involved:

Draw the whole abstract pattern your framework would provide.

Here is the prototypic pattern of our Framework:

Figure 1 (Master-Page Layout/pattern)

MaterWeb User-Control

If we decompose this pattern into objects, it�s being clear that we should have something like skeleton or template for the place holders, i.e., there should be something like a master-page that is composed of the placeholders, like header, footer, logo, menus, navigator, and contents etc.

Page 38: MC0081 - Answer

Since our plan is to change these place holders visually, we could safely put these place holders in a user control (PageUserControlBase) that in turn contains all the place holders. Call it a Master user-control, where you define your layout for these contents. Now, our model would have a Master Page that in turn is composed of Master User-Control (PageUserControlBase) that in turn is composed of placeholders, like this:

Getting closer, great! :) Now the visual part is decided that we provide using user-control or so. We want this user-control to be pluggable at run time, so we�ll dynamically load it at run time using web.config like this:

<appSettings> <add key="MasterPageUserControl" value="MasterPageUserControl.ascx"/>

</appSettings>

Our Framework encapsulates all the functionality of the Master User-Control (PageUserControlBase) class in an assembly as a base/abstract class, so that we can extend it in future, if we need it. Here is how it would look like:

Page 39: MC0081 - Answer

With this approach, if in future, we decide with some other look and feel of the master user control, all we need is to extend PageUserControlBase class and use it:

Page 40: MC0081 - Answer

<%@ Control Inherits="Shams.Web.UI.MasterPages.PageUserControl" %>

Or use it like this:

<%@ Control Inherits="Shams.Web.UI.MasterPages.PageUserControlExtra" %>

PageUserControl or PageUserControlExtra, will provide us access to the WebControls.PlaceHolder(s). Here is how the PageUserControlBase.ascx should look like:

Page 41: MC0081 - Answer

This was straightforward, right? Yes, it is. Now the visual component can easily be extended, and further, is pluggable through the web.config, and is ready. So while designing the Framework, we are right on target, extendible and pluggable Framework, great :). What else would be needed, well lot of work still there? All we have done so far is we provided a consistent look and feel through pluggable Master User Control-Base. We have a long way to go. Let's first analyze how the HTML/aspx page looks like:

You can see the page itself has four parts, let’s examine them closely:

Part A: - HTML Header, describing code-behind language, Page title, Meta info, and HTML body etc. Part-B: - Form area.

Part-C: - Master User-Control area, [or any controls].

Part-D: - HTML footer area.

Master Custom-Control:

Every page can have one and only one HTML Form. We put all the server-controls in this form (part-C). So, what we need is another object that would encapsulate all these HTML-Rendering stuff shown above, like Part-A, Part-B, Part-C, and Part-D in it. If you look at the Control class, it has all the functionality we are looking for. The Control is a composite that means we can put other controls in it. So, it would be a good starting point to start with a Custom control by extending the Control Object. This extended Custom Control, we named it PageControlBase, will provide HTML rendering capability as well as it would have a System.Web.UI.HtmlControls.HtmlForm object. This Form object would be used to add our famous master-user-control or Part-C in it. Now, our master page would be composed of some master custom control, and master-user-control. Here is the UML diagram that demonstrates all these:

Page 42: MC0081 - Answer

Now that we have a pluggable Master-User-Control, a custom control that will create all of the HTML parts is necessary.

What we need is an integrator class that will insert Master User-Control into Custom control form and attach it to the Master-Page. And that’s the MasterPageBase class, derived from UI. Page class:-

Design Patterns used in Master-Page Framework

When you are planning for any Framework that is based on some prototype or follow POAD, the most effective pattern is the Template design pattern. Here is the code that demonstrates this pattern:

public interface IPageControl { System.Web.UI.Control ParentControl(); void HtmlRenderStarts(); void PreHtmlRender(); void HtmlRender(); void PostHtmlRender(); void HtmlRenderEnds();

Page 43: MC0081 - Answer

string PageTitle { get; set; }

string MetaInfo { get; set; } }

We defined the sequence/pattern of execution that would later be overridden by the derived classes.

Template Design Pattern is used in two occasions:

Defined template in the Custom control:-

And here is the other place where the same design pattern is used:

Page 44: MC0081 - Answer

Other patterns that are used are Factory and Composite Design Patterns. The Factory pattern is used to create classes, and should provide one place; if we have plan to put some business logic around their creation, we can do it, without breaking the existing code.

Composite Pattern is built in with the .NET Framework, like Control Class is itself based on composite pattern. Composite Pattern in its simple form is a list of list of objects. Instead of reinventing my own containers for objects, I used the Control class as my starting point.

Page 45: MC0081 - Answer

So that’s it, we are done with the Framework. All you need is to derive your page from the MasterPage class, and override the stuff you want to change in your concrete classes. How we do it is shown using UML Diagram here:

Let�s discuss some typical scenarios we�ll come across while doing implementation:

1. Creation of Master Page Skeleton: -

As discussed earlier, all we need is to derive from MasterPageBase. Here is the code snippet as an example:

Page 46: MC0081 - Answer

Here is the output we’ll get; it’s a master-page skeleton.

The visual settings are from web.config, i.e.,

<appSettings> <add key="MasterPageUserControl" value="MasterPageUserControl.ascx"/>

</appSettings>

If you have some other-layout in your mind for your MasterPage, you can create your own user control and change the signature in the web.config.

Here is the not so detailed objects sequence diagram, for the above scenario:-

Page 47: MC0081 - Answer

2. Creation of MasterPage from MasterPage Skeleton:-

We would create a MasterPage class from MasterPageBase and override the placeholders with our own UserControls. Here is the example code snippet for this:-

Page 48: MC0081 - Answer

5. Explain the importance and applications of Global.asax Application file. In Asp.net 1.1  when you create web application with visual studio 2003 editor it will automatically create global.asax file, but this is not the same case with visual studio 2005, 2008 it will not create global.asax file by default. You need to explicitly add global.asax file to make use of this.

But here I want to make it clear that all the event and method will fired according to it nature.

So till here we are clear that in visual studio 2005 and 2008 global.asax file is default and if you want to add it you have to add manually.

How to create or add global.asax file in Asp.Net 2.0, 3.0 and 3.5?

Its simple , Right click on the solution explorer in visual studio editor -> Add New Item -> Select "Global Application Class" - > press "Add" Button

Now you have added global.asax file in you web application.

By default you can see that below event method is automatically available in your global.asax file.

Application_StartApplication_EndApplication_ErrorSession_StartSession_End

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

<script runat="server">

Page 49: MC0081 - Answer

void Application_Start(object sender, EventArgs e) 

{

// Code that runs on application startup

}

void Application_End(object sender, EventArgs e) 

{

// Code that runs on application shutdown

}

void Application_Error(object sender, EventArgs e)

{

// Code that runs when an unhandled error occurs

}

void Session_Start(object sender, EventArgs e) 

{

// Code that runs when a new session is started

}

void Session_End(object sender, EventArgs e) 

{

// Code that runs when a session ends. 

// Note: The Session_End event is raised only when the sessionstate mode

// is set to InProc in the Web.config file. If session mode is set to StateServer 

// or SQLServer, the event is not raised.

}

</script>

Now we will explore each above listed method and its importance one by one.

Application_Start - This method will get fired when First time the application and web server (eg. IIS) starts, That means If the IIS recycle or restart again then this event also will be fired.

Application_End - This method will be fired when application started shut down.

Application_Error - This event  will be fired when there is any exception occurred in the application during run time. This event method is one of most important method used by most of the web developer.

Page 50: MC0081 - Answer

Session_Start -  This event will be fired when a new user request a page from the server. That means for every user request the page this event will b fired.

Session_End - This code will be fired when session end for a use. But make sure this event willl only fired when Session Mode is "InProc" as we know there are three session state InProc, StateServer, SqlServer mode to store session.

Now let's see real time example of the above events present in global.asax file.

Create Hits counter of web application.

We are going to make use of Application_Start event and Session_Start even to achieve hit counter.

public void Application_Start(object sender, EventArgs e)

{

//Create Application object and assign 0 to it

Application["TotalHits"] = 0;

}

public void Session_Start(object sender, EventArgs e)

{

//Lock the Application using Lock method of application

Application.Lock();

//Increment by 1 Application object every time when session starts

Application["TotalHits"] = Application["TotalHits"] + 1;

//Unlock the Application Object using Unlock() method if Application object

Application.UnLock();

}

6. Describe the importance of Application State in ASP.Net applications.

ASP.NET and its State of ApplicationASP.NET is a web application framework developed and marketed by Microsoft, which programmers can use to build dynamic web sites, web applications and web services.

ASP.NET applications are hosted in a web server and are accessed over the stateless HTTP protocol. As such, if the application uses stateful interaction, it has to implement state management on its own. ASP.NET provides various functionality for state management in ASP.NET applications, these state management includes application state, session state, and view state.

 Application state is a collection of user-defined variables that are shared by all invocations of an ASP.NET application. These are set and initialized when the Application_OnStart event fires on the loading of the first instance of the applications and are available till the last instance exits. Application

Page 51: MC0081 - Answer

state variables are accessed using the Applications collection, which provides a wrapper for the application state variables. Application state variables are identified by names. Learn more about this with the austin .net developer.

 Session state is a collection of user-defined session variables, which are persisted during a user session. These variables are unique to different instances of a user session, and are accessed using the Session collection. Session variables can be set to be automatically destroyed after a defined time of inactivity, even if the session does not end. Learn more about this with the austin .net developer.

 ASP.NET supports three modes of persistence for session variables: the In Process Mode, ASPState Mode, and SqlServer Mode.

 On the In Process Mode, the session variables are maintained within the ASP.NET process. This is the fastest way, however, in this mode the variables are destroyed when the ASP.NET process is recycled or shut down. Since the application is recycled from time to time this mode is not recommended for critical applications.

 In ASPState Mode, ASP.NET runs a separate Windows service that maintains the state variables. Because the state management happens outside the ASP.NET process, this has a negative impact on performance, but it allows multiple ASP.NET instances to share the same state server, thus allowing an ASP.NET application to be load-balanced and scaled out on multiple servers.

 In the SqlServer Mode, the state variables are stored in a database server, accessible using SQL. Session variables can be persisted across ASP.NET process shutdowns in this mode as well. The main advantage of this mode is it would allow the application to balance load on a server cluster while sharing sessions between servers. Learn more about these with the austin .net developer.

 View state refers to the page-level state management mechanism, which is utilized by the HTML pages emitted by ASP.NET applications to maintain the state of the web form controls and widgets. The server sends back the variable so that when the page is re-rendered, the controls render at their last state.

 At the server side, the application might change the viewstate, if the processing results in updating the state of any control. The states of individual controls are decoded at the server, and are available for use in ASP.NET pages using the ViewState collection.

7. Write the basic steps in building Connection Strings from Configuration Files in ADO.Net applications. If certain elements of a connection string are known ahead of time, they can be stored in a configuration file and retrieved at run time to construct a complete connection string. For example, the name of the database might be known in advance, but not the name of the server. Or you might want a user to supply a name and password at run time without being able to inject other values into the connection string.

One of the overloaded constructors for a connection string builder takes a String as an argument, which allows you to supply a partial connection string which can then be completed from user input. The partial connection string can be stored in a configuration file and retrieved at run time.

ExampleThis example demonstrates retrieving a partial connection string from a configuration file and completing it by setting the DataSource, UserID, and Password properties of the SqlConnectionStringBuilder. The configuration file is defined as follows.

<connectionStrings><clear/><add name="partialConnectString" connectionString="Initial Catalog=Northwind;" providerName="System.Data.SqlClient" />

</connectionStrings>

Private Sub BuildConnectionString(ByVal dataSource As String, _

Page 52: MC0081 - Answer

ByVal userName As String, ByVal userPassword As String)

Dim settings As ConnectionStringSettings = _ ConfigurationManager.ConnectionStrings("partialConnectString")

If Not settings Is Nothing Then 'Retrieve the partial connection string. Dim connectString As String = settings.ConnectionString Console.WriteLine("Original: {0}", connectString)

' Create a new SqlConnectionStringBuilder based on the ' partial connection string retrieved from the config file. Dim builder As New SqlConnectionStringBuilder(connectString)

' Supply the additional values. builder.DataSource = dataSource builder.UserID = userName builder.Password = userPassword

Console.WriteLine("Modified: {0}", builder.ConnectionString) End IfEnd Sub

8. Describe the concept of Forms Authentication in Dot Net.

Often, in legacy Web applications, users authenticate themselves via a Web form. This Web form submits the user's credentials to business logic that determines their authorization level. Upon successful authentication, the application then submits a ticket in the form of a cookie, albeit a hard cookie or session variable. This ticket contains anything from just a valid session identification access token to customized personalization values.

ASP.NET encompasses and extends the very same logic described above into its architecture as an authentication facility, Forms Authentication. Forms Authentication is one of three authentication providers. Windows Authentication and Passport Authentication make up the other two providers. In this article, we will focus on Forms Authentication.

Forms Authentication is a system in which unauthenticated requests are redirected to a Web form where users are required to provide their credentials. Upon submitting the form, and being properly verified by your application, an authorization ticket is issued by your Web application in the form of a cookie. This authorization cookie contains the user's credentials or a key for reacquiring the user's identity (e.g. therefore making the identity persistent). In essence, Forms Authentication is a means for wrapping your Web application around your own login user interface and verification processes.

Forms Authentication Flow1. A client generates a request for a protected resource (e.g. a secured page from your site). 2. IIS (Internet Information Server) receives the request. If the requesting client is authenticated by

IIS, the user/client is passed on to the ASP.NET application. Note that if Anonymous Access is enabled, the client will be passed onto the ASP.NET application by default. Otherwise, Windows will prompt the user for credentials to access the server's resources. Also note that because the authentication mode in the ASP.NET application is set to Forms, IIS authentication cannot be used.

3. If the client doesn't contain a valid authentication ticket/cookie, ASP.NET will redirect the user to the URL specified in the loginURL attribute of the Authentication tag in your web.config file. This URL should contain the login page for your application. At this URL, the user is prompted to enter their credentials to gain access to the secure resource.

4. The client must provide credentials, which are then authenticated/processed by your ASP.NET application. Your ASP.NET application also determines the authorization level of the request, and, if

Page 53: MC0081 - Answer

the client is authorized to access the secure resource, an authentication ticket is finally distributed to the client. If authentication fails, the client is usually returned an Access Denied message.

5. The client can then be redirected back to the originally-requested resource, which is now accessible, provided that the client has met the authentication and authorization prerequisites discussed above. Once the authorization ticket/cookie is set, all subsequent requests will be authenticated automatically until the client closes the browser or the session terminates. You can have the user's credentials persist over time by setting the authorization ticket/cookie expiration value to the date you desire to have the credentials persist through. After that date, the user will have to log in again.

Setting Up Forms Authentication

Let's take a look at the applicable settings to execute Forms Authentication. In general, setting up Forms Authentication involves just a few simple steps.

1. Enable anonymous access in IIS. By default, anonymous users should be allowed to access your Web application. In rare cases, however, you may opt to layer an Integrated Windows OS security layer level with Forms authentication. We will discuss how to integrate this layer with anonymous access enabled in the article succeeding this one ("Part 2 (Integration w/ Active Directory)").

2. Configure your Web application's web.config file to use Forms Authentication. Start by setting the authentication mode attribute to Forms, and denying access to anonymous users. The following example shows how this can be done in the web.config file for your Web application:

<configuration> <system.web> <authentication mode="Forms"> <forms name=".COOKIEDEMO" loginUrl="login.aspx" protection="All" timeout="30" path="/"/> </authentication> <authorization> <deny users="?" /> </authorization> </system.web></configuration>

Upon setting the authentication mode to Forms, you'll notice that we appended another child element. The Forms element has five attributes that implement your forms authentication configuration. The attributes and their descriptions are as follows :

Attribute Description

name This is the name of the HTTP cookie from which we will store our authentication ticket and information, respectively.

loginURL This is the URL from which your unauthenticated client will be redirected. In most scenarios, this would be your login page, where the client is required to provide their credentials for authentication.

protection This is used to set the method from which to protect your cookie data. The following valid values can be supplied:

All: Specifies to use both data validation and encryption to protect the cookie. Triple DES is used for encryption, if it is available and if the key is long enough

Page 54: MC0081 - Answer

(48 bytes). The All value is the default (and suggested) value.

None: Used for sites that are only using cookies for personalization and have weaker requirements for security. Both encryption and validation can be disabled. This is the most efficient performance wise, but must be used with caution.

Encryption: Specifies that the cookie is encrypted using Triple DES or DES, but data validation is not done on the cookie. It's important to note that this type of cookie is subject to chosen plaintext attacks.

Validation: Specifies to avoid encrypting the contents of the cookie, but validate that the cookie data has not been altered in transit. To create the cookie, the validation key is concatenated in a buffer with the cookie data and a MAC is computed/appended to the outgoing cookie.

timeout This is the amount of time (in integer minutes) that the cookie has until it expires. The default value for this attribute is 30 (thus expiring the cookie in 30 minutes).

The value specified is a sliding value, meaning that the cookie will expire n minutes from the time the last request was received.

path This is the path to use for the issued cookie. The default value is set to "/" to avoid issues with mismatched case in paths. This is because browsers are case-sensitive when returning cookies.

In our web.config file, it's also important to note the value we have for the deny child element of the authorization section (as highlighted below). Essentially, we set that value of the users attribute to "?" to deny all anonymous users, thus redirecting unauthenticated clients to the loginURL.

<configuration> <system.web> <authentication mode="Forms"> <forms name=".COOKIEDEMO" loginUrl="login.aspx" protection="All" timeout="30" path="/"/> </authentication> <authorization> <deny users="?" /> </authorization> </system.web></configuration>

3. Create your login page (as referenced in the loginURL attribute discussed above). In this case, we should save our login page as login.aspx. This is the page to where clients without valid authentication cookie will be redirected. The client will complete the HTML form and submit the values to the server. You can use the example below as a prototype.

<%@ Import Namespace="System.Web.Security " %><html> <script language="C#" runat=server> void Login_Click(Object sender, EventArgs E) { // authenticate user: this sample accepts only one user with

Page 55: MC0081 - Answer

// a name of [email protected] and a password of 'password' if ((UserEmail.Value == "[email protected]") && (UserPass.Value == "password")) { FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked); } else { lblResults.Text = "Invalid Credentials: Please try again"; } } </script> <body> <form runat="server"> <h3>Login Page</h3> <hr> Email:<input id="UserEmail" type="text" runat="server"/> <asp:RequiredFieldValidator ControlToValidate="UserEmail" Display="Static" ErrorMessage="*" runat="server"/> <p>Password:<input id="UserPass" type="password" runat="server"/> <asp:RequiredFieldValidator ControlToValidate="UserPass" Display="Static" ErrorMessage="*" runat="server"/> <p>Persistent Cookie:<ASP:CheckBox id="PersistCookie" runat="server" /> <p><asp:button id="cmdLogin" text="Login" OnClick="Login_Click" runat="server"/> <p><asp:Label id="lblResults" ForeColor="red" Font-Size="10" runat="server" /> </form> </body></html>

It's important to note that the above page authenticates the client on the click event of the cmdLogin button. Upon clicking, the logic determines if the username and password provided match those hard-coded in the logic. If so, the client is redirected to the requested resource. If not, the client is not authorized, and thus receives a message depicting this.

You can adjust the logic to fit your needs, as it is very likely that you will not have your usernames and passwords hard-coded into the logic. It is here at the Login_Click function that you can substitute the logic with that of your own. It is common practice to substitute database logic to verify the credentials against a data table with a stored procedure.

You can also provide authorized credentials in the web.config file. Inside the forms section, you would append a user element(s), as follows :

<configuration> <system.web> <authentication mode="Forms">

Page 56: MC0081 - Answer

<forms name=".COOKIEDEMO" loginUrl="login.aspx" protection="All" timeout="30" path="/"> <credentials passwordFormat="Clear"> <user name="user1" password="password1"/> <user name="user2" password="password2"/> <user name="user3" password="password3"/> </credentials> </forms> </authentication> <authorization> <deny users="?" /> </authorization> </system.web></configuration>

Doing so allows you to authenticate against a list of users in your web.config file, easily. You can append as many users as necessary. To authenticate against that list of users, you would append the applicable logic in the click event of the cmdLogin button discussed above. Here is the code :

void Login_Click(Object sender, EventArgs E) { // authenticate user: this sample authenticates // against users in your app domain's web.config file if (FormsAuthentication.Authenticate(UserEmail.Value, UserPass.Value)) { FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked); } else { lblResults.Text = "Invalid Credentials: Please try again"; }}

Client Requirements

To enable forms authentication, cookies must be enabled on the client browser. If the client disables cookies, the cookie generated by Forms Authentication is lost and the client will not be able to authenticate.

Coming in Next Part of This Series

In the next part of this series, we'll discuss how to incorporate Active Directory with Forms Authentication, to get that Windows OS layer of security without forcing the user to authenticate twice, once through your user interface and again through the Windows user interface.