summer - MC0081.doc

Embed Size (px)

Citation preview

  • 7/27/2019 summer - MC0081.doc

    1/8

    MC0081 - DOT NET TECHNOLOGIES

    1. Describe the following with respect to creating Web Forms in .Net environment:

    a. Web Form Life Cycle b. Creating a Web Form

    Write programs with corresponding output screens to demonstrate the above concepts.

    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 lifecycle to the other, the goal is to render appropriate HTML output back to the requesting

    browser.

    Initialize: Initialize is the first phase where incoming request are initialized.

    Load View State: LoadViewState ( ) method is used 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 isposted.

    Process Postback Data: During this phase, the data sent to the server in the posting isprocessed. If any of this data results in a requirement to update the View State, that

    update is performed via the LoadPostData ( ) method.

    Load: CreateChildControls ( ) is called, if necessary, to create and initialize servercontrols in the control tree. State is restored, and the form controls show client-side data.

    You can modify the load phase by handling the Load event with the OnLoad method.

    Send Postback Change Modifications: If there are any state changes between thecurrent 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 to modify the output prior to rendering using the

    OnPreRender ( ) method.

    Save State: You can override this using the SaveViewState () method.

    Render: You can override it using the Render method. CreateChildControls ( ) is called,if necessary, to create and initialize server controls in the control tree.

    Dispose: It gives you an opportunity to do any final cleanup and release references to any

    expensive resources.

    b) CREATING A WEB FORM

    To create the simple Web Form that will be used in the above example, go to the option

    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,

    ProgrammingCSharpWeb. Visual Studio .NET will display http://localhost/ as the defaultlocation.

    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.

  • 7/27/2019 summer - MC0081.doc

    2/8

    The solution files and other Visual Studio-specific files are stored in \Documents

    and Settings\\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 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# associatedwith your form; this is the code-behind file.

    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

    forms 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 HTMLmode 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.

    Run the page by pressing Ctrl-F5 (or save it and navigate to it in your browser).

    2. Describe the following with respect to State Management in ASP.Net:

    a. Cookies in ASP.NET b. Session State c. Application State

    a)COOKIES IN ASP.NET : A cookie is a small bit of text that accompanies requestsand 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.

    Cookies help Web sites store information about visitors. Generally, cookies are one way

    of maintaining continuity in a Web applicationthat is, of performing state management.

    Except for the brief time when they are actually exchanging information, the browser andWeb 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 torecognize users when they request a 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, presentingpertinent identification that helps an application know how to proceed.

    Cookies are used for many purposes, all relating to helping the Web site remember users.

    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 HTTPrequest 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 applicationsthat 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 browser during a limited period of time as a

    session, and provides the ability to persist variable values for the duration of that session.

  • 7/27/2019 summer - MC0081.doc

    3/8

    c)APPLICATION STATE : Application state is a data repository available to all classes

    in an ASP.NET application. Application state is stored in memory on the server and isfaster 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.

    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.

    Application can be used in two ways:

    We 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. Alternatively, we can add objects to the StaticObjects collection via an

    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.

    3. Describe the following with respect to Web Services in .Net:

    a. Writing and Testing a Web Service b. Implementing a Web Service Client

    a) Writing and Testing a Web Service :

    Creating your first web service is incredibly easy. In fact, by using the wizards in Visual

    Studio. NET you can have your first service up and running in minutes with no coding.

    A new namespace will be defined called MyService, and within this namespace will be aset of classes that define your Web Service. By default the following classes will be

    created:

    Global (in global.asax) Derived from HttpApplication. This file is theASP.NET equivalent of a standard ASP

    global.asa file.

    WebService1 (in WebService1.cs) Derived from System.Web.Services.WebService.This is your WebService class that allows you to

    expose methods that can be called as

    WebServices.

    [WebService(Namespace="http://codeproject.com/webservices/",

    Description="This is a demonstration WebService.")]

    public class WebService1 : System.Web.Services.WebService{

    public WebService1()

    {

  • 7/27/2019 summer - MC0081.doc

    4/8

    //CODEGEN: This call is required by the ASP+ Web Services Designer

    InitializeComponent();

    }[WebMethod]

    public string HelloWorld()

    { return "Hello World";

    }

    }}

    Testing a Web Service:

    For testing an ASMX Web service, call it in the browser. Copy Calc.asmx to wwwroot and type

    http://localhost/calc.asmxin the browsers address bar. User will be greeted as shown in the figure.

    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 files WebService attribute appear at the top of the

    page. Underneath is a list of Web methods that the service exposes, complete with the descriptions spelledout in the WebMethod attributes.

    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 intoyour 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 Microsoft

    TerraServer.

    B. IMPLEMENTING A WEB SERVICE CLIENTS:

    Web service clients that is, applications that use, or consume, Web methods. Its

    easy to write Web services. Writing Web service clients is even easier, thanks to somehigh-level support lent by the .NET Framework class library (FCL) and a code-

    generator named Wsdl.exe. If you have a WSDL contract describing a Web service

    (or the URL of a DISCO file that points to a WSDL contract).

    The methods in the proxy class mirror the Web methods in the Web service. If theWeb service exposes Web methods named Add and Subtract, the Web service proxy

    also contains methods named Add and Subtract. When you call one of these methods,

    the proxy packages up the input parameters and invokes the Web method using theprotocol encapsulated in the proxy (typically SOAP). The proxy insulates you from

    the low-level details of the Web service and of the protocols that it uses. It even

    parses the XML that comes back and makes the result available as managed types.

    To write a client, following are the steps:

    Use Wsdl.exe to create a proxy class for Calc.asmx. If you installed Calc.asmx in wwwroot, the

    http://localhost/calc.asmxhttp://localhost/calc.asmx
  • 7/27/2019 summer - MC0081.doc

    5/8

    proper command is wsdl http://localhost/calc.asmx. Wsdl.exe responds by creating a file named

    Calculator Web Service.cs.

    Create a new text file named CalcClient.cs and enter the code in Figure. Compile the CS files into

    a console application with the following command: cscCalcClient.cs "Calculator Web Service.cs".

    Run CalcClient.exe.

    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

    a) CREATING APPLICATION POOLS(IIS 6.0)

    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 yourapplications remain available even when a worker process serving an application pool is

    recycled because of a faulty application.

    Steps to create a new Application Pool:

    In IIS Manager, expand the local computer, right-click Application Pools, point to New, and then

    click Application Pool.

    In the Application pool name box, type the name of the new application pool.

    If the ID that appears in Application pool ID box is not the ID that you want, type a new ID.

    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.

    Click OK.

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

    to an application pool.

    b) DEPLOYING ASP.NET APPLICATIONS : 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 configurationsections in the Machine.config and Web.config files are configured the same way in

    IIS 6.0, except for the section of the Machine.config file. When IIS

    6.0 is configured to run in worker process isolation mode, some of the attributes in thesection 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 sessionstate method. Depending onthe 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.

    Deploy the Web Server

    http://localhost/calc.asmx.http://localhost/calc.asmx.
  • 7/27/2019 summer - MC0081.doc

    6/8

    Install Windows Server 2003.

    Install and configure IIS 6.0.

    Enable ASP.NET in the Web service extensions list.

    Practical Questions:5. 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.

    a.BASIC ARITHMETIC OPERATION:

    using System;class MainClass

    {

    static void Main(string[] args){

    int a,b,c,d,e,f;

    a = 1;b = a + 6;

    Console.WriteLine(b);

    c = b - 3;

    Console.WriteLine(c);d = c * 2;

    Console.WriteLine(d);

    e = d / 2;Console.WriteLine(e);

    f = e % 2;

    Console.WriteLine(f);}

    }

    a) FINDING GREATER OF N NUMBERS

    public static void FindLargestAndSmallest(){

    int arraySize;

    bool isNum;int largestNum;

    int[] numArray = new int[50] //ask the user for the size of their array

    Console.WriteLine("Enter the size of Array"); //read in the valuestring sizeString = Console.ReadLine(); //we will now use TryParse to get the

    numeric value entered

    isNum = Int32.TryParse(sizeString, out arraySize) //now we will determine if the valueis numeric

    if (isNum)

    {

    //then entered a numeric value so now we need to ask for the values they want in array

  • 7/27/2019 summer - MC0081.doc

    7/8

    Console.WriteLine("Enter array value:");

    for (int i = 0; i < arraySize; i++)

    { //int variable to hold the our valuefrom TryParse

    int temp; //read in each value and add it to our array if it's a numeric value

    string arrayValue = Console.ReadLine();isNum = Int32.TryParse(arrayValue, out temp) //now do our check

    if (isNum)

    { //value is numeric soa dd to our arraynumArray[i] = temp;

    }else

    { //value isnt numeric

    Console.WriteLine("Array values must be numeric!");break;

    } }

    Console.Write("\r\n"); //now we need to set the values of our

    largestlargestNum = numArray[0]; //now loop through the length of our array

    for (int i = 1; i < arraySize; i++){ //check if the current array index is larger than the largest number variable

    if (numArray[i] > largestNum)

    { //if it is then that is the largest number(for this iteration)largestNum = numArray[i];

    } //now print out the results

    Console.WriteLine("Largest value is: {0}", largestNum);

    }else{

    Console.WriteLine("Array size must be numeric!");

    }}

    6. Describe the steps involved in creating classes and objects with the help of a

    program in C#.

    A class is a construct that enables you to create your own custom types by grouping

    together variables of othertypes, methods and events. A class is like a blueprint. It definesthe data and behavior of a type. If the class is notdeclared as static, client code can use it

    by creating objects or instances which are assigned to a variable. At that time, the CLR

    marks it as eligible forgarbage collection. If the class is declared as static, then only onecopy exists in memory and client code can onlyaccess it through the class itself, not an

    instance variable.

    Declaring classes

    public class Customer { //Fields, properties, methods and events go here...

    }

  • 7/27/2019 summer - MC0081.doc

    8/8

    Creating object

    Customer object1 = new Customer();

    Class Inheritancepublic class Manager : Employee

    { // Employee fields, properties, methods and events are inherited

    // new Manager fields, properties, methods and events go here...}

    EXAMPLE

    public class Person

    { // Field

    public string name; // Constructor

    Public Person (){

    name = "unknown";

    } // Method

    public void SetName(string newName){

    name = newName;}

    }

    classTestPerson{static void Main(){

    Person person = new Person();

    Console.WriteLine(person.name);

    person.SetName("John Smith");Console.WriteLine(person.name); // Keep the console window 3

    Console.WriteLine("Press any key to exit.");

    Console.ReadKey();}

    } /* Output:unknownJohn Smith*/