MC0081 set 1 &2 solved assingment 2012

54
1. Describe the steps involved in creating classes and objects with the help of a program in C#. Answer : Defining a Class C# is an object-oriented programming language and uses classes and structs to implement types such as Windows Forms, user interface controls, and data structures. A typical C# application consists of classes defined by the programmer, combined with classes from the .NET Framework. Classes enable you to develop applications using object-oriented programming (OOP) techniques. Classes are templates that define objects. When you create a new form in a C# project, you are actually creating a class that defines a form; forms instantiated at runtime are derived from the class. Using objects derived from predefined classes, such as a C# Form class, is just the start of enjoying the benefits of object- oriented programming – to truly realize the benefits of OOP, you must create your own classes. All generic class declarations will have one or more type parameters. C# provides many powerful ways of defining classes, such as providing different access levels, inheriting features from other classes, and enabling the programmer to specify what occurs when types are instantiated or destroyed. Classes can also be defined as generic by using type parameters that enable client code to customize the class in a type-safe and efficient manner.A single generic class, for example System.Collections. Generic.List(T) in the .NET Framework can be used by client code to store integers, strings, or any other type of object. A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type. Programmers can then create objects that are instances of this class. Unlike structures, classes support inheritance, which is a fundamental part of object- oriented programming. Declaring Classes Classes are defined by using the class keyword, as shown in the following example: The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name

description

MC0081 set 1 &2 solved assingment 2012

Transcript of MC0081 set 1 &2 solved assingment 2012

Page 1: MC0081 set 1 &2  solved assingment 2012

1. Describe the steps involved in creating classes and objects with the help of a program in C#.

Answer :

Defining a Class C# is an object-oriented programming language and uses classes and structs to implement types such as Windows Forms, user interface controls, and data structures. A typical C# application consists of classes defined by the programmer, combined with classes from the .NET Framework. Classes enable you to develop applications using object-oriented programming (OOP) techniques. Classes are templates that define objects.When you create a new form in a C# project, you are actually creating a class that defines a form; forms instantiated at runtime are derived from the class. Using objects derived from predefined classes, such as a C# Form class, is just the start of enjoying the benefits of object-oriented programming – to truly realize the benefits of OOP, you must create your own classes. All generic class declarations will have one or more type parameters. C# provides many powerful ways of defining classes, such as providing different access levels, inheriting features from other classes, and enabling the programmer to specify what occurs when types are instantiated or destroyed. Classes can also be defined as generic by using type parameters that enable client code to customize the class in a type-safe and efficient manner.A single generic class, for example System.Collections. Generic.List(T) in the .NET Framework can be used by client code to store integers, strings, or any other type of object. A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type. Programmers can then create objects that are instances of this class. Unlike structures, classes support inheritance, which is a fundamental part of object-oriented programming.

Declaring Classes Classes are defined by using the class keyword, as shown in the following example:

The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.

Creating Objects Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class. Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:

Page 2: MC0081 set 1 &2  solved assingment 2012

When an instance of a class is created, a reference to the object is passed back to the programmer. In the previous example, object1 is a reference to an object that is based on Customer. This reference refers to the new object but does not contain the object data itself. In fact, you can create an object reference without creating an object at all.

We do not recommend creating object references such as this one that does not refer to an object because trying to access an object through such a reference will fail at run time. However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:

Example

