mc0081- 1&2

Upload: subhajit-saha

Post on 04-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 MC0081- 1&2

    1/39

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

    Answer :

    Defining a Class

    C# is an object-oriented programming language and uses classes and structs to implementtypes 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 aform; forms instantiated at runtime are derived from the class. Using objects derived frompredefined 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 occurswhen types are instantiated or destroyed.Classes can also be defined as generic by using type parameters that enable client code tocustomize the class in a type-safe and efficient manner.A single generic class, for exampleSystem.Collections. Generic.List(T) in the .NET Framework can be used by client code to storeintegers, strings, or any other type of object.A class is the most powerful data type in C#. Like structures, a class defines the data andbehavior of the data type. Programmers can then create objects that are instances of thisclass. Unlike structures, classes support inheritance, which is a fundamental part of object-oriented programming.

    Declaring ClassesClasses 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, anyonecan create objects from this class. The name of the class follows the class keyword. Theremainder 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 ObjectsAlthough they are sometimes used interchangeably, a class and an object are different things. Aclass defines a type of object, but it is not an object itself. An object is a concrete entity basedon 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 theobject will be based on, like this:

    When an instance of a class is created, a reference to the object is passed back to theprogrammer. In the previous example, object1 is a reference to an object that is based on

  • 7/30/2019 MC0081- 1&2

    2/39

    Customer. This reference refers to the new object but does not contain the object data itself. Infact, 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 anobject 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, orby assigning it to an existing object, such as this:

    Example

    public class Person{

    // Fieldpublic string name;

    // Constructor that takes no arguments.public Person(){

    name = "unknown";}

    // Constructor that takes one argument.public Person(string nm){

    name = nm;}

    // Methodpublic 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);

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

  • 7/30/2019 MC0081- 1&2

    3/39

    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 Cycleb. Creating a Web Form

    Write programs with corresponding output screens to demonstrate the aboveconcepts.

    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 cycleof the page and all itscomponents.

    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 HTMLoutput back to the requesting browser.

    The life cycle of a page is marked by the following events, each of which you can handleyourself 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. 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 itsdefault 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.

  • 7/30/2019 MC0081- 1&2

    4/39

    State is restored, and the form controls show client-side data. The load phase can bemodified 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 theproject type, and type in its name, ProgrammingCSharpWeb. Visual Studio .NET will displayhttp://localhost/as the default location, as shown in Figure

  • 7/30/2019 MC0081- 1&2

    5/39

    Visual Studio places nearly all the files it creates for the project in a folder within your localmachine's default web site for example, c:\Inetpub\wwwroot\ProgrammingCSharpWeb.The solution files and other Visual Studio-specific files are stored in \Documents andSettings\\My Documents\Visual Studio Projects(where and are specific to your machine).When the application is created, Visual Studio places a number of files in your project. The WebForm 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 thecode-behind file.Notice that the code-behind file does notappear 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 atthe bottom of the Editor window. Design mode lets you drag controls onto your form; HTMLmode allows you to view and edit the HTML code directly.Let's take a closer look at the .aspxand code-behind files that Visual Studio creates. Start byrenaming WebForm1.aspxto 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. Afteryou rename it, open HelloWeb.aspxand view the code; you will find that the code-behind file hasbeen renamed as well to HelloWeb.aspx.cs.When you create a new Web Form application, VisualStudio .NET will generate a bit of boilerplate code to get you started, as shown in Examplebelow:

    WebForm1

  • 7/30/2019 MC0081- 1&2

    6/39

    content="http://schemas.microsoft.com/intellisense/ie5">

    What you see is typical boilerplate HTML except for the first line, which contains thefollowing ASP.NET code:The language attribute indicates that the language used on the code-behind page is C#. TheCodebehind 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 classthat defines the properties, methods, and events common to all server-side pages. Returning tothe HTML view of HelloWeb.aspx, you see that a form has been specified in the body of the pageusing the standard HTML form tag:Web Forms assumes that you need at least one form to manage the user interaction, andcreates one when you open a project. The attribute runat="server" is the key to the serversidemagic. Any tag that includes this attribute is considered a server-side control to be executed bythe ASP.NET framework on the server.Having created an empty Web Form, the first thing you might want to do is add some text tothe page. By switching to HTML view, you can add script and HTML directly to the file just asyou could with classic ASP. Adding the following line to the body segment of the HTML pagewill cause it to display a greeting and the current local time:Hello World! It is now The marks work just as they did in classic ASP, indicating that code falls betweenthem (in this case, C#). The = sign immediately following the opening tag causes ASP.NET todisplay the value, just like a call to Response.Write( ). You could just as easily write the line as:Hello World! It is nowRun the page by pressing Ctrl-F5 (or save it and navigate to it in your browser). You should seethe string printed to the browser, as in Figure

  • 7/30/2019 MC0081- 1&2

    7/39

    3. Describe the following with respect to State Management in ASP.Net:a. Cookies in ASP.NETb. Session Statec. Application State

    Answer :

    a. Cookies in ASP.NETIntroduction: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 otherinformation. When the user visits your Web site another time, the application can retrieve theinformation it stored earlier.A cookie is a small bit of text that accompanies requests and pages as they go between theWeb server and browser. The cookie contains information the Web application can readwhenever 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, thebrowser 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 browserlooks on the local hard disk for a cookie associated with the URL. If the cookie exists, thebrowser sends the cookie to your site along with the page request. Your application can thendetermine the date and time that the user last visited the site. You might use the information todisplay 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 willexchange cookie information no matter what page the user requests from your site. As the uservisits different sites, each site might send a cookie to the user's browser as well; the browserstores all the cookies separately.Cookies help Web sites store information about visitors. Generally, cookies are one way ofmaintaining continuity in a Web applicationthat is, of performing state management. Except

    for the brief time when they are actually exchanging information, the browser and Web serverare disconnected. Each request a user makes to a Web server is treated independently of anyother request. Many times, however, it's useful for the Web server to recognize users when theyrequest a page. For example, the Web server on a shopping site keeps track of individualshoppers so the site can manage shopping carts and other user-specific information. A cookietherefore acts as a kind of calling card, presenting pertinent identification that helps anapplication know how to proceed.Cookies are used for many purposes, all relating to helping the Web site remember users. Forexample, a site conducting a poll might use a cookie simply as a Boolean value to indicatewhether 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 onso that the user does not have to keep entering credentials.

    Cookie LimitationsMost browsers support cookies of up to 4096 bytes. Because of this small limit, cookies arebest used to store small amounts of data, or better yet, an identifier such as a user ID. The userID can then be used to identify the user and read user information from a database or otherdata store. (See the section "Cookies and Security" below for information about securityimplications of storing user information.)Browsers also impose limitations on how many cookies your site can store on the user'scomputer. Most browsers allow only 20 cookies per site; if you try to store more, the oldestcookies are discarded. Some browsers also put an absolute limit, usually 300, on the number ofcookies they will accept from all sites combined.A cookie limitation that you might encounter is that users can set their browser to refusecookies. If you define a P3P privacy policy and place it in the root of your Web site, more

  • 7/30/2019 MC0081- 1&2

    8/39

    browsers will accept cookies from your site. However, you might have to avoid cookiesaltogether and use a different mechanism to store user-specific information. A common methodfor storing user information is session state, but session state depends on cookies, asexplained later in the section "Cookies and Session State."Although cookies can be very useful in your application, the application should not depend onbeing 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 CookiesThe browser is responsible for managing cookies on a user system. Cookies are sent to thebrowser via the HttpResponse object that exposes a collection called cookies. You can accessthe HttpResponse object as the Response property of your Page class. Any cookies that youwant to send to the browser must be added to this collection. When creating a cookie, youspecify a Name and Value. Each cookie must have a unique name so that it can be identifiedlater when reading it from the browser. Because cookies are stored by name, naming twocookies 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 browserwhen a user visits the site that has written the cookies. The expiration of a cookie should be setfor 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'shard disk. Instead, the cookie is maintained as part of the user's session information. When theuser closes the browser, the cookie is discarded. A non-persistent cookie like this is useful forinformation that needs to be stored for only a short time or that for security reasons shouldnot be written to disk on the client computer. For example, non-persistent cookies are useful ifthe 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 exampleshows 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 othernamed lastVisit. For the first cookie, the values of the Cookies collection are set directly. Youcan add values to the collection this way because Cookies derives from a specialized collectionof type NameObjectCollectionBase.For the second cookie, the code creates an instance of an object of type HttpCookie, sets itsproperties, and then adds it to the Cookies collection via the Add method. When you instantiatean 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, theexpiration 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 convertedto a String.

    Cookies with More Than One ValueYou can store one value in a cookie, such as user name and last visit. You can also storemultiple in a single cookie. The name-value pairs are referred to as .(Subkeys are laid out much like a query string in a URL.) For example, instead of creating twoseparate cookies named userName and lastVisit, you can create a single cookie named userInfothat has the subkeys userName and lastVisit.You might use subkeys for several reasons. First, it is convenient to put related or similarinformation 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

  • 7/30/2019 MC0081- 1&2

    9/39

    assign different expiration dates to different types of information, you should store theinformation in separate cookies.)A cookie with subkeys also helps you limit the size of cookie files. As noted earlier in the "CookieLimitations" section, cookies are usually limited to 4096 bytes and you can't store more than20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookiesthat 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 whichcounts 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 StateASP.NET session state enables you to store and retrieve values for a user as the usernavigates the different ASP.NET pages that make up a Web application. HTTP is a statelessprotocol, meaning that your Web server treats each HTTP request for a page as an independentrequest; by default, the server retains no knowledge of variable values used during previousrequests. As a result, building Web applications that need to maintain some cross-request stateinformation (applications that implement shopping carts, data scrolling, and so on) can be achallenge. ASP.NET session state identifies requests received from the same browser during alimited 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 sessionvariable values as a collection indexed by name. For example, the following code examplecreates the session variables FirstName and LastName to represent the first name and lastname of a user, and sets them to values retrieved from TextBox controls.

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

    ASP.NET stores session information in the memory space of the ASP.NET application bydefault. You can, optionally, store session information using a stand-alone service so thatsession information is preserved if the ASP.NET application is restarted, in a SQL Server sothat session information is available to multiple Web servers in a Web farm (and also persists ifthe ASP.NET application is restarted), or in a custom data store.ASP.NET also provides several other options for persisting data within an application besidessession state.ASP.NET session state enables you to store and retrieve values for a user as the usernavigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that aWeb server treats each HTTP request for a page as an independent request. The server retainsno knowledge of variable values that were used during previous requests. ASP.NET sessionstate identifies requests from the same browser during a limited time window as a session, andprovides 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 VariablesSession variables are stored in a SessionStateItemCollection object that is exposed through theHttpContext:Session property. In an ASP.NET page, the current session variables are exposedthrough 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 todeclare a session variable or explicitly add it to the collection. The following example shows howto create session variables in an ASP.NET page for the first and last name of a user, and setthem to values retrieved from TextBox controls.Session variables can be any valid .NET Framework type.

  • 7/30/2019 MC0081- 1&2

    10/39

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

    Session IdentifiersSessions 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 theapplication is examined for a SessionID value sent from the browser. If no SessionID value issupplied, ASP.NET starts a new session and the SessionID value for that session is sent to thebrowser with the response.By default, SessionID values are stored in a cookie. However, you can also configure theapplication 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 sameSessionID value. If the time between requests for a particular session exceeds the specifiedtime-out value in minutes, the session is considered expired. Requests made with an expiredSessionID value result in a new session.

    Cookieless SessionIDsBy 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 settingthe 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 usecookieless session identifiers.ASP.NET maintains cookieless session state by automatically inserting a unique session ID intothe 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 withabsolute paths are not modified.) Session state is maintained as long as the user clicks linksthat have been modified in this manner. However, if the client rewrites a URL that is supplied bythe application, ASP.NET may not be able to resolve the session ID and associate the requestwith 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 andbefore any remaining file or virtual directory identifier.This enables ASP.NET to resolve the application name before involving the SessionStateModulein the request.

    Note: To improve the security of your application, you should allow users to log out of yourapplication, at which point the application should call the Abandon method. This reduces thepotential for a malicious user to get the unique identifier in the URL and use it to retrieve privateuser data stored in the session.

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

    Session EventsASP.NET provides two events that help you manage user sessions. The Session_OnStart eventis raised when a new session starts, and the Session_OnEnd event is raised when a session is

  • 7/30/2019 MC0081- 1&2

    11/39

    abandoned or expires. Session events are specified in the Global.asax file for an ASP.NETapplication.The Session_OnEnd event is not supported if the session Mode property is set to a value otherthan InProc, which is the default mode.Note: If the Global.asax file or Web.config file for an ASP.NET application is modified, theapplication will be restarted and any values stored in application state or session state will be

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

    Configuring Session StateSession state is configured by using the sessionState element of the system.web configurationsection. You can also configure session state by using the EnableSessionState value in the @Page directive.The 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 Timeoutvalue. Supporting values that are based on the session Mode setting.

    The following example shows a sessionState element that configures an application forSQLServer session mode. It sets the Timeout value to 30 minutes, and specifies that sessionidentifiers are stored in the URL.

    You can disable session state for an application by setting the session-state mode to Off. If youwant to disable session state for only a particular page of an application, you can set theEnableSessionState value in the @ Page directive to false. The EnableSessionState value canalso be set to ReadOnly to provide read-only access to session variables.

    Concurrent Requests and Session StateAccess to ASP.NET session state is exclusive per session, which means that if two differentusers 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 sameSessionID value), the first request gets exclusive access to the session information. The secondrequest executes only after the first request is finished. (The second session can also getaccess if the exclusive lock on the information is freed because the first request exceeds thelock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, arequest for the read-only session information does not result in an exclusive lock on thesession 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 SessionStatenamespace:

    Member DescriptionSessionIDManager Manages unique identifiers for

    ASP.NET session state.SessionStateItemCollection Used to store session state

    variables.

  • 7/30/2019 MC0081- 1&2

    12/39

    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 retrievinginformation 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 usefulplace 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 howto use it.Using Application StateApplication state is stored in an instance of the HttpApplicationState class. This class exposesa key-value dictionary of objects.The HttpApplicationState instance is created the first time a user accesses any URL resource inan application. The HttpApplicationState class is most often accessed through the Applicationproperty of the HttpContext class.You can use application state in two ways. You can add, access, or remove values from theContents collection directly through code. The HttpApplicationState class can be accessed atany time during the life of an application. However, it is often useful to load application statedata when the application starts. To do so, you can put code to load application state into theApplication_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 declaration in your Web application's Global.asax file. Application state defined in this way canthen be accessed from code anywhere in your application. The following example shows anobject declaration for an application state value:You can add objects to the StaticObjects collection only in the Global.asax file. The collectionthrows 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 theApplication collection. The following code example shows how to reference a member of anobject defined in the StaticObjects collection of application state:C# Codeprotected void Page_Load(Object sender, EventArgs e)Label1.Text = MyInfo.Title;End Sub

    Application State ConsiderationsWhen 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 savingdata to disk or a database. However, storing large blocks of data in application state can fill upserver memory, causing the server to page memory to disk. As an alternative to usingapplication state, you can use the ASP.NET cache mechanism for storing large amounts ofapplication 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 becomesscarce. For more information see ASP.NET Caching Overview.2. Volatility: As the application state is stored in server memory, it is lost whenever theapplication is stopped or restarted. For example, if the Web.config file is changed, theapplication is restarted and all application state is lost unless application state values havebeen written to a non-volatile storage medium such as a database.3. Scalability: Application state is not shared among multiple servers serving the sameapplication, as in a Web farm, or among multiple worker processes serving the same applicationon the same server, as in a Web garden. Your application therefore cannot rely on applicationstatecontaining the same data for application state across different servers or processes. If yourapplication 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.

  • 7/30/2019 MC0081- 1&2

    13/39

    4. Concurrency: Application state is free-threaded, which means that application state datacan be accessed simultaneously by many threads. Therefore, it is important to ensure thatwhen you update application state data, you do so in a thread-safe manner by including built-insynchronization support. You can use the Lock and UnLock methods to ensure data integrity bylocking the data for writing by only one source at a time. You can also reduce the likelihood ofconcurrency 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 Serviceb. 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 theWeb service is as simple as copying it to a directory on your Web server that is URL-addressable. If you put Calc.asmx in , the Web services local URL is

    .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 registeredto 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 aClass attribute identifying the class that makes up the Web service. Web service classes can be attributed with optional WebService attributes. The one in thisexample assigns the Web service a name and a description that show up in the HTML pagegenerated 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 namespacethat scopes the Web services members. Web methods are declared by tagging public methods in the Web service class withWebMethod attributes. You can build helper methods into a Web service methods that areused internally by Web methods but that are not exposed as Web methods themselves byomitting the attribute. The WebMethod attributes in Figure 8.5 also assign descriptive text totheir Web methods. Youll learn more about Description and other WebMethod parameters inthe section entitledThe WebMethod Attribute.

    HTTP, XML, and SOAP are hidden under the hood. You dont have to deal with raw XML dataor SOAP messages because the .NET Framework deals with them for you.

    http://localhost/calc.asmxhttp://localhost/calc.asmx
  • 7/30/2019 MC0081- 1&2

    14/39

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

    Testing a Web ServiceHow 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.asmxin your browsers address bar. Youll 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 HTMLpage that describes the Web service.The name and description in the ASMX files WebService attribute appear at the top of the page.Underneath is a list of Web methods that the service exposes, complete with the descriptionsspelled out in the WebMethod attributes.

  • 7/30/2019 MC0081- 1&2

    15/39

    ClickAdd 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 readsthem from the metadata in the DLL it compiled from Calc.asmx. It even generates an HTML formthat you can use to call the Add method with your choice of inputs. Type 2 and 2 into the a

    andb boxes and click Invoke. The XML returned by the Web method appears in a separate

    browser window

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

    http://terraservice.net/terraservice.asmx

    Thats the URL of the Microsoft TerraService, an ultra-cool Web service that provides aprogrammatic interface to a massive database of geographic data known as the MicrosoftTerraServer.

    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, theproper command is

    http://terraservice.net/terraservice.asmxhttp://terraservice.net/terraservice.asmxhttp://terraservice.net/terraservice.asmx
  • 7/30/2019 MC0081- 1&2

    16/39

    wsdl http://localhost/calc.asmxWsdl.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 services Add method. Theresulting output proves beyond the shadow of a doubt that Calc.asmx is smart enough to add 2and 2CalcClient.csusing System;class MyApp{public static void Main (){CalculatorWebService calc = new CalculatorWebService ();int sum = calc.Add (2, 2);

    Console.WriteLine ("2 + 2 = " + sum);}}

    Avoiding Hard-Coded Service URLsLook through a CS file generated by Wsdl.exe, and youll see the Web service proxy class as wellas the methods that wrap the Web services Web methods. Youll also see that the Webservices URL is hardcoded into the CS file in the proxys class constructor. Heres an example:

    public CalculatorWebService() {

    this.Url = "http://www.wintellect.com/calc.asmx";}If the Web service moves, youll have to modify the CS file and regenerate the proxy.To avoid having to update code when a Web services URL changes, you can use Wsdl.exes/appsettingurlkey (abbreviated /urlkey) switch. The commandwsdl /urlkey:CalcUrl http://www.wintellect.com/calc.asmx produces the following classconstructor:public CalculatorWebService() {string urlSetting =System.Configuration.ConfigurationSettings.AppSettings["CalcUrl"];if ((urlSetting != null)) {this.Url = urlSetting;}

  • 7/30/2019 MC0081- 1&2

    17/39

    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:If the URL changes, we can update the proxy simply by editing Web.config. No code changes arerequired.

  • 7/30/2019 MC0081- 1&2

    18/39

    1. Write a program in C# language to perform the following operations:a. Basic arithmetic operationsb. 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{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;

  • 7/30/2019 MC0081- 1&2

    19/39

    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;

    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++)

  • 7/30/2019 MC0081- 1&2

    20/39

    {Console.WriteLine("Enter elements:{0}", i+1);array[i] = Convert.ToInt32(Console.ReadLine());

    }largest = array[0];for (i = 0; i largest){

    largest = array[i];}

    }Console.WriteLine("The Largest number is :{0}", largest);Console.ReadLine();

    }

    }

    }

    2. Explain the following with respect to ASP.Net:a. Master Pagesb. 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, ornavigation bar, in a common location called a "master page", to be shared by manypages in your site. This improves the maintainability of your site and avoidsunnecessary duplication of code for shared site structure or behavior.Just as Themes and Skins allow you to factor out style definitions from your page codeand maintain them in a common file, Master Pages do the same for page layout. AMaster Pages is a page that contains markup and controls that should be sharedacross multiple pages in your site. For example, if all of your pages should have thesame header and footer banners or the same navigation menu, you could define this in aMaster Page once, and then all pages associated to this Master Page would inheritthose common elements. The advantage of defining the header, footer, and navigation ina Master Page is that these elements need only be defined once, instead of multipletimes 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 ofASP.NET pages in your application. In working with Master Pages, the developer creates aMaster File that is the template referenced by a subpageor Content Page.Master Pages use a .master file extension, whereas content pages use the .aspx file extensionyou are used to; but content pages are declared as such within the files pagedirective.

    Master and Content PagesDefining 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 aspecial type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines aregion of the master page rendering that can be substituted with content from a page

  • 7/30/2019 MC0081- 1&2

    21/39

    associated to the master. A ContentPlaceHolder can also contain default content, just in casethe derive page does not need to override this content. The syntax of a ContentPlaceHoldercontrol is given below:

    Welcome to my florist website!To differentiate a Master Page from a normal page, a Master Page is saved under thefile extension. A page can derive from a Master Page by defining a MasterPageFile attribute onits Page directive, as demonstrated below. A page that is associated to a Master Page is calleda Content Page.A Content Page can declare Content controls that specifically override content placeholdersections in the Master Page. A Content control is associated to a particular ContentPlaceHoldercontrol through its ContentPlaceHolderID property. A Content Page may only contain markupand controls inside Content controls; it cannot have any top-level content of its own. It can,

    however, have directives or server-side code.

    With sunshine, water, and careful tending, roses will bloom several times in aseason.The following example demonstrates the relationship between Master and Content pages. TheMaster Page in this case defines two ContentPlaceHolder regions, named FlowerPicture andFlowerText, 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 thedefault content for the named ContentPlaceHolder regions with their own content. Note that theDefault.aspx page in this site does not define any Content controls, and so it just inherits thedefault content from the Master Page.

    The source code for the above web page using C# is given below:

  • 7/30/2019 MC0081- 1&2

    22/39

    Daffodil
    Rose
    Dahlia
    Hydrangea
    Daisy

    Welcome to my florist website!

    We have an enormous selection of quality flowers and seeds, available for shippingto any location worldwide. Let us handle all you gardening needs!



    URL Rebasing in a Master PageOne thing to notice about the preceding example is that there are several places in the MasterPage that refer to URL resources like images or stylesheet or page references using a relative-path syntax, for example:

    Daffodil...

    This works fine when the Master Page and Content Page are in the same directory, but whenthe Content Page is in a physically separate location, the relative path will not be correct. Tosolve this problem, you may take one of the following approaches: Use absolute URL paths in the Master Page, for example

    Use relative or application-relative URLs in server controls instead of static markup, forexample The following example demonstrates this technique. The Content Pages have been moved to asubdirectory "Pages" under the directory that contains the Master Page. The Master Page hasbeen updated to use server controls in place of HTML:

  • 7/30/2019 MC0081- 1&2

    23/39

    ...Daffodil...

    Accessing a Master Page from CodeIn addition to overriding content, it is possible for a Content Page to programmatically accessits Master Page. A Content Page creates a strongly-typed reference to the Master Page usingthe directive, specifying the virtual path to the master page:

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

    C# CodeMaster.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, whileMyAdRotator is a control on the Master Page.

    Nesting Master PagesContent Pages can also be Master Pages. That is, it is possible to derive a Master page fromanother Master Page. For example, you might have a top-level Master Page that represents theoverall 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 withinyour site. Content Pages would then derive from the appropriate section master for the sectionthe Content Page belongs to. The following example demonstrates this idea, dividing the Floristexample site into two sections, Annuals and Perennials.

    The following is the code for the Home Page of the Nested Pages:

  • 7/30/2019 MC0081- 1&2

    24/39

    b. Themes & Skins

    Creating ThemesThemes and Skins: The Themes and Skins feature of ASP.NET allows you to factor style andlayout information into a separate group of files, collectively called a Theme. A Theme can thenbe 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, withouthaving to edit the individual pages in your site. Themes can also be shared with otherdevelopers.When you build a web application, it usually has a similar look-and-feel across all its pages. Nottoo 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 thepages within the application.You can apply these common styles individually to each and every server control or objects oneach 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 forone or more control types. You can define skins in a separate file for each control or define allthe skins for a theme in a single file.There are two types of control skins, and :A automatically applies to all controls of the same type when a theme is applied toa page. A is a default skin if it does not have a SkinID attribute. For example, if youcreate a default skin for a Calendar control, the control skin applies to all Calendar controls onpages that use the theme. (Default skins are matched exactly by control type, so that a Buttoncontrol skin applies to all Button controls, but not to LinkButton controls or to controls thatderive from the Button object.)A is a control skin with a SkinID property set. Named skins do not automaticallyapply to controls by type. Instead, you explicitly apply a named skin to a control by setting thecontrol's SkinID property. Creating named skins allows you to set different skins for differentinstances of the same control in an application.

    Cascading Style SheetsA theme can also include a cascading style sheet (.css file). When you put a .css file in the themefolder, the style sheet is applied automatically as part of the theme. You define a style sheetusing 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

    STLNET St. Louis .NET User Group



  • 7/30/2019 MC0081- 1&2

    25/39

  • 7/30/2019 MC0081- 1&2

    26/39

    If the themes are disabled by setting the EnableTheming attribute is set to False at the pagelevel, we can still enable theming for specific controls on that page by setting EnableTheming forthose specific controls to true and applying a specific theme at the same time as shown in theexample given below:

    Usage of Themes with Master PagesThe ASP.NET applications that use Master pages have both the Pageand Masterpagedirectives that contain an EnableTheming attribute.If this is the case, what is the behavior of any content pages using the master page? If thecontent page that is using this master page does not make any specification on theming (itdoes not use the EnableTheming attribute), what is specified in the master page naturally takesprecedence and no theme is utilized as required by the falsesetting. Even if you have set theEnableTheming attributes value in the content page, any value specified in the master pagetakes precedence.That is, if the theming is set to false in the master page and set to truein the content page, thepage 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 controllevel rather than doing it in the Page directive of the content page.

    Creation of User-Defined ThemesUsers can define their own themes to the pages they would create within an application. Thesethemes 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.Right click the project and add a new folderName the folder appropriately (for example: App_Themes)You can also create this folder by right clicking on your project in Visual Studio and

    selecting Add ASP.NET Folder Theme.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 brushas shown below:Within the existing (or newly created) themes folder, we can create an additional theme folderfor each and every theme that you can use in your application.For If you are going to have four themes Summer, Fall, Winter, and Spring thenyou 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 ThemesIn addition to the server control definitions that can be created from within a .skin file, we canmake further definitions using Cascading Style Sheets (CSS).With a .skin file, we could define only the styles associated with server controls and nothingelse.For a theme that goes beyond the server controls, we must further define the theme style sothat 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.

  • 7/30/2019 MC0081- 1&2

    27/39

    Right click the Summertheme folder and select Add New Item. In the list of options,select the option Style Sheet and name it Summer.css. The Summer.cssfile should be sittingright next to your Summer.skinfile. This creates an empty .css file for your theme.To create comprehensive theme with this dialog, you define each HTML element that mightappear in the ASP.NET page or you make use of class names or element IDs.

    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;

    a: link

    color: Blue;text-decoration: none;

    a: visited

    color: Blue;text-decoration: none;

    color: Red;text-decoration: underline overline;

    In this CSS file four things are defined: You define the text that is found within the tag of the page basically all the text. Ingeneral, plenty of text can appear in a typical ASP.NET page that is not placed inside an

    or tag. Therefore you can define how your text should appear in theCSS file; otherwise your web page may appear quite odd at times. In this case, a definition is inplace for the size, the font family, and the color of the text.

    The next three definitions in the CSS file revolve around the (anchor tag element used forhyperlinks). The definition defines the look of a hyperlink on a web page. The definition defines the look of the link of a web page already visited by the userpreviously.

    The definition defines the appearance of the hyperlink when the end user hovers on ahyper-link.

    Skin Creation:A skin is a definition of styles applied to the server controls in your ASP.NET page. Skins canwork in conjunction with CSS files or images. To create a theme to use in your ASP.NETapplication, you use a single skin file in the theme folder. The skin file can have any name, but itmust have a .skin file extension.

    Creation of the Summer themeRight click the Summer folder, select Add New Item, and select Skin. Name the fileSummer.skin.The listing for the Summer.skin file is shown below:

    The Summer.skin file

  • 7/30/2019 MC0081- 1&2

    28/39

    To use the above listing in a real application, you should actually make a definition for each andevery server control option.If you specify the runat = serverattribute in the skinned version of the control, you alsoinclude it in the server control you put on an .aspxpage that uses this theme.Using the Summer theme in an ASP.NET pageUsing C# Language

    protected void Button1_Click(object sender, System.EventArgs e){Label1.Text = Hello + TextBox1.Text.ToString;}

  • 7/30/2019 MC0081- 1&2

    29/39

    The App_Themes FolderThemes reside in the App_Themes folder directly under the application root directory. A Themeconsists of a named subdirectory under this folder that contains a collection of one or more

    files, named with the .skin extension. A Theme can also contain a CSS file and/orsubdirectories for static files like images. The figure below shows an App_Themes directorywith 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 asthey might appear in a page. A skin file can contain multiple control definitions, for example onedefinition 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 theTheme applied. For example, a controldefinition in a skin file will cause all Calendar controls in pages with the Theme applied to usethe 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 property value for a control definition in a skin file.

    Global and Application ThemesA Theme can reside at the application-level or machine-level (globally available to allapplications). Application-level Themes are placed in the App_Themes directory under theapplication root directory, as described above. Global Themes are placed in a "Themes" directoryunder an ASP.NETClientFiles folder under the ASP.NET installation directory, for example%WINDIR%\Microsoft.NET\Framework\\ASP.NETClientFiles\Themes. The location

  • 7/30/2019 MC0081- 1&2

    30/39

    of global themes is Inetpub\ wwwroot\aspnet_ client\system_web\\Themes for IISweb sites.

    Assigning a Theme to a PageAn individual page can be assigned a Theme by setting the directive tothe 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 skinfiles in the theme that apply style settings to controls in the page.

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

    Answer :We have to write the following code in the 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);}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);

  • 7/30/2019 MC0081- 1&2

    31/39

    }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 = '%';}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.

  • 7/30/2019 MC0081- 1&2

    32/39

    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 applicationsinto application pools. Application pools allow specific configuration settings to be applied togroups of applications, and the worker processes servicing those applications. Any Webdirectory or virtual directory can be assigned to an application pool.By creating new application pools and assigning Web sites and applications to them, you canmake your server more efficient and reliable, and your other applications always available, evenwhen 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 Webapplications or Web sites in pools, which are called . An application pool is a

    group of URLs that are routed to one or more worker processes that share the sameconfiguration. The URLs that you assign to an application pool can be for an application, a Website, a Web directory, or a virtual directory.In an application pool, process boundaries separate each worker process from other workerprocesses so that when an application is routed to one application pool, applications in otherapplication pools do not affect that application.By using an application pool, you can assign specific configuration settings to a workerprocess (or, in the case of a Web garden, to a set of worker processes) that services a group ofapplications. For example, you can configure worker process recycling, which offers severalconfiguration options to match the needs of each application. If, for example, you suspect thatan application has a memory leak, you might configure the application pools worker process torecycle when its memory use reaches a certain threshold. If another application fails because of

  • 7/30/2019 MC0081- 1&2

    33/39

    the volume of requests that it receives, you can set the application pools worker process torecycle when the application exceeds a specified number of requests.By creating new application pools and assigning Web sites and applications to them, you canmake your server more efficient, reliable, and secure, and ensure that your applications remainavailable even when a worker process serving an application pool is recycled because of afaulty application.

    Configuring Application Pools in IIS 6.0 (IIS 6.0)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 ormore worker processes. Because applications in an application pool are separated from otherapplications by worker process boundaries, an application in one application pool is notaffected by problems caused by applications in other application pools.By creating new application pools and assigning Web sites and applications to them, you canmake your server more efficient and reliable, as well as making your other applications alwaysavailable, even when the worker process serving the new application pool has problems.

    Guidelines for Creating Application Pools To isolate Web applications on a Website 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 applicationpool. Use an account with the least user rights possible, such as Network Service in theIIS_WPG group. If there is a test version of an application on the same server with the production version ofthe application, separate the two versions intodifferent 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 uniqueset of properties, create a unique application pool for that application.

    You must be a member of the Administrators group on the local computer to perform thefollowing procedure or procedures. As a security best practice, log on to your computer byusing an account that is not in the Administrators group, and then use the command torun IIS Manager as an administrator.At a command prompt, type Administrative_AccountName"mmc %systemroot%\system32\inetsrv\iis.msc".

    Steps to create a new Application Pool:1. In IIS Manager, expand the local computer, right-click Application Pools, point to New, andthen 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 existingapplication pool as template, in Application pool name box, right-click the application pool thatyou want to use as a template.5. Click OK.

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

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

  • 7/30/2019 MC0081- 1&2

    34/39

    About Configuring Servers for Applications (IIS 6.0)Internet Information Services (IIS) 6.0 delivers Web hosting services through an adjustablearchitecture 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, IISmanages them by shutting down and redeploying faulty resources and connecting faultyprocesses 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 ofthe 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. Useworker process isolation mode unless you have a specific compatibility issue that makes theuse of IIS 5.0 isolation mode necessary. Web sites that serve static content or simple ASPapplications should be able to move to IIS 6.0 running in worker process isolation mode withlittle 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 isolationmode.Worker process isolation mode provides better default security for running Web applicationsthan 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.0isolation mode. Web applications that run in-process in IIS 5.0 application mode run asLocalSystem. The LocalSystem account can read, execute, and change most of the resources onthe computer.The default isolation mode upon installing IIS 6.0 depends on whether you perform a cleaninstallation or an upgrade. 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 isolationmode is the same asconfigured 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 tomaintain compatibility with your existing applications.

    Worker Process Isolation ModeIIS 6.0 introduces worker process isolation mode, which runs all Web applications in an isolatedenvironment. When you run IIS in worker process isolation mode, applications can be configuredto run in separate application pools. Each application pool is a logical representation of aconfigurable worker process and links to the applications in the pool. Worker processes operateindependently of each other; they can fail without affecting other worker processes. The poolingof applications protects applications from the effects of worker processes that support otherapplication pools. In this way, applications are protected from each other.

    In worker process isolation mode, Hypertext Transfer Protocol (HTTP) requests are routeddirectly to an in-kernel application pool queue serving the configured application. Workerprocesses that serve an application pool pull the requests directly from the queue, avoidingprocess-switching overhead.To further protect your WWW service, IIS 6.0 isolates critical World Wide Web PublishingService (WWW service) components, such as the HTTP protocol stack (HTTP.sys) and WWWService Administration and Monitoring, from the effects of third-party code running in workerprocesses. HTTP.sys receives and queues requests for WWW services. When a worker processenters an unhealthy state, and thus stops processing requests, HTTP.sys continues to processrequests. Meanwhile, the WWW service detects that the worker process is unhealthy and shutsit down. If there is demand for a new worker process to serve requests (HTTP.sys has requestsqueued), the WWW service starts a new worker process to pick up the queued requests from

  • 7/30/2019 MC0081- 1&2

    35/39

    HTTP.sys. Even though a worker process has failed, the WWW service continues to processrequests and shields the user from experiencing a loss of service.IIS 6.0 worker process isolation mode delivers the following specific improvements over earlierversions of IIS: Robust Performance Isolation prevents Web applications and Web sites from affecting eachother 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 andperiodic restart of deteriorating worker processes. Scalability Web gardens allow more than one worker process to serve the same applicationpool. 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 failingworker processes to debugging tools. CPU Limiting This monitoring feature enables controlling the amount of CPU resources that anapplication 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 theMicrosoft .NET Framework version 1.1 with the operating system installation. This chapterdescribes how to deploy ASP.NET applications on a newly installed server running InternetInformation Services (IIS) 6.0. Version 1.1 of the .NET Framework is installed with WindowsServer 2003. Most ASP.NET applications run without modification on version 1.1 of the .NETFramework.

    Overview of Deployment process using IIS 6.0ASP.NET is a unified Web application platform that provides services to help you build anddeploy 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 Frameworkversion 1.1 as a part of Windows Server 2003. However, to run ASP.NET applications, you mustalso install IIS 6.0.ASP.NET is not available on the following operating systems: Microsoft Windows XP 64-BitEdition; the 64-bit version of Windows Server 2003, Enterprise Edition; and the 64-bitversion of Windows Server 2003, Datacenter Edition.The deployment process presented in this section describes how to deploy ASP.NETapplications on a newly installed IIS 6.0 Web server. Before you begin this process, completethe following steps: Install Windows Server 2003, which includes version 1.1 of the .NET Framework, with thedefault options.

    Install IIS 6.0 with the default settings inAdd or Remove Programs in Control Panel.

    When you configure IIS 6.0 to run in IIS 5.0 isolation mode, the settings in the section of the Machine.config file are configured in the same way as they were in IIS 5.0 in theMachine.config or Web.config files.Upon completing the process described in this section, you will have a Web server running IIS6.0 and hosting your ASP.NET applications. However, you can further configure the Web serverto improve the security and availability of your ASP.NET applications.Deployment Process using IIS 6.0The process for deploying new ASP.NET applications on a newly installed Web server requiresno understanding of earlier versions of IIS or the .NET Framework. All the ASP.NETconfiguration sections in the Machine.config and Web.config files are configured the same wayin IIS 6.0, except for the section of the Machine.config file. When IIS 6.0 is

  • 7/30/2019 MC0081- 1&2

    36/39

    configured to run in worker process isolation mode, some of the attributes in the section of the Machine.config file are now in equivalent IIS 6.0 metabaseproperties.In addition, if your ASP.NET applications need to retain session state, you must configure IIS6.0 to use the appropriate ASP.NET application session state method. Depending on themethod 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

    Deploy the Web Server1. Install Windows Server 2003.2. Install and configure IIS 6.0.3. Enable ASP.NET in the Web service extensions list.

    Install ASP.NET Applications1. 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 additionto 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.

  • 7/30/2019 MC0081- 1&2

    37/39

    Installing Windows Server 2003 (IIS 6.0)The deployment process presented here assumes that you install Windows Server 2003 withthe default options. If you use other methods for installing and configuring Windows Server2003, such as unattended setup, your configuration settings might be different.Note: When you complete the installation of Windows Server 2003, Manage Your Serverautomatically starts. The deployment process assumes that you quit Manage Your Server, andthen 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, thenext step in deploying the Web server is to install and configure IIS 6.0. The deployment processpresented here assumes that you install IIS 6.0 with the default options in Add or RemovePrograms in Control Panel. If you use other methods for installing and configuring WindowsServer 2003, such as Manage Your Server, the default configuration settings might bedifferent.

    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 configuringIIS 6.0 is to ensure that the security of the Web server is maintained. Enabling unnecessarycomponents 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, installFrontPage 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 orRemove Windows Components, which is accessible from Add or Remove Programs in ControlPanel. When you enable ASP.NET by using this method, ASP.NET is also enabled in the Webservice extensions list. If you enabled ASP.NET in this way, then you can continue to the nextstep 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 istrue: You installed a version of the .NET Framework and ASP.NET other than version 1.1 from aWeb download or as part of an application such as the Microsoft Visual Studio .NETdevelopment tool. You disabled ASP.NET in the Web service extensions list because you were not runningASP.NET applications on an existing Web server.

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

  • 7/30/2019 MC0081- 1&2

    38/39

    Installing ASP.NET Applications (IIS 6.0)After the Web server is deployed, you can install your ASP.NET applications. First, you mustcreate a Web site and virtual directories for each ASP.NET application. Then you need to installeach 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 scriptsto 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, youdo not need to perform any manual steps to install the ASP.NET applications. In this case, runthe provisioning or setup scripts to install and configure the Web sites and applications, andthen continue to the next step in the application deployment process. Figure 9.4 belowillustrates 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 theircorresponding Web sites and virtual directories.Create the Web sites and virtual directories for your ASP.NET applications by completing thefollowing steps: Create Web sites and home directories. Create virtual directories.

    Creating Web Sites and Home Directories Using IIS 6.0Each Web site must have one home directory. The home directory is the central location foryour published Web pages. It contains a home page or index file that serves as a portal to otherpages in your Web site. The home directory is mapped to the domain name of the Web site or tothe name of the Web server.Create a Web site and home directory for an ASP.NET application by completing the followingsteps:

    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 andsubdirectories for the Web site. The folder can be created on the same computer as the Webserver or on a Universal Naming Convention (UNC)shared folder on a separate server. At aminimum, create the folder on the following: An NTFS file system partition, which helps ensure proper security. Adisk 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 requestedURL. As a security measure, ASP.NET returns a 404 error for all requests containing /bin inthe requested URL.

    Create the Web site on the server.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 directoryis a folder name, used in an address, which corresponds to a physicaldirectory on the Web server or a Universal Naming Convention (UNC) location. This is alsosometimes referred to as URL mapping. Virtual directories are used to publish Web contentfrom any folder that is not contained in the home directory of the Web site. When clients access

  • 7/30/2019 MC0081- 1&2

    39/39

    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 volumeduring the application deployment process. You can move the content to another disk volume onthe Web server or to a shared folder on a separate server. You can use virtual directories tospecify 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 virtualdirectory 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 ofthe 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, youcan copy the content of the ASP.NET application to the corresponding Web site and virtualdirectories 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 theXcopy command to copy ASP.NET application content to the Web server on anintranet or internal network. Use Microsoft Windows Explorer to copy ASP.NET application content to the Web server onan intranet or internal network. Use theCopy Project command in Visual Studio .NET to copy ASP.NET application content tothe Web server on an intranet or internal network, if the application has been developed byusing Visual Studio .NET.

    Note: FrontPage Server Extensions must be installed on the Web server to use the Copy Projectcommand. Use thePublish Web command in FrontPage to copy ASP.NET application content to the Webserver on an intranet or over the Internet, if the Web site that contains the application has beendeveloped 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 aWeb farm or across different worker processes or worker process instances on a single Webserver. Clients can access different servers in the Web farm across multiple requests and stillhave 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 e