You are on page 1of 18

August 2012

Master of Computer Application (MCA) - Semester 5 MC0081 - . (DOT) Net Technologies - 4 Credits
(Book ID: B0974)

Assignment Set - 1 (40 Marks)


Answer all Questions Each question carries TEN marks

1. Describe the steps involved in creating classes and objects with the help of a program in C#. 2. 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. 3. Describe the following with respect to State Management in ASP.Net: a. Cookies in ASP.NET b. Session State c. Application State 4. Describe the following with respect to Web Services in .Net: a. Writing and Testing a Web Service b. Implementing a Web Service Client

August 2012

Master of Computer Application (MCA) - Semester 5 MC0081 - . (DOT) Net Technologies - 4 Credits
(Book ID: B0974)

Assignment Set - 2 (40 Marks)


Answer all Questions Each question carries TEN marks

1. Write a program in C# language to perform the following operations: a. Basic arithmetic operations b. Finding greatest of n numbers Write separate programs for each of the above points. 2. Explain the following with respect to ASP.Net: a. Master Pages b. Themes & Skins Write code snippets to demonstrate the above concepts. 3. Design a simple Window based form application to perform basic arithmetic operations. 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

1. 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 other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable. For more information, see Static Classes and Static Class Members (C# Programming Guide). Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming. Declaring classes public class Customer { //Fields, properties, methods and events go here... } Creating object Customer object1 = new Customer(); Class Inheritance public class Manager : Employee { // Employee fields, properties, methods and events are inherited // New Manager fields, properties, methods and events go here... } EXAMPL E public class Person { // Field public string name; // Constructor public Person() { name = "unknown"; } // Method public void SetName(string newName) { name = newName; } } class TestPerson { static void Main() { Person person = new Person();

Console.WriteLine(person.name); person.SetName("John Smith"); Console.WriteLine(person.name); Console.WriteLine("Press any key to exit."); Console.ReadKey(); }}

2. Describe the following with respect to creating Web Forms in .Net environment: A. Web Form Life Cycle B.Creating a Web Form

Ans 2 of A Stage 1 - Initialization After the control hierarchy has been built, the Page, along with all of the controls in its control hierarchy, enter the initialization stage. This stage is marked by having the Page and controls fire their Init events. At this point in the page life cycle, the control hierarchy has been constructed, and the Web control properties that are specified in the declarative syntax have been assigned. Stage 2 - Load View State The load view state stage only happens when the page has been posted back. During this stage, the view state data that had been saved from the previous page visit is loaded and recursively populated into the control hierarchy of the Page. It is during this stage that the view state is validated. As we'll discuss later in this article, the view state can become invalid due to a number of reasons, such as view state tampering, and injecting dynamic controls into the middle of the control hierarchy. Stage 3 - Load Postback Data The load postback data stage also only happens when the page has been posted back. A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data.

To help clarify things, let's look at a simple example. One nice thing about ASP.NET is that the Web controls in a Web Form remember their values across postback. That is, if you have a TextBox Web control on a page and the user enters some value into the TextBox and posts back the page, the TextBox's Text property is automatically updated to the user's entered value. This happens because the TextBox Web control implements the IPostBackDataHandler interface, and the Page class hands off the appropriate value to the TextBox class, which then updates its Text property. To concretize things, imagine that we have an ASP.NET Web page with a TextBox whose ID property is set to txtName. When the page is first visited, the following HTML will be rendered for the TextBox: <input type="text" id="txtName" name="txtName" />. When the user enters a value into this TextBox (such as, "Hello, World!") and submits the form, the browser will make a request to the same ASP.NET Web page, passing the form field values back in the HTTP POST headers. These include the hidden form field values (such as __VIEWSTATE), along with the value from the txtName TextBox. Stage 4 - Load This is the stage with which all ASP.NET developers are familiar, as we've all created an event handler for a page's Load event (Page_Load). When the Load event fires, the view state has been loaded (from stage 2, Load View State), along with the postback data (from stage 3, Load Postback Data). If the page has been posted back, when the Load event fires we know that the page has been restored to its state from the previous page visit.

Stage 5 - Raise Postback Event Certain server controls raise events with respect to changes that occurred between postbacks. For example, the DropDownList Web control has

a SelectedIndexChanged event, which fires if the DropDownList's SelectedIndex has changed from the SelectedIndex value in the previous page load. Another example: if the Web Form was posted back due to a Button Web control being clicked, the Button's Click event is fired during this stage. There are two flavors of postback events. The first is a changed event. This event fires when some piece of data is changed between postbacks. An example is the DropDownListsSelectedIndexChanged event, or the TextBox's TextChanged event. Server controls that provide changed events must implement the IPostBackDataHandler interface. The other flavor of postback events is the raised event. These are events that are raised by the server control for whatever reason the control sees fit. For example, the Button Web control raises the Click event when it is clicked, and the Calendar control raises the VisibleMonthChanged event when the user moves to another month. Controls that fire raised events must implement the IPostBackEventHandler interface. Stage 6 - Save View State In the save view state stage, the Page class constructs the page's view state, which represents the state that must persist across postbacks. The page accomplishes this by recursively calling the SaveViewState() method of the controls in its control hierarchy. This combined, saved state is then serialized into a base-64 encoded string. In stage 7, when the page's Web Form is rendered, the view state is persisted in the page as a hidden form field. In the render stage the HTML that is emitted to the client requesting the page is generated. The Page class accomplishes this by recursively invoking the RenderControl() method of each of the controls in its hierarchy. These seven stages are the most important stages with respect to understanding view state. (Note that I did omit a couple of stages, such as the PreRender and Unload stages.) As you continue through the article, keep in mind that every single time an ASP.NET Web page is requested, it proceeds through these series of stages.