public class Person{ // Field  public string name;

// Constructor that takes no arguments.  public Person() { name = "unknown"; }

// Constructor that takes one argument.  public Person(string nm) { name = nm; }

// Method  public void SetName(string newName) { name = newName; }}class TestPerson{ static void Main() { // Call the constructor that has no parameters. Person person1 = new Person(); Console.WriteLine(person1.name);

Page 3: MC0081 set 1 &2  solved assingment 2012

person1.SetName("John Smith"); Console.WriteLine(person1.name);

// Call the constructor that has one parameter. Person person2 = new Person("Sarah Jones"); Console.WriteLine(person2.name);

// Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }}// Output: // unknown // John Smith // Sarah Jones

2. Describe the following with respect to creating Web Forms in .Net environment: a. Web Form Life Cycle b. Creating a Web FormWrite programs with corresponding output screens to demonstrate the above concepts.

Answer :

a. 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 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 render appropriate 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 any settings needed for the duration of the incoming request

are initialized. Load ViewState

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.

Page 4: MC0081 set 1 &2  solved assingment 2012

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. The load phase can be modified 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 the 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.

This can be overridden by using the SaveViewState( ) method. Render

This is where the output to be sent back to the client browser is generated. This can be overridden by 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.

This can be modified by using the Dispose( ) method.

b. Creating a Web FormTo create the simple Web Form that will be used in the next example, start

up Visual Studio .NET and open a New Project named ProgrammingCSharpWeb. Select the Visual C# Projects folder (because C# is your language of choice), select ASP.NET Web Application as the project type, and type in its name,

Page 5: MC0081 set 1 &2  solved assingment 2012

ProgrammingCSharpWeb. Visual Studio .NET will display http://localhost/ as the default location, as shown in Figure

Visual Studio places nearly all the files it creates for the project in a folder within your local machine's default web site – for example, c:\Inetpub\wwwroot\ProgrammingCSharpWeb. The solution files and other Visual Studio-specific files are stored in <drive>\Documents and Settings\<user name>\My Documents\Visual Studio Projects (where <drive> and <user name> are specific to your machine). When the application is created, Visual Studio places a number of files in your project. The Web Form itself is stored in a file named WebForm1.aspx. This file will contain only HTML. A second, equally important file, WebForm1.aspx.cs, stores the C# associated with your form; this is the code-behind file. Notice that the code-behind file does not appear in the Solution Explorer. To see the code behind (.cs) file, you must place the cursor within Visual Studio .NET, right-click the form, and choose "View Code" in the pop-up menu. You can now tab back and forth between the form itself, WebForm1.aspx, and the C# code-behind file, WebForm1.aspx.cs. When viewing the form, WebForm1.aspx, you can choose between Design mode and HTML mode by clicking the tabs at the bottom of the Editor window. Design mode lets you drag controls onto your form; HTML mode allows you to view and edit the HTML code directly. Let's take a closer look at the .aspx and code-behind files that Visual Studio creates. Start by renaming WebForm1.aspx to HelloWeb.aspx. To do this, close WebForm1.aspx, and then right-click its name in the Solution Explorer. Choose Rename and enter the name HelloWeb.aspx. After you rename it, open HelloWeb.aspx and view the code; you will find that the code-behind file has been renamed as well to HelloWeb.aspx.cs.When you create a new Web Form application, Visual Studio .NET will generate a bit of boilerplate code to get you started, as shown in Example below:

<%@ Page language="c#" Codebehind="HelloWeb.aspx.cs" AutoEventWireup="false" Inherits="ProgrammingCSharpWeb.WebForm1" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

Page 6: MC0081 set 1 &2  solved assingment 2012

<html> <head> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> </form> </body> </html>

What you see is typical boilerplate HTML except for the first line, which contains the following ASP.NET code:<%@ Page language="c#" Codebehind="HelloWeb.aspx.cs" AutoEventWireup="false" Inherits="ProgrammingCSharpWeb.WebForm1" %>The language attribute indicates that the language used on the code-behind page is C#. The Codebehind attribute designates that the filename of thatpage is HelloWeb.cs, and the Inherits attribute indicates that this page derives from WebForm1. WebForm1 is a class declared in HelloWeb.cs. public class WebForm1 : System.Web.UI.Page As the C# code makes clear, WebForm1 inherits from System.Web.UI.Page, which is the class that defines the properties, methods, and events common to all server-side pages. Returning to the HTML view of HelloWeb.aspx, you see that a form has been specified in the body of the page using the standard HTML form tag: <form id="Form1" method="post" runat="server"> Web Forms assumes that you need at least one form to manage the user interaction, and creates one when you open a project. The attribute runat="server" is the key to the serverside magic. Any tag that includes this attribute is considered a server-side control to be executed by the ASP.NET framework on the server. Having created an empty Web Form, the first thing you might want to do is add some text to the page. By switching to HTML view, you can add script and HTML directly to the file just as you could with classic ASP. Adding the following line to the body segment of the HTML page will cause it to display a greeting and the current local time: Hello World! It is now <% = DateTime.Now.ToString( ) %> The <% and %> marks work just as they did in classic ASP, indicating that code falls between them (in this case, C#). The = sign immediately following the opening tag causes ASP.NET to display the value, just like a call to Response.Write( ). You could just as easily write the line as: Hello World! It is now <% Response.Write(DateTime.Now.ToString( )); %>Run the page by pressing Ctrl-F5 (or save it and navigate to it in your browser). You should see the string printed to the browser, as in Figure

Page 7: MC0081 set 1 &2  solved assingment 2012

3. Describe the following with respect to State Management in ASP.Net: a. Cookies in ASP.NET b. Session State c. Application State

Answer :

a. Cookies in ASP.NET Introduction: Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier. A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.For example, if a user requests a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the user's browser gets the page, the browser also gets the cookie, which it stores in a folder on the user's hard disk. Later, if user requests a page from your site again, when the user enters the URL the browser looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site. You might use the information to display a message to the user or check an expiration date. Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately. Cookies help Web sites store information about visitors. Generally, cookies are one way of maintaining continuity in a Web application—that is, of performing state management. Except for the brief time when they are actually exchanging information, the browser and Web server are disconnected. Each request a user makes to a Web server is treated independently of any other request. Many times, however, it's useful for the Web server to recognize users when they request a

Page 8: MC0081 set 1 &2  solved assingment 2012

page. For example, the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting pertinent identification that helps an application know how to proceed. Cookies are used for many purposes, all relating to helping the Web site remember users. For example, a site conducting a poll might use a cookie simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials.

Cookie Limitations Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store. (See the section "Cookies and Security" below for information about security implications of storing user information.) Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined. A cookie limitation that you might encounter is that users can set their browser to refuse cookies. If you define a P3P privacy policy and place it in the root of your Web site, more browsers will accept cookies from your site. However, you might have to avoid cookies altogether and use a different mechanism to store user-specific information. A common method for storing user information is session state, but session state depends on cookies, as explained later in the section "Cookies and Session State." Although cookies can be very useful in your application, the application should not depend on being able to store cookies. Do not use cookies to support critical features. If your application must rely on cookies, you can test to see whether the browser will accept cookies.

Writing Cookies The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten. You can also set a cookie's date and time expiration. Expired cookies are deleted by the browser when a user visits the site that has written the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value to be valid. For a cookie to effectively never expire, you can set the expiration date to be 50 years from now. If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client

Page 9: MC0081 set 1 &2  solved assingment 2012

computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.You can add cookies to the Cookies collection in a number of ways. The following example shows the method using C# code to write cookies:Response.Cookies["userName"].Value = "patrick"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); HttpCookie aCookie = new HttpCookie("lastVisit"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);

The example adds two cookies to the Cookies collection, one named userName and the other named lastVisit. For the first cookie, the values of the Cookies collection are set directly. You can add values to the collection this way because Cookies derives from a specialized collection of type NameObjectCollectionBase. For the second cookie, the code creates an instance of an object of type HttpCookie, sets its properties, and then adds it to the Cookies collection via the Add method. When you instantiate an HttpCookie object, you must pass the cookie name as part of the constructor. Both examples accomplish the same task, writing a cookie to the browser. In both methods, the expiration value must be of type DateTime. However, the lastVisited value is also a date-time value. Because all cookie values are stored as strings, the date-time value has to be converted to a String.

Cookies with More Than One Value You can store one value in a cookie, such as user name and last visit. You can also store multiple name-value pairs in a single cookie. The name-value pairs are referred to as subkeys. (Subkeys are laid out much like a query string in a URL.) For example, instead of creating two separate cookies named userName and lastVisit, you can create a single cookie named userInfo that has the subkeys userName and lastVisit.You might use subkeys for several reasons. First, it is convenient to put related or similar information into a single cookie. In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the information. (Conversely, if you want to assign different expiration dates to different types of information, you should store the information in separate cookies.) A cookie with subkeys also helps you limit the size of cookie files. As noted earlier in the "Cookie Limitations" section, cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.

b. Session State ASP.NET session state enables you to store and retrieve values for a user as the user navigates the different ASP.NET pages that make up a Web application. HTTP is a stateless protocol, meaning that your Web server treats each HTTP request for a page as an independent request; by default, the server retains no knowledge of variable values used during previous requests. As a result, building Web applications that need to maintain some cross-request state information (applications that implement shopping carts, data scrolling, and so on) can be a challenge. ASP.NET session state identifies requests received from the same

Page 10: MC0081 set 1 &2  solved assingment 2012

browser during a limited period of time as a session, and provides the ability to persist variable values for the duration of that session.

ASP.NET session state is enabled by default for all ASP.NET applications. ASP.NET session-state variables are easily set and retrieved using the Session property, which stores session variable values as a collection indexed by name. For example, the following code example creates the session variables FirstName and LastName to represent the first name and last name of a user, and sets them to values retrieved from TextBox controls.

C# Code Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text;

ASP.NET stores session information in the memory space of the ASP.NET application by default. You can, optionally, store session information using a stand-alone service so that session information is preserved if the ASP.NET application is restarted, in a SQL Server so that session information is available to multiple Web servers in a Web farm (and also persists if the ASP.NET application is restarted), or in a custom data store. ASP.NET also provides several other options for persisting data within an application besides session state. ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Session Variables Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext:Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name of a user, and set them to values retrieved from TextBox controls. Session variables can be any valid .NET Framework type.

C# Code Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text;

Session Identifiers Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response.

Page 11: MC0081 set 1 &2  solved assingment 2012

By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a "cookieless" session. A session is considered active as long as requests continue to be made with the same SessionID value. If the time between requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session.

Cookieless SessionIDs By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file. The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers.<configuration> <system.web> <sessionState cookieless="true" regenerateExpiredSessionId="true" /> </system.web> </configuration>ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page's URL. When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that case, a new session is started for the request. The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier.This enables ASP.NET to resolve the application name before involving the SessionStateModule in the request. Note: To improve the security of your application, you should allow users to log out of your application, at which point the application should call the Abandon method. This reduces the potential for a malicious user to get the unique identifier in the URL and use it to retrieve private user data stored in the session.

Session Modes ASP.NET session state supports several storage options for session variables. Each option is identified as a session-state Mode type. The default behavior is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a custom data source. If you do not want session state enabled for your application, you can set the session mode to Off.

Session Events ASP.NET provides two events that help you manage user sessions. The Session_OnStart event is raised when a new session starts, and the Session_OnEnd event is raised when a session is abandoned or expires. Session events are specified in the Global.asax file for an ASP.NET application. The Session_OnEnd event is not supported if the session Mode property is set to a value other than InProc, which is the default mode. Note: If the Global.asax file or Web.config file for an ASP.NET application is modified, the application will be restarted and any values stored in application state

Page 12: MC0081 set 1 &2  solved assingment 2012

or session state will be lost. Be aware that some anti-virus software can update the last-modified date and time of the Global.asax or Web.config file for an application.

Configuring Session State Session state is configured by using the sessionState element of the system.web configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive. The sessionState element enables you to specify the following options: The mode in which the session will store data. The way in which session identifier values are sent between the client and the server. The session Timeout value. Supporting values that are based on the session Mode setting.

The following example shows a sessionState element that configures an application for SQLServer session mode. It sets the Timeout value to 30 minutes, and specifies that session identifiers are stored in the URL.<sessionState mode="SQLServer" cookieless="true " regenerateExpiredSessionId="true " timeout="30" sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;" stateNetworkTimeout="30"/>

You can disable session state for an application by setting the session-state mode to Off. If you want to disable session state for only a particular page of an application, you can set the EnableSessionState value in the @ Page directive to false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables. Concurrent Requests and Session State Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear. The following table lists key classes that relate to session state are in the SessionState namespace:Member Description SessionIDManager Manages unique identifiers

for ASP.NET session state. SessionStateItemCollection

Used to store session state variables.

Page 13: MC0081 set 1 &2  solved assingment 2012

c. Application StateApplication state is a data repository available to all classes in an ASP.NET

application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and all sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another. The topics in this section provide information on how application state works and how to use it.Using Application State Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of objects. The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class. You can use application state in two ways. You can add, access, or remove values from the Contents collection directly through code. The HttpApplicationState class can be accessed at any time during the life of an application. However, it is often useful to load application state data when the application starts. To do so, you can put code to load application state into the Application_Start method in the Global.asax file. For more information see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0. Alternatively, you can add objects to the StaticObjects collection via an <object runat="server"> declaration in your Web application's Global.asax file. Application state defined in this way can then be accessed from code anywhere in your application. The following example shows an object declaration for an application state value:<object runat="server" scope="application" ID="MyInfo" PROGID="MSWC.MYINFO"> </object>You can add objects to the StaticObjects collection only in the Global.asax file. The collection throws a NotSupportedException if you attempt to add objects directly through code. You can access members of objects stored in application state without having to reference the Application collection. The following code example shows how to reference a member of an object defined in the StaticObjects collection of application state:C# Code protected void Page_Load(Object sender, EventArgs e) Label1.Text = MyInfo.Title; End Sub

Application State Considerations When using application state, you must be aware of the following important considerations: 1. Resources: Because it is stored in memory, application state is very fast compared to saving data to disk or a database. However, storing large blocks of data in application state can fill up server memory, causing the server to page memory to disk. As an alternative to using application state, you can use the ASP.NET cache mechanism for storing large amounts of application data. The ASP.NET cache also stores data in memory and is therefore very fast; however, ASP.NET actively manages the cache and will remove items when memory becomes scarce. For more information see ASP.NET Caching Overview.

Page 14: MC0081 set 1 &2  solved assingment 2012

2. Volatility: As the application state is stored in server memory, it is lost whenever the application is stopped or restarted. For example, if the Web.config file is changed, the application is restarted and all application state is lost unless application state values have been written to a non-volatile storage medium such as a database. 3. Scalability: Application state is not shared among multiple servers serving the same application, as in a Web farm, or among multiple worker processes serving the same application on the same server, as in a Web garden. Your application therefore cannot rely on application statecontaining the same data for application state across different servers or processes. If your application runs in multi-processor or multi-server environments, consider using a more scalable option, such as a database, for data that must preserve fidelity across the application. 4. Concurrency: Application state is free-threaded, which means that application state data can be accessed simultaneously by many threads. Therefore, it is important to ensure that when you update application state data, you do so in a thread-safe manner by including built-in synchronization support. You can use the Lock and UnLock methods to ensure data integrity by locking the data for writing by only one source at a time. You can also reduce the likelihood of concurrency problems by initializing application state values in the Application_Start method in the Global.asax file.

4. Describe the following with respect to Web Services in .Net: a. Writing and Testing a Web Service b. Implementing a Web Service Client

Answer :

a. Writing a Web ServiceThe ASMX file shown in Figure 8.5 is a complete Web service. It implements two Web methods: Add and Subtract. Both take two integers as input and return an integer as well. Deploying the Web service is as simple as copying it to a directory on your Web server that is URL-addressable. If you put Calc.asmx in wwwroot, the Web service’s local URL is http://localhost/calc.asmx.Calc.asmx demonstrates several important principles of Web service programming using the .NET Framework: Web services are implemented in ASMX files. ASMX is a special file name extension registered to ASP.NET (specifically, to an ASP.NET HTTP handler) in Machine.config. ASMX files begin with @ WebService directives. At a minimum, the directive must contain a Class attribute identifying the class that makes up the Web service. Web service classes can be attributed with optional WebService attributes. The one in this example assigns the Web service a name and a description that show up in the HTML page generated when a user calls up Calc.asmx in his or her browser. The WebService attribute also supports a Namespace parameter that can be used to change the name of the XML namespace that scopes the Web service’s members. Web methods are declared by tagging public methods in the Web service class with WebMethod attributes. You can build helper methods into a Web service – methods that are used internally by Web methods but that are not exposed as Web methods themselves – by omitting the attribute. The WebMethod attributes in Figure 8.5 also assign descriptive text to their Web methods. You’ll learn more

Page 15: MC0081 set 1 &2  solved assingment 2012

about Description and other WebMethod parameters in the section entitled ―The WebMethod Attribute.‖ HTTP, XML, and SOAP are hidden under the hood. You don’t have to deal with raw XML data or SOAP messages because the .NET Framework deals with them for you.

Despite its brevity, Calc.asmx is a full-blown Web service when installed on a Web server outfitted with ASP.NET. Its Web methods can be invoked with SOAP, HTTP GET, and HTTP POST, and it’s capable of returning output in SOAP responses or simple XML wrappers. All we need now is a way to test it out. The .NET Framework lends a hand there too.

Testing a Web Service How do you test an ASMX Web service? Simple: just call it in your browser. To demonstrate, copy Calc.asmx to wwwroot and type http://localhost/calc.asmx in your browser’s address bar. You’ll be greeted with the screen shown in Figure 8.6. What happened? ASP.NET responded to the HTTP request for Calc.asmx by generating an HTML page that describes the Web service.The name and description in the ASMX file’s WebService attribute appear at the top of the page. Underneath is a list of Web methods that the service exposes, complete with the descriptions spelled out in the WebMethod attributes.

Page 16: MC0081 set 1 &2  solved assingment 2012

Click ―Add‖ near the top of the page, and ASP.NET displays a page that you can use to test the Add method (Figure 8.7). ASP.NET knows the method name and signature because it reads them from the metadata in the DLL it compiled from Calc.asmx. It even generates an HTML form that you can use to call the Add method with your choice of inputs. Type 2 and 2 into the ―a‖ and ―b‖ boxes and click Invoke. The XML returned by the Web method appears in a separate browser window

Page 17: MC0081 set 1 &2  solved assingment 2012

The forms that ASP.NET generates on the fly from ASMX files enable you to test the Web services that you write without writing special clients to test them with. They also let you explore a Web service built with the .NET Framework simply by pointing your browser to it. For kicks, type the following URL into your browser’s address bar:

http://terraservice.net/terraservice.asmx

That’s the URL of the Microsoft TerraService, an ultra-cool Web service that provides a programmatic interface to a massive database of geographic data known as the Microsoft TerraServer.

b. Implementing a Web Service ClientHere are the steps: 1. Use Wsdl.exe to create a proxy class for Calc.asmx. If you installed Calc.asmx in wwwroot, the proper command is

wsdl http://localhost/calc.asmx Wsdl.exe responds by creating a file named Calculator Web Service.cs. 2. Create a new text file named CalcClient.cs and enter the code in Figure 11-9. 3. Compile the CS files into a console application with the following command:

csc CalcClient.cs "Calculator Web Service.cs" 4. Run CalcClient.exe.

CalcClient.exe instantiates a Web service proxy and calls the service’s Add method. The resulting output proves beyond the shadow of a doubt that Calc.asmx is smart enough to add 2 and 2 CalcClient.cs using System; class MyApp { public static void Main () { CalculatorWebService calc = new CalculatorWebService (); int sum = calc.Add (2, 2); Console.WriteLine ("2 + 2 = " + sum); } }

Page 18: MC0081 set 1 &2  solved assingment 2012

Avoiding Hard-Coded Service URLs Look through a CS file generated by Wsdl.exe, and you’ll see the Web service proxy class as well as the methods that wrap the Web service’s Web methods. You’ll also see that the Web service’s URL is hardcoded into the CS file in the proxy’s class constructor. Here’s an example: public CalculatorWebService() { this.Url = "http://www.wintellect.com/calc.asmx"; } If the Web service moves, you’ll have to modify the CS file and regenerate the proxy. To avoid having to update code when a Web service’s URL changes, you can use Wsdl.exe’s /appsettingurlkey (abbreviated /urlkey) switch. The command wsdl /urlkey:CalcUrl http://www.wintellect.com/calc.asmx produces the following class constructor:public CalculatorWebService() { string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["CalcUrl"]; if ((urlSetting != null)) { this.Url = urlSetting; } else { this.Url = "http://www.wintellect.com/calc.asmx"; } }

Now you can assign a value to ―CalcUrl‖ in the appSettings section of a local Web.config file, like so:<configuration> <appSettings> <add key="CalcUrl" value="http://www.wintellect.com/calc.asmx" /> </appSettings> </configuration>If the URL changes, we can update the proxy simply by editing Web.config. No code changes are required.

Page 19: MC0081 set 1 &2  solved assingment 2012

1. Write a program in C# language to perform the following operations: a. Basic arithmetic operations b. Finding greatest of n numbers Write separate programs for each of the above points.

Answer :

a. Basic arithmetic operations

using System;using System.Collections.Generic;using System.Text; namespace SwitchCase{

Page 20: MC0081 set 1 &2  solved assingment 2012

class SwitchCaseExample { static bool ReadInteger(out int n) { string input = System.Console.ReadLine(); n = 0; try { n = Convert.ToInt32(input); return true; } catch (System.Exception ex) { System.Console.WriteLine("Error in the input format\n\n"); return false; } } static void Main(string[] args) { int a, b, opcode, result; System.Console.WriteLine("Program for Addition, Subtraction, Multiplication and Division\n"); while (true) { System.Console.Write("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: "); ReadInteger(out opcode); if (opcode < 1 || opcode > 4) return; System.Console.Write("Enter First Number:"); ReadInteger(out a); System.Console.Write("Enter Second Number:"); ReadInteger(out b); switch (opcode) { case 1: result = a + b; System.Console.WriteLine("{0} + {1} = {2}", a, b, result); break; case 2: result = a - b; System.Console.WriteLine("{0} - {1} = {2}", a, b, result); break; case 3: result = a * b; System.Console.WriteLine("{0} * {1} = {2}", a, b, result); break;

Page 21: MC0081 set 1 &2  solved assingment 2012

case 4: result = a / b; System.Console.WriteLine("{0} / {1} = {2}\n{3} % {4} = {5}", a, b, result, a, b, a % b); break; default: break; } } } }}

b. Finding greatest of n numbers

using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace ConsoleApplication23{    class Program

    {        static void Main(string[] args)        {            int i, largest;            int[] array = new int[5];            for (i = 0; i < 5; i++)            {                Console.WriteLine("Enter elements:{0}", i+1);                array[i] = Convert.ToInt32(Console.ReadLine());            }            largest = array[0];            for (i = 0; i <5; i++)            {                if (array[i] > largest)

Page 22: MC0081 set 1 &2  solved assingment 2012

                {                    largest = array[i];                }            }            Console.WriteLine("The Largest number is :{0}", largest);            Console.ReadLine();        }            }

        }

2. Explain the following with respect to ASP.Net: a. Master Pages b. Themes & Skins

Answer :

a. Master Pages Master Pages – The Master Pages feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior. Just as Themes and Skins allow you to factor out style definitions from your page code and maintain them in a common file, Master Pages do the same for page layout. A Master Pages is a page that contains markup and controls that should be shared across multiple pages in your site. For example, if all of your pages should have the same header and footer banners or the same navigation menu, you could define this in a Master Page once, and then all pages associated to this Master Page would inherit those common elements. The advantage of defining the header, footer, and navigation in a Master Page is that these elements need only be defined once, instead of multiple times in duplicate code across the pages in your site. The Master Pages are an easy way to provide a template that can be used by any number of ASP.NET pages in your application. In working with Master Pages, the developer creates a Master File that is the template referenced by a subpage or Content Page. Master Pages use a .master file extension, whereas content pages use the .aspx file extension you are used to; but content pages are declared as such within the file’s page directive.

Master and Content Pages Defining a Master Page is just like defining a normal page. Master Pages can contain markup, controls, or code, or any combination of these elements. However, a Master Page can contain a special type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be substituted with content from a page associated to the master. A

Page 23: MC0081 set 1 &2  solved assingment 2012

ContentPlaceHolder can also contain default content, just in case the derive page does not need to override this content. The syntax of a ContentPlaceHolder control is given below:<%-- ContentPlaceHolder control --%> <asp:contentplaceholder id="FlowerText" runat="server"/> <%-- ContentPlaceHolder with default content --%> <asp:contentplaceholder id="FlowerText" runat="server"> <h3>Welcome to my florist website!</h3> </asp:contentplaceholder>To differentiate a Master Page from a normal page, a Master Page is saved under the .master file extension. A page can derive from a Master Page by defining a MasterPageFile attribute on its Page directive, as demonstrated below. A page that is associated to a Master Page is called a Content Page.<%@ Page MasterPageFile="Site.master" %>A Content Page can declare Content controls that specifically override content placeholder sections in the Master Page. A Content control is associated to a particular ContentPlaceHolder control through its ContentPlaceHolderID property. A Content Page may only contain markup and controls inside Content controls; it cannot have any top-level content of its own. It can, however, have directives or server-side code.<%@ Page MasterPageFile="Site.master" %> <asp:content id="Content1" contentplaceholderid="FlowerText" runat="server"> With sunshine, water, and careful tending, roses will bloom several times in a season. </asp:content> <asp:content id="Content2" contentplaceholderid="FlowerPicture" runat="server"> <asp:Image id="image1" imageurl="~/images/rose.jpg" runat="server"/> </asp:content>The following example demonstrates the relationship between Master and Content pages. The Master Page in this case defines two ContentPlaceHolder regions, named FlowerPicture and FlowerText, along with some default content for those regions. Individual content pages in the site inherit the common site layout and look-and-feel from the Master Page, but override the default content for the named ContentPlaceHolder regions with their own content. Note that the Default.aspx page in this site does not define any Content controls, and so it just inherits the default content from the Master Page.

The source code for the above web page using C# is given below:<%@ master language="C#" %> <html> <head> <link rel="stylesheet" href="StyleSheet.css" type="text/css" /> </head> <body> <form id="Form1" runat="server"> <div> <table class="main" cellspacing="0" cellpadding="2">

Page 24: MC0081 set 1 &2  solved assingment 2012

<tr class="header"> <td colspan="2" class="header"/> </tr> <tr valign="top"> <td class="sidebar" rowspan="2"> <a href="daffodil.aspx">Daffodil</a><br/> <a href="rose.aspx">Rose</a><br/> <a href="dahlia.aspx">Dahlia</a><br/> <a href="hydrangea.aspx">Hydrangea</a><br/> <a href="daisy.aspx">Daisy</a><br /> </td> <td class="body"> <asp:contentplaceholder id="FlowerText" runat="server"> <h3>Welcome to my florist website!</h3> We have an enormous selection of quality flowers and seeds, available for shipping to any location worldwide. Let us handle all you gardening needs! </asp:contentplaceholder> <br /><br /> <asp:contentplaceholder id="FlowerPicture" runat="server"> <img alt="water lilies" src="Images/waterlilies.jpg"/> </asp:contentplaceholder> <br /><br /> <asp:adrotator id="MyAdRotator" advertisementfile="Ads.xml" runat="server"/> </td> </tr> <tr> <td class="footer"> <asp:label id="Footer" font-italic="true" text="Copyright Microsoft 2003" runat="server" /> </td> </tr> </table> </div> </form> </body> </html>

URL Rebasing in a Master Page One thing to notice about the preceding example is that there are several places in the Master Page that refer to URL resources like images or stylesheet or page references using a relative-path syntax, for example:<head> <link rel="stylesheet" href="StyleSheet.css" type="text/css" /> </head> ... <a href="daffodil.aspx">Daffodil</a> ... <img alt="water lilies" src="Images/waterlilies.jpg"/>This works fine when the Master Page and Content Page are in the same directory, but when the Content Page is in a physically separate location, the relative path will not be correct. To solve this problem, you may take one of the following approaches: Use absolute URL paths in the Master Page, for example

Page 25: MC0081 set 1 &2  solved assingment 2012

<img src="/myapplication/images/banner.gif" />

Use relative or application-relative URLs in server controls instead of static markup, for example <asp:Image ImageUrl="~/images/banner.gif" runat="server" /> The following example demonstrates this technique. The Content Pages have been moved to a subdirectory "Pages" under the directory that contains the Master Page. The Master Page has been updated to use server controls in place of HTML:<head runat="server"> <link rel="stylesheet" href="StyleSheet.css" type="text/css" /> </head> ... <a id="A1" href="pages/daffodil.aspx" runat="server">Daffodil</a/> ... <asp:Image ID="Image1" AlternateText="Water Lillies" ImageUrl="~/Images/Waterlilies.jpg" runat="server"/>

Accessing a Master Page from Code In addition to overriding content, it is possible for a Content Page to programmatically access its Master Page. A Content Page creates a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, specifying the virtual path to the master page:<%@ MasterType VirtualPath="Site.master" %>

The Content Page can then reference the Master Page using the Master property of the Page class:

C# Code Master.FooterText = "This is a custom footer"; AdRotator ad = (AdRotator)Master.FindControl("MyAdRotator"); Master.FooterText = "This is a custom footer" Dim ad As AdRotator = Master.FindControl("MyAdRotator");In the code example above, FooterText is a public property exposed on the Master Page, while MyAdRotator is a control on the Master Page.

Nesting Master Pages Content Pages can also be Master Pages. That is, it is possible to derive a Master page from another Master Page. For example, you might have a top-level Master Page that represents the overall site header/footer and navigation of your site, and then separate Master Pages that derive from this Master in order to define different looks for the various sub-sections within your site. Content Pages would then derive from the appropriate section master for the section the Content Page belongs to. The following example demonstrates this idea, dividing the Florist example site into two sections, Annuals and Perennials.

Page 26: MC0081 set 1 &2  solved assingment 2012

The following is the code for the Home Page of the Nested Pages:<%@ page language="C#" MasterPageFile="~/Site4.master" %>

b. Themes & Skins

Creating Themes Themes and Skins: The Themes and Skins feature of ASP.NET allows you to factor style and layout information into a separate group of files, collectively called a Theme. A Theme can then be applied to any site to affect the look and feel of pages and controls within the site. Style changes to a site can then be easily maintained by making changes to the Theme, without having to edit the individual pages in your site. Themes can also be shared with other developers. When you build a web application, it usually has a similar look-and-feel across all its pages. Not too many applications are designed with each page dramatically different from each other. In general, your applications use similar fonts, colors, and server control styles across all the pages within the application. You can apply these common styles individually to each and every server control or objects on each page, or you can use a capability provided by ASP.NET to centrally specify these styles. All pages or parts of pages in the application can then access them. Themes are the text-based style definitions in ASP.NET. You create .skin files in the Theme folder. A .skin file can contain one or more control skins for one or more control types. You can define skins in a separate file for each control or define all the skins for a theme in a single file.There are two types of control skins, default skins and named skins: A Default Skin automatically applies to all controls of the same type when a theme is applied to a page. A Control Skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.) A Named Skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows

Page 27: MC0081 set 1 &2  solved assingment 2012

you to set different skins for different instances of the same control in an application.

Cascading Style Sheets A theme can also include a cascading style sheet (.css file). When you put a .css file in the theme folder, the style sheet is applied automatically as part of the theme. You define a style sheet using the file name extension .css in the theme folder. The following are the uses of ASP.NET Themes: They enable you to define visual styles for your Web Pages They also allow you to apply styles, graphics They allow you to apply the CSS files themselves to the pages of an application They can be applied at the application, page, or server control level.

An ASP Page that does not use themes <% Page Language = VB” %> <html xmlns = http://www.w3.org/1999/xhtml> <head runat = “server”> <title>STLNET</title> </head> <body><form id = “form1” runat = “server”> <h1> St. Louis .NET User Group</h1><br /> <asp:Textbox ID = “Textbox1” runat = “server”/> <br /> <br /> <asp:Calendar ID = “Calendar1” runat = “server”/> <br /> <asp:Button ID = “Button1” runat = “server” Text = “Button” /> </form> </body> </html>This simple page shows some default server controls, but which you can change with one of these new ASP.NET themes. You can instantly change the appearance of this page without changing the style of each server control on the page. From within the Page directive, you simply apply an ASP.NET theme that you have either built or downloaded from the Internet: <%@ Page Language = “VB” Theme = “SmokeAndGlass” %> Adding the Them attribute changes the appearance of everything on the page that is defined in an example SmokeAndGlass theme file. If you have multiple pages, you do not have to think about applying styles to everything you do as you build because the styles are already defined centrally for you.

Applying a Theme to an Entire Application You can apply a Theme to your entire application using the web.config file.Example: Applying a Theme to an Entire Application<?xml Version = “1.0”> <configuration> <system.web> <pages theme = “SmokeAndGlass”> </ system.web> </configuration>By specifying the Theme in your web.config file, you need not define the theme again in the Page directive of your ASP.NET pages. This theme is applied automatically to each and every page within your application.

Page 28: MC0081 set 1 &2  solved assingment 2012

In order to apply the theme to only a specific part of an application, make use of the <location/> element to specify the areas of the application for which the theme should be applied.

Removing Themes from the Server Controls Some times you want an alternative to the theme that has already been defined. As an example, to change the text box server control that you have been already working with by making its background black and using white text: <asp:Textbox ID = TextBox1” runat = “server” BackColor = “#000000” ForeColor = “#ffffff” /> To apply a theme to your ASP.NET page but not to the Textbox control, use the EnableTheming property of the Textbox Server Control: <asp:Textbox ID = TextBox1” runat = “server” BackColor = “#000000” ForeColor = “#ffffff” EnableTheming = “false” /> To turn off the theming property for multiple controls within a page, consider using the Panel Control (or any Container Control) to encapsulate a collection of controls and then set the EnableTheming attribute of the Control Panel to false. This disables the theming for each and every control within the panel.