Ans 2 of B

Creating a New ASP.NET Web Forms Page


When you create a new Web site using the ASP.NET Web Site project template, Visual Studio adds an ASP.NET page (Web Forms page) named Default.aspx. You can use the Default.aspx page as the home page for your Web site. However, for this walkthrough, you will create and work with a new page.

To add a page to the Web site


1. Close the Default.aspx page. To do this, right-click the tab that displays the file click name and then click Close Close. 2. In Solution Explorer, right , right-click the Web site (for example, C:\ \BasicWebSite), and then click Add New Item Item. The Add New Item dialog box is displayed. The following illustration shows an example of the Add New Item dialog box.

3. In the template list, select Web Form. 4. In the Name box, type FirstWebPage. When you created the Web site project, you specified a default language based on the project template that you selected. However, each time you create a new page or component for your Web site, you can select the programming language for that page or component. You can use different programming languages in the same Web site. 5. Clear the Place code in separate file check box.

In this walkthrough, you are creating a single-file page with the code and HTML in the same page. The code for ASP.NET pages can be located either in the page or in a separate class file. 6. Click Add. Visual Studio creates the new page and opens it.

Adding HTML to the Page


In this part of the walkthrough, you will add some static text to the page.

To add text to the page


1. At the bottom of the document window, click the Design tab to switch to Design view. Design view displays the page that you are working on in a WYSIWYG-like way. At this point, you do not have any text or controls on the page, so the page is blank except for a dashed line that outlines a rectangle. This rectangle represents a div element on the page. 2. Click inside the rectangle that is outlined by a dashed line. 3. Type Welcome to Visual Web Developer and press ENTER twice. The following illustration shows the text you typed in Design view.

4. Switch to Source view. You can see the HTML that you created by typing in Design view, as shown in the following illustration.

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

Cookiesin asp.net : Web applications can store small pieces of data in the clients Web browser by using cookies. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary). The most common use of cookies is to identify a single user as he or she visits multiple Web pages. Reading and Writing Cookies: A Web application creates a cookie by sending it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request. Create a cookie -> add a value to the Response.Cookies HttpCookieCollection. Read a cookie -> read values in Request.Cookies. Example:

// Check if cookie exists, and display it if it does if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains clientside script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value); else Label1.Text = "No value defined"; // Define the cookie for the next visit Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

If you do not define the Expires property, the browser stores it in memory and the cookie is lost if the user closes his or her browser. To delete a cookie, overwrite the cookie and set an expiration date in the past. You cant directly delete cookies because they are stored on the clients computer. Controlling the Cookie Scope: By default, browsers wont send a cookie to a Web site with a different hostname. You can control a cookies scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates:

Example:

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

Through this the scope is limited to the /Application1 folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement: Example: Response.Cookies[lastVisit].Domain = Contoso; Storing Multiple Values in a Cookie: Though it depends on the browser, you typically cant store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates: Example:

Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString(); Response.Cookies["info"]["firstName"].Value = "Tony"; Response.Cookies["info"]["border"].Value = "blue"; Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);

Running the code in this example sends a cookie with the following value to the Web browser: (visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue) Query Strings: Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. A typical query string might look like the following real-world example: http://support.microsoft.com/Default.aspx?kbid=315233 In this example, the URL identifies the Default.aspx page. The query string (which starts with a question mark [?]) contains a single parameter named kbid, and a value for that parameter, 315233. Query strings can also have multiple parameters, such as the following real-world

URL, which specifies a language and query when searching the Microsoft.com Web site: http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=hello+world Value Name | ASP.NET Object | Value mkt | Request.QueryString[mkt] | en-US setlang | Request.QueryString[setlang] | en-US q | Request.QueryString[q] | hello world Limitations for Query Strings: 1. Some Browsers and client devices impose a 2083 character limit on the length of the URL. 2. You must submit the page using an HTTP GET command in order for query string values to be available during page processing. Therefore, you shouldnt add query strings to button targets in forms. 3. You must manually add query string values to every hyperlink that the user might click. Example:

Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) + ", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) + ", Page: " + Server.HtmlEncode(Request.QueryString["page"]);

Server - Side State Management: Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted. ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors: a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.

b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging. c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.

Session State: ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary. You can use session state to accomplish the following tasks: i. Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit. ii. Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information. iii. Raise appropriate session management events. In addition, you can write application code leveraging these events. ASP.NET session state supports several different storage options for session data: a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer. b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the

startup type to Automatic. c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities. d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider. e. Off Disables session state. You should disable session state if you are not using it to improve performance.

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

Ans 4 Of A Testing A Web Service


How do you test an ASMX Web service? Simple: just call it in your browser. To demonstrate, copy Calc.asmx to wwwroot and type http://localhost/calc.asmx in your 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 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 spelled out in the WebMethod attributes.

Calc.asmx as seen in Internet Explorer

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

Test page for the Add method

XML returned by the Add method

The forms that ASP.NET generates on the fly from ASMX files enable you to test the Web services that you write without writing special clients to test them with. They also let you explore a Web service built with the .NET Framework simply by pointing your browser to it. For kicks, type the following URL into your browsers address bar: http://terraservice.net/terraservice.asmx Thats the URL of the Microsoft TerraService, an ultra-cool Web service that provides a programmatic interface to a massive database of geographic data known as the Microsoft TerraServer. Dont worry about the details just yet; youll be using TerraService to build a Web service client later in this chapter. But do notice how much you can learn about TerraService simply by viewing the page that ASP.NET generated for it.

Ans 4 Of B Testing A Web Service

Implementing Web Service Clients


Now that youve seen Web services up close and personal, its time to learn about 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 some high-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