Removing Themes from Web pages Suppose that you have set the theme for the entire application using web.config file, and you want to exclude a single ASP.NET page; which could be made possible by removing a theme setting at the page level. The Page directive for every ASP.NET web page includes an EnableTheming Attribute that can be used to remove theming from your ASP.NET pages. To remove the theme that would be applied by the theme setting in the web.config file, you simply construct your corresponding Page directive as follows:

<%@ Page Language =”VB” EnableTheming = “False” %> This statement constructs the theme setting to nothing and removes any settings specified in the web.config file for that particular page.Note: The .skin files are used to define styles for ASP.NET server controlsIf the themes are disabled by setting the EnableTheming attribute is set to False at the page level, we can still enable theming for specific controls on that page by setting EnableTheming for those specific controls to true and applying a specific theme at the same time as shown in the example given below:<asp:Textbox ID = TextBox1” runat = “server” BackColor = “#000000” ForeColor = “#ffffff” EnableTheming = “true” SkinID = “mySkin”/>

Usage of Themes with Master Pages The ASP.NET applications that use Master pages have both the Page and Master page directives that contain an EnableTheming attribute.If this is the case, what is the behavior of any content pages using the master page? If the content page that is using this master page does not make any specification on theming (it does not use the EnableTheming attribute), what is specified in the master page naturally takes precedence and no theme is utilized as required by the false setting. Even if you have set the EnableTheming attribute’s value in the content page, any value specified in the master page takes precedence. That is, if the theming is set to false in the master page and set to true in the content page, the page is constructed with the value provided from the master page, which in this case is false. Even if the value is set to false in the master page, you can override this setting at the control level rather than doing it in the Page directive of the content page.

Page 29: MC0081 set 1 &2  solved assingment 2012

Creation of User-Defined Themes Users can define their own themes to the pages they would create within an application. These themes created can be applied at the following levels within an application: Application Level Page Level Server Control Level

Themes are a way of applying a consistent look and feel across entire application. To create your own themes at first, you have to create a proper folder structure in your application. Step1: Right click the project and add a new folder Step 2: Name the folder appropriately (for example: App_Themes)Step 3: You can also create this folder by right – clicking on your project in Visual Studio and selecting Add ASP.NET Folder Theme. Note: When you execute step3 of above, the theme folder within the App_Themes folder does not have the typical folder icon next to it, instead it has a folder icon that includes a paint brush as shown below: Within the existing (or newly created) themes folder, we can create an additional theme folder for each and every theme that you can use in your application. For Example: If you are going to have four themes – Summer, Fall, Winter, and Spring – then you create four folders that are named appropriately. Each theme folder must contain the elements of the theme, that can include the following: A single skin file CSS Files Images

Adding a CSS to your Themes In addition to the server control definitions that can be created from within a .skin file, we can make further definitions using Cascading Style Sheets (CSS). With a .skin file, we could define only the styles associated with server controls and nothing else. For a theme that goes beyond the server controls, we must further define the theme style so that HTML server controls, HTML, and raw text are all changed in accordance with the theme. This can be done by including a CSS file within your theme folder. It is an easy task to create CSS files for your themes with Visual Studio 2008.Example: Right click the Summer theme folder and select Add New Item. In the list of options, select the option Style Sheet and name it Summer.css. The Summer.css file should be sitting right next to your Summer.skin file. This creates an empty .css file for your theme. To create comprehensive theme with this dialog, you define each HTML element that might appear in the ASP.NET page or you make use of class names or element IDs. Example: Creation of a simple CSS file that changes some of the non-server control items on a ASP.NET page. The sample code for this file creation is shown below:body { font – size: x-small; font – family: Verdana; color: #004000; }

Page 30: MC0081 set 1 &2  solved assingment 2012

a: link { color: Blue; text-decoration: none; } a: visited { color: Blue; text-decoration: none; } a: hover { color: Red; text-decoration: underline overline; }In this CSS file four things are defined: You define the text that is found within the <body> tag of the page (basically all the text). In general, plenty of text can appear in a typical ASP.NET page that is not placed inside an <asp:Label> or <asp:Literal> tag. Therefore you can define how your text should appear in the CSS file; otherwise your web page may appear quite odd at times. In this case, a definition is in place for the size, the font family, and the color of the text.

The next three definitions in the CSS file revolve around the <a> (anchor tag element used for hyperlinks). The A: link definition defines the look of a hyperlink on a web page. The A: visited definition defines the look of the link of a web page already visited by the user previously.

The A: hover definition defines the appearance of the hyperlink when the end user hovers on a hyper-link. Skin Creation: A skin is a definition of styles applied to the server controls in your ASP.NET page. Skins can work in conjunction with CSS files or images. To create a theme to use in your ASP.NET application, you use a single skin file in the theme folder. The skin file can have any name, but it must have a .skin file extension. Example: Creation of the Summer theme Right – click the Summer folder, select Add New Item, and select Skin. Name the file Summer.skin.The listing for the Summer.skin file is shown below:The Summer.skin file

<asp:Label runat = “server” Forecolor = “#004000” Font-Names = “Verdana” Font-Size = “X-Small” /> <asp:Textbox runat = “server” Forecolor = “#004000” Font-Names = “Verdana” Font-Size = “X-Small” BorderStyle=”Solid” BorderWidth = “1px” BorderColor = “#004000” Font-Bold = “True” /> <asp:Button runat = “server” Forecolor = “#004000” Font-Names = “Verdana” Font-Size = “X-Small” BorderStyle=”Solid” BorderWidth = “1px” BorderColor = “#004000” Font-Bold = “True” BackColor = “#FFE0C0” />To use the above listing in a real application, you should actually make a definition for each and every server control option.

Page 31: MC0081 set 1 &2  solved assingment 2012

If you specify the runat = “server” attribute in the skinned version of the control, you also include it in the server control you put on an .aspx page that uses this theme.Using the Summer theme in an ASP.NET page Using C# Language <%@ Page Language = “C#” Theme = “Summer” %> <script runat = “server”> protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = “Hello” + TextBox1.Text.ToString(); } </script>

Page 32: MC0081 set 1 &2  solved assingment 2012

The App_Themes Folder Themes reside in the App_Themes folder directly under the application root directory. A Theme consists of a named subdirectory under this folder that contains a collection of one or more Skin files, named with the .skin extension. A Theme can also contain a CSS file and/or subdirectories for static files like images. The figure below shows an App_Themes directory with two Themes defined, named "Default" and "White", each of which has a single skin file and CSS file.

Observe in the previous example that the contents of a skin file are simply control definitions as they might appear in a page. A skin file can contain multiple control definitions, for example one definition for each control type. The properties of controls defined in the theme automatically override the local property value for a control of the same type in the target page with the Theme applied. For example, a <asp:Calendar Font-Name="Verdana" runat="server"/> control definition in a skin file will cause all Calendar controls in pages with the Theme applied to use the Verdana font. A local value for this property on the control will be overridden by the Theme. Note that it is an error to specify an ID property value for a control definition in a skin file.

Global and Application Themes A Theme can reside at the application-level or machine-level (globally available to all applications). Application-level Themes are placed in the App_Themes directory

Page 33: MC0081 set 1 &2  solved assingment 2012

under the application root directory, as described above. Global Themes are placed in a "Themes" directory under an ASP.NETClientFiles folder under the ASP.NET installation directory, for example %WINDIR%\Microsoft.NET\Framework\<version>\ASP.NETClientFiles\Themes. The location of global themes is Inetpub\ wwwroot\aspnet_ client\system_web\<version>\Themes for IIS web sites.

Assigning a Theme to a Page An individual page can be assigned a Theme by setting the <%@ Page Theme="..." %> directive to the name of a global or application-level Theme (the name of a folder under the Themes or App_Themes directory). A page can only have one Theme applied, but there may be multiple skin files in the theme that apply style settings to controls in the page.

3. Design a simple Window based form application to perform basic arithmetic operations.

Answer :We have to write the following code in the .cs file. 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace Calculator{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        string i, j;        static char c;        private void btnthree_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(3);        }        private void btnone_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(1);        }        private void btntwo_Click(object sender, EventArgs e)       {            textBox1.Text += Convert.ToString(2);        }         private void btnfour_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(4);        } 

Page 34: MC0081 set 1 &2  solved assingment 2012

        private void btnfive_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(5);        }         private void btnsix_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(6);        }         private void btnseven_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(7);        }         private void btneight_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(8);        }         private void btnnine_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(9);        }         private void btnzero_Click(object sender, EventArgs e)        {            textBox1.Text += Convert.ToString(0);        }         private void btnplus_Click(object sender, EventArgs e)        {            i = textBox1.Text;            textBox1.Text = "";            c = '+';        }        private void btnminuse_Click(object sender, EventArgs e)        {            i = textBox1.Text;            textBox1.Text = "";            c = '-';        }        private void btnmultiply_Click(object sender, EventArgs e)        {           i = textBox1.Text;            textBox1.Text = "";            c = '*';        }        private void btndivide_Click(object sender, EventArgs e)        {            i = textBox1.Text;            textBox1.Text = "";            c = '/';        }        private void btnmodulo_Click(object sender, EventArgs e)        {            i = textBox1.Text;            textBox1.Text = "";            c = '%';        }

Page 35: MC0081 set 1 &2  solved assingment 2012

        private void btnequal_Click(object sender, EventArgs e)        {            j = textBox1.Text;            calclocalhost.CalcWebService obj = new calclocalhost.CalcWebService();            textBox1.Text = obj.calculate(i, j, c);        }    }}Run the application.

Output:

4. Describe the following with respect to Web site deployment in ASP.Net: a. Creating Application Pools (IIS 6.0) b. Deploying ASP.NET Applications

Answer :

a. Creating Application Pools (IIS 6.0) With IIS 6.0 running in worker process isolation mode, you can group Web

applications into application pools. Application pools allow specific configuration settings to be applied to groups of applications, and the worker processes servicing those applications. Any Web directory or virtual directory can be assigned to an application pool.By creating new application pools and assigning Web sites and applications to them, you can make your server more efficient and reliable, and your other applications always available, even when the applications in the new application pool terminate.

ProceduresCreating Application Pools (IIS 6.0) When you run IIS 6.0 in worker process isolation mode, you can isolate different Web applications or Web sites in pools, which are called Application Pools. An

Page 36: MC0081 set 1 &2  solved assingment 2012

application pool is a group of URLs that are routed to one or more worker processes that share the same configuration. The URLs that you assign to an application pool can be for an application, a Web site, a Web directory, or a virtual directory. In an application pool, process boundaries separate each worker process from other worker processes so that when an application is routed to one application pool, applications in other application pools do not affect that application. By using an application pool, you can assign specific configuration settings to a worker process (or, in the case of a Web garden, to a set of worker processes) that services a group of applications. For example, you can configure worker process recycling, which offers several configuration options to match the needs of each application. If, for example, you suspect that an application has a memory leak, you might configure the application pools worker process to recycle when its memory use reaches a certain threshold. If another application fails because of the volume of requests that it receives, you can set the application pools worker process to recycle when the application exceeds a specified number of requests. By creating new application pools and assigning Web sites and applications to them, you can make your server more efficient, reliable, and secure, and ensure that your applications remain available even when a worker process serving an application pool is recycled because of a faulty application.

Configuring Application Pools in IIS 6.0 (IIS 6.0) Note: This feature of IIS 6.0 is available only when running in worker process isolation mode. An application pool is a configuration that links one or more applications to a set of one or more worker processes. Because applications in an application pool are separated from other applications by worker process boundaries, an application in one application pool is not affected by problems caused by applications in other application pools. By creating new application pools and assigning Web sites and applications to them, you can make your server more efficient and reliable, as well as making your other applications always available, even when the worker process serving the new application pool has problems.

Guidelines for Creating Application Pools To isolate Web applications on a Web site from Web applications on other sites running on the same computer, create an individual application pool for each Web site. For enhanced security, configure a unique user account (process identity) for each application pool. Use an account with the least user rights possible, such as Network Service in the IIS_WPG group. If there is a test version of an application on the same server with the production version of the application, separate the two versions into different application pools. This isolates the test version of the application. As a design consideration, if you want to configure an application to run with its own unique set of properties, create a unique application pool for that application. Note: You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".

Steps to create a new Application Pool:

Page 37: MC0081 set 1 &2  solved assingment 2012

1. In IIS Manager, expand the local computer, right-click Application Pools, point to New, and then click Application Pool. 2. In the Application pool name box, type the name of the new application pool. 3. If the ID that appears in Application pool ID box is not the ID that you want, type a new ID. 4. Under Application pool settings, click the appropriate setting. If you click Use existing application pool as template, in Application pool name box, right-click the application pool that you want to use as a template. 5. Click OK.

Application pools allow you to apply configuration settings to groups of applications and the worker processes that service those applications. Any Web site, Web directory, or virtual directory can be assigned to an application pool.

Assigning an application to an application pool: In IIS Manager, right-click the application that you want to assign to an application pool, and then click Properties. Click the Virtual Directory, Directory, or Home Directory tab. If you are assigning a directory or virtual directory, verify that Application name is filled in. If the Applicationname box is not filled in, click Create, and then type a name. In the Application pool list box, click the name of the application pool to which you want to assign the Web site.

About Configuring Servers for Applications (IIS 6.0) Internet Information Services (IIS) 6.0 delivers Web hosting services through an adjustable architecture that you can use to manage server resources with improved stability, efficiency, and performance. IIS separates applications into isolated pools and automatically detects memory leaks, defective processes, and over-utilized resources. When problems occur, IIS manages them by shutting down and redeploying faulty resources and connecting faulty processes to analytical tools. IIS can run in either of two mutually exclusive modes of operation: Worker process isolation mode. This is the default mode of IIS 6.0, isolates key components of the World Wide Web Publishing Service (WWW service) from the effects of errant applications, and it protects applications from each other by using the worker process component. Use worker process isolation mode unless you have a specific compatibility issue that makes the use of IIS 5.0 isolation mode necessary. Web sites that serve static content or simple ASP applications should be able to move to IIS 6.0 running in worker process isolation mode with little or no modification.

IIS 5.0 isolation mode. With this mode, you can run applications that are incompatible with worker process isolation mode because they were developed for earlier versions of IIS. Applications that run correctly on IIS 5.0 should run correctly on IIS 6.0 in IIS 5.0 isolation mode. Worker process isolation mode provides better default security for running Web applications than IIS 5.0 isolation mode. By default, worker processes run with the Network Service identity. The Network Service account has lower access rights than the default account for IIS 5.0 isolation mode. Web applications that run in-process in IIS 5.0 application mode run as LocalSystem. The LocalSystem account can read, execute, and change most of the resources on the computer. The default isolation mode upon installing IIS 6.0 depends on whether you perform a clean installation or an upgrade.

Page 38: MC0081 set 1 &2  solved assingment 2012

After a clean install of IIS 6.0, IIS runs in worker process isolation mode. After an upgrade from an earlier version of IIS 6.0, the isolation mode is the same as configured on the previously-installed version of IIS 6.0. After an upgrade from IIS 5.0 or IIS 4.0, IIS 6.0 runs in IIS 5.0 isolation mode by default to maintain compatibility with your existing applications.

Worker Process Isolation Mode IIS 6.0 introduces worker process isolation mode, which runs all Web applications in an isolated environment. When you run IIS in worker process isolation mode, applications can be configured to run in separate application pools. Each application pool is a logical representation of a configurable worker process and links to the applications in the pool. Worker processes operate independently of each other; they can fail without affecting other worker processes. The pooling of applications protects applications from the effects of worker processes that support other application pools. In this way, applications are protected from each other.

In worker process isolation mode, Hypertext Transfer Protocol (HTTP) requests are routed directly to an in-kernel application pool queue serving the configured application. Worker processes that serve an application pool pull the requests directly from the queue, avoiding process-switching overhead. To further protect your WWW service, IIS 6.0 isolates critical World Wide Web Publishing Service (WWW service) components, such as the HTTP protocol stack (HTTP.sys) and WWW Service Administration and Monitoring, from the effects of third-party code running in worker processes. HTTP.sys receives and queues requests for WWW services. When a worker process enters an unhealthy state, and thus stops processing requests, HTTP.sys continues to process requests. Meanwhile, the WWW service detects that the worker process is unhealthy and shuts it down. If there is demand for a new worker process to serve requests (HTTP.sys has requests queued), the WWW service starts a new worker process to pick up the queued requests from HTTP.sys. Even though a worker process has failed, the WWW service continues to process requests and shields the user from experiencing a loss of service. IIS 6.0 worker process isolation mode delivers the following specific improvements over earlier versions of IIS: Robust Performance Isolation prevents Web applications and Web sites from affecting each other or the WWW service. Reboots of the operating system and restarting of the WWW service are avoided. Self - Healing Automated management provides auto-restart of failed worker processes and periodic restart of deteriorating worker processes. Scalability Web gardens allow more than one worker process to serve the same application pool. Process Affinity enables the connection of worker processes to specific processors on multi-CPU servers. Automated Debugging The debugging feature enables the automatic assignment of failing worker processes to debugging tools. CPU Limiting This monitoring feature enables controlling the amount of CPU resources that an application pool consumes in a configured amount of time.

b. Deploying ASP.NET Applications

Deploying ASP.NET Applications in IIS 6.0 (IIS 6.0) Microsoft® Windows® Server 2003 includes support for ASP.NET applications and the Microsoft .NET Framework version 1.1 with the operating system installation.

Page 39: MC0081 set 1 &2  solved assingment 2012

This chapter describes how to deploy ASP.NET applications on a newly installed server running Internet Information Services (IIS) 6.0. Version 1.1 of the .NET Framework is installed with Windows Server 2003. Most ASP.NET applications run without modification on version 1.1 of the .NET Framework. Overview of Deployment process using IIS 6.0 ASP.NET is a unified Web application platform that provides services to help you build and deploy enterprise-class Web applications and XML-based Web services. ASP.NET is supported on the Microsoft® Windows® Server 2003, Standard Edition; Windows® Server2003, Enterprise Edition; Windows® Server2003, Datacenter Edition; and Windows® Server2003, Web Edition operating systems. ASP.NET is installed with the Microsoft .NET Framework version 1.1 as a part of Windows Server 2003. However, to run ASP.NET applications, you must also install IIS 6.0. ASP.NET is not available on the following operating systems: Microsoft® Windows® XP 64-Bit Edition; the 64-bit version of Windows® Server 2003, Enterprise Edition; and the 64-bit version of Windows® Server 2003, Datacenter Edition. The deployment process presented in this section describes how to deploy ASP.NET applications on a newly installed IIS 6.0 Web server. Before you begin this process, complete the following steps: Install Windows Server 2003, which includes version 1.1 of the .NET Framework, with the default options. Install IIS 6.0 with the default settings in Add or Remove Programs in Control Panel.

When you configure IIS 6.0 to run in IIS 5.0 isolation mode, the settings in the <processModel> section of the Machine.config file are configured in the same way as they were in IIS 5.0 – in the Machine.config or Web.config files. Upon completing the process described in this section, you will have a Web server running IIS 6.0 and hosting your ASP.NET applications. However, you can further configure the Web server to improve the security and availability of your ASP.NET applications. Deployment Process using IIS 6.0 The process for deploying new ASP.NET applications on a newly installed Web server requires no understanding of earlier versions of IIS or the .NET Framework. All the ASP.NET configuration sections in the Machine.config and Web.config files are configured the same way in IIS 6.0, except for the <processModel> section of the Machine.config file. When IIS 6.0 is configured to run in worker process isolation mode, some of the attributes in the <processModel> section of the Machine.config file are now in equivalent IIS 6.0 metabase properties. In addition, if your ASP.NET applications need to retain session state, you must configure IIS 6.0 to use the appropriate ASP.NET application session state method. Depending on the method you select, you might need to configure the ASP.NET state service or Microsoft SQL Server™ to act as the repository for centralized state storage. The process for deploying ASP.NET applications in IIS 6.0 is shown in Figure

Page 40: MC0081 set 1 &2  solved assingment 2012

Deploy the Web Server 1. Install Windows Server 2003. 2. Install and configure IIS 6.0. 3. Enable ASP.NET in the Web service extensions list.

Install ASP.NET Applications 1. Create Web sites and virtual directories for each ASP.NET application by doing the following: Create Web sites and home directories. Create virtual directories.

2. Copy ASP.NET application content to the Web server.3. Enable common storage for ASP.NET session state by completing the following steps: Step-1: Select the method for maintaining and storing ASP.NET session state. Step - 2: If you have decided to maintain session state with the ASP.NET state service, configure out-of-process session state with the ASP.NET state service. Step - 3: If you have decided to maintain session state with SQL Server, configure out-of-process session state with SQL Server. Step - 4: Configure encryption and validation keys. Step - 5: Configure ASP.NET to use the appropriate session state. Step - 6: Secure the ASP.NET session state connection string. Complete the ASP.NET Application Deployment Ensure the security and availability of your ASP.NET applications. Verify that the ASP.NET applications were deployed successfully. Back up the Web server. Enable client access to your ASP.NET applications.

Deploying the Web Server (IIS 6.0) You must install the Web server before you can install your ASP.NET applications. In addition to installing Windows Server 2003, you must install and configure IIS 6.0 on the Web server. You must also enable ASP.NET so that the Web server can run ASP.NET applications.

Page 41: MC0081 set 1 &2  solved assingment 2012

Installing Windows Server 2003 (IIS 6.0) The deployment process presented here assumes that you install Windows Server 2003 with the default options. If you use other methods for installing and configuring Windows Server 2003, such as unattended setup, your configuration settings might be different. Note: When you complete the installation of Windows Server 2003, Manage Your Server automatically starts. The deployment process assumes that you quit Manage Your Server, and then further configure the Web server in Add or Remove Programsin Control Panel.

Installing and Configuring IIS 6.0 (IIS 6.0) Because IIS 6.0 is not installed during the default installation of Windows Server 2003, the next step in deploying the Web server is to install and configure IIS 6.0. The deployment process presented here assumes that you install IIS 6.0 with the default options in Add or Remove Programs in Control Panel. If you use other methods for installing and configuring Windows Server 2003, such as Manage Your Server, the default configuration settings might be different.

Install and configure IIS 6.0 by completing the following steps: Step – 1: Install IIS 6.0 with only the essential components and services. As with installing Windows Server 2003, the primary concern when installing and configuring IIS 6.0 is to ensure that the security of the Web server is maintained. Enabling unnecessary components and services increases the attack surface of the Web server. You can help ensure that the Web server is secure by enabling only the essential components and services in IIS 6.0. Step – 2: If you want to manage the Web site content by using Microsoft® FrontPage®, install FrontPage 2002 Server Extensions from Microsoft on the Web server.

Enabling ASP.NET in the Web Service Extensions List (IIS 6.0) After you install IIS 6.0, you need to enable ASP.NET. You can enable ASP.NET in Add or Remove Windows Components, which is accessible from Add or Remove Programs in Control Panel. When you enable ASP.NET by using this method, ASP.NET is also enabled in the Web service extensions list. If you enabled ASP.NET in this way, then you can continue to the next step in the deployment process.

ASP.NET is not Enabled ASP.NET might not be enabled in the Web service extensions list if either of the following is true: You installed a version of the .NET Framework and ASP.NET (other than version 1.1) from a Web download or as part of an application such as the Microsoft Visual Studio® .NET development tool. You disabled ASP.NET in the Web service extensions list because you were not running ASP.NET applications on an existing Web server.

Page 42: MC0081 set 1 &2  solved assingment 2012

If ASP.NET is not already enabled, view the Web service extensions list in IIS Manager and configure the status of the ASP.NET v1.1.4322 Web service extension to Allowed.

Installing ASP.NET Applications (IIS 6.0) After the Web server is deployed, you can install your ASP.NET applications. First, you must create a Web site and virtual directories for each ASP.NET application. Then you need to install each ASP.NET application in the corresponding Web site and virtual directory. When there are provisioning or setup scripts for your ASP.NET applications, use these scripts to install the ASP.NET applications on the Web server. Because the provisioning and setup scripts create the Web sites and virtual directories while installing ASP.NET applications, you do not need to perform any manual steps to install the ASP.NET applications. In this case, run the provisioning or setup scripts to install and configure the Web sites and applications, and then continue to the next step in the application deployment process. Figure 9.4 below illustrates the process for installing your ASP.NET applications.

Creating Web Sites and Virtual Directories for each ASP.NET Application (IIS 6.0) For each ASP.NET application, you must create a virtual directory in a new or existing Web site. Later in the installation process, you will install your ASP.NET applications into their corresponding Web sites and virtual directories.Create the Web sites and virtual directories for your ASP.NET applications by completing the following steps: Create Web sites and home directories. Create virtual directories.

Creating Web Sites and Home Directories Using IIS 6.0 Each Web site must have one home directory. The home directory is the central location for your published Web pages. It contains a home page or index file that serves as a portal to other pages in your Web site. The home directory is mapped to the domain name of the Web site or to the name of the Web server. Create a Web site and home directory for an ASP.NET application by completing the following steps: Step – 1: Create the folder that will be the home directory for the Web site on the Web server. The folder that is the home directory of the Web site contains all of the content and subdirectories for the Web site. The folder can be created on the same computer as the Web server or on a Universal Naming Convention (UNC)–shared folder on a separate server. At a minimum, create the folder on the following: An NTFS file system partition, which helps ensure proper security.

Page 43: MC0081 set 1 &2  solved assingment 2012

A disk volume other than the system volume, which reduces the potential of an attack on a Web site bringing down the entire Web server and improves performance. In a location that will not require requests for Web site content to contain /bin in the requested URL. As a security measure, ASP.NET returns a 404 error for all requests containing /bin in the requested URL. Step – 2: Create the Web site on the server.Step – 3: If the Web site is FrontPage extended, then configure the Web site on the Web server to be FrontPage extended.

Creating Virtual Directories (IIS 6.0) A virtual directory is a folder name, used in an address, which corresponds to a physical directory on the Web server or a Universal Naming Convention (UNC) location. This is also sometimes referred to as URL mapping. Virtual directories are used to publish Web content from any folder that is not contained in the home directory of the Web site. When clients access content in a virtual directory, the content appears to be in a subdirectory of the home directory, even though it is not. For security reasons, you might want to move the Web site content to a different disk volume during the application deployment process. You can move the content to another disk volume on the Web server or to a shared folder on a separate server. You can use virtual directories to specify the UNC name for the location where the content is placed, and provide a user name and password for access rights. For each virtual directory required by the ASP.NET application, create a corresponding virtual directory on the Web server by completing the following steps: Create the folder on the Web server to contain the virtual directory content. 1. Ensure that you create the folder in a secure manner that does not compromise the security of the Web server. 2. Create the virtual directory under the appropriate Web site on the server.

Copying ASP.NET Application Content (IIS 6.0) When no installation program or provisioning scripts exist for your ASP.NET application, you can copy the content of the ASP.NET application to the corresponding Web site and virtual directories that you created on the Web server.You can copy the ASP.NET application content to the Web server by using one of the following methods: Run the Xcopy command to copy ASP.NET application content to the Web server on an intranet or internal network. Use Microsoft Windows Explorer to copy ASP.NET application content to the Web server on an intranet or internal network. Use the Copy Project command in Visual Studio .NET to copy ASP.NET application content to the Web server on an intranet or internal network, if the application has been developed by using Visual Studio .NET.

Note: FrontPage Server Extensions must be installed on the Web server to use the Copy Project command. Use the Publish Web command in FrontPage to copy ASP.NET application content to the Web server on an intranet or over the Internet, if the Web site that contains the application has been developed using FrontPage.

Enabling Common Storage for ASP.NET Session State (IIS 6.0) ASP.NET session state lets you share client session data across all of the Web servers in a Web farm or across different worker processes or worker process

Page 44: MC0081 set 1 &2  solved assingment 2012

instances on a single Web server. Clients can access different servers in the Web farm across multiple requests and still have full access to session data. You can enable common storage for ASP.NET session state by performing the following steps: 1. Select the method for maintaining and storing ASP.NET session state. 2. If you have decided to maintain session state with the ASP.NET state service, configure out-of-process session state with the ASP.NET state service. 3. If you have decided to maintain session state with SQL Server, configure out-of-process session state with SQL Server. 4. Configure the encryption and validation keys. 5. Configure ASP.NET to use the session state method that you selected in Step 1. 6. Secure the ASP.NET session state connection string in the registry