You are on page 1of 21

Summer 2013 Master of Computer Application (MCA) Semester 5 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 concept

Ans) a) Web Form Life Cycle : Every request for a page made from a web server causes a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with a request for the page, which causes the server to load it. When the request is complete, the page is unloaded. From one end of the life cycle to the other, the goal is to render appropriate HTML output back to the requesting browser. The life cycle of a page is marked by the following events, each of which you can handle yourself or leave to default handling by the ASP.NET server:

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

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

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

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

Send Post back Change Modifications: If there are any state changes between the current state and the previous state, change events are raised via the Raise Post Data Changed Event ( ) method. Handle Post back Events: The client-side event that caused the post back is handled. Pre Render: This is the phase just before the output is rendered to the browser. It is essentially your last chance to modify the output prior to rendering using the OnPreRender ( ) method.

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

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

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

b) Creating a Web Form :


Let's create a Web Form that allows a user to input their first and last names. After entering the data into these two text fields on the Web page, the user clicks a login button and the user's Last name, First name appear in a label below the login button. To build a Login form *Open Visual Studio and, on the Start page, click Create New Project. *Highlight Visual Basic Projects from the tree view on the left. *In the Templates window, click Web Application.

*For the Name of this project, type WebForms101. *Choose the location of the machine where you wish to create this Web site. *Click OK to begin the process of creating the new Web Application project. *You should now have a Web Form named WebForm1.aspx in your Visual Studio project. Rename this form to Login.aspx. *Open the Toolbox and create the form in Figure by adding the appropriate controls and setting the properties of those controls as outlined in Table.

Control Type Label

Property Name Text

Value Label1 First Name Txt First

Text Box

Name Text

Label

Name Text

Label2 Last Name Txt Last

Text Box

Name Text

Button

Name Text

BtnSubmit Login LblName Insert

Label

Name Border Style Text

Try It Out
At this point, you can run this application and see this Web Form appear in your browser. Although this page does not have any functionality yet, this exercise is a good test to make sure everything is running up to this point. Press F5 to run this sample application. If you receive an error message informing you that you need a start page, right-click the Login.aspx page and click Set as Start Page from the context menu. You should now see the Web Form displayed in your browser, and you can enter data into the two text fields. If you click the Login button, nothing will happen because you have not told it to do anything yet. You will next learn how to make this Login button do something.

Adding Code to the Button


Let's add some code to the button so that it posts the data you entered in the text boxes, and fills in the appropriate data in the label below the button control. End the program by closing down the browser. While looking at the Login page in design mode, double-click the Login button control. You will now see a code window appear with the event procedure btnSubmit. Right-click by your cursor. Fill in the Click event procedure so it looks like the following code. Public Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click lblName.Text = txtLast.Text & ", " & txtFirst.Text

End Sub
What you have just done is retrieved the text property from both the txtLast and txt First text boxes and placed the data into the label control below the Login button. This should look very familiar, if you have ever programmed in Visual Basic. In fact, the

whole point of .NET is that all of the coding, whether for Windows applications or Web applications, should look the same.

2). Describe the following with respect to State Management in ASP.Net: a. Cookies in ASP.NET b. Session State c. Application State
Ans) . Cookies in ASP.NET :
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With ASP, you can both create and retrieve cookie values.

Create a Cookie
The "Response.Cookies" command is used to create cookies. Note: The Response.Cookies command must appear BEFORE the <html> tag. In the example below, we will create a cookie named "firstname" and assign the value "Alex" to it:
<% Response.Cookies("firstname")="Alex" %>

B) Session State :
ASP.NET allows you to save values by using session state which is an instance of the HttpSessionState class for each active Web-application session. Session state is similar to application state, except that is is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.

Session state is structured as a key/value dictionary for storing session-specific information that needs to be maintained between server round trips and between requests for pages. You can use session state to accomplish the following tasks: Uniquely identity browser or client-device requests and map them to an individual session instance on the server. Store session-specific data on the server for use across multiple browser or client-device requests within the same session. Raise appropriate session management events. In addition, you can write application code leveraging these events. Once you add your application-specific information to session state, the server manages this object. Depending on which options you specify, session information can be stored in cookies, on an out-ofprocess server, or an a computer running Microsoft SQL Server.

c) Application State:
ASP.NET allows you to save values using application state which is an instance of the HttpApplocationState class for each active Web application. Application state is a global storage m mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests. Once you add your application-specific information to application state, the server manages it.

3. Describe the following with respect to Web Services in .Net: a. Writing and Testing a Web Service b. Implementing a Web Service Client Ans). 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. For this example I have created a service called MyService in the /WebServices directory on my local machine. The files will be created in the /WebServices/MyService directory.

A new namespace will be defined called MyService, and within this namespace will be a set 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 the ASP.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.

There are also a number of files created: AssemblyInfo.cs


Contains version and configuration information for your assembly.

web.config
Defines how your application will run (debug options, the use of cookies etc).

MyService.disco
Discovery information for your service.

WebService1.asmx
Your WebService URL. Navigate to this file in a browser and you will get back a user-friendly page showing the methods available, the parameters required and the return values. Forms are even provided allowing you to test the services through the web page.

bin\MyService.dll
The actual WebService component. This is created when you build the service.

The class for your service that is created by default is called (in this case) WebService1, and is within theMyService namespace. The code is partially shown below.

namespace MyService { ... /// <summary> /// Summary description for WebService1. /// </summary> [WebService(Namespace="http://codeproject.com/webservices/", Description="This is a demonstration WebService.")] public class WebService1 : System.Web.Services.WebService { public WebService1() { //CODEGEN: This call is required by the ASP+ Web Services Designer InitializeComponent(); } ... [WebMethod] public string HelloWorld() { return "Hello World";

} } }

B) Implementing a Web Service Client :

Let's start by creating a simple "Hello world" web service. When we create and run this web service , it will be run by a web browser. However, in real life, the true aim of web service can only be achieved if we can call it from some web application or a console application.

1)<%@ WebService Language= "C#" Class= "HelloWorld" %> 2)using System; 3)using System.Web.Services; 4) 5)[web service (Namespace = "http://myorg.org/webservices")] 6)public class HelloWorld : web service 7){ 8)[WebMethod] 9)public String GetMessage() 10){ 11)String message = "Hello World"; 12)return message; 13)} 14)}

Creating a console application client for web service

Before further description, let me introduce the concept of proxy class to you. This class plays a third party role for interacting between a client and a server. It facilitates all the communication between the client and the server, be it connecting client to the server or passing parameters and methods to the server or returning results from the server. We should create a proxy as a first step to enable console application to call a web service. Creating Web proxy

A utility named WSDL.exe is available in .NET to create proxies. This utility needs to know the WSDL which the proxy should use. Follow these steps to create a proxy using WSDL.exe: 1. Choose Start >> Visual Studio.NET >> Visual Studio.NET Tools >> Visual Studio.NET Command Prompt to open the Visual Studio.NET command prompt.

2. Create a new directory for storing client projects.

3. In the command prompt, type: - C:> cd projects \ wsclient (directory where client project is stored) - C:\ src \ wsclient > wsdl /l:CS /n:WebBook /out:HelloworldProxy.cs http://localhost/TimeService/Hello.asmx?WSDL This command needs explanation: /l:CSindicates a proxy built in C Sharp Language. /n:WebBookspecifies namespace /out:HelloworldProxy.cs specifies the proxy name. In this case, it is HelloWorldProxy. http://localhost/TimeService/Hello.asmx?WSDL is the url which is description of the web service for which proxy class is being created.

4. As the last step, Compile the proxy you have made by typing: C: \ projects \ wsclient> csc /t:library HelloWorldProxy.cs WSDL utility generates the source code of HelloWorldProxy.cs in result. This proxy file will contain a new definition for HelloWorld class that we developed in Listing 1.1. This class definition is different from the definition we have created before but our clients will use this definition. Instead of executing methods directly, it invokes the methods of original class (HelloWorld in this case). When you see the source code of this file, you will also notice two functions BeginGetMessage() and EndGetMessage(). These two functions have been created to facilitate calling the web services asynchronously. The proxy class has been created. Now, we can write console applications as clients: 1) using System; 2) using WebBook; 3) 4) namespace WebBook 5) { 6) public class HelloClient 7) { 8) public static void main() 9) { 10) HelloWorld hw = new HelloWorld(); 11) Console.WriteLine ("Message returned from web service"); 12) 13) Console.WriteLine (hw.GetMessage()); 14) 15) } 16) } 17) }

Since you have created a proxy class and compiled it, you no longer need to worry how this client application calls the web service or how methods and parameters are sent. The proxy class handles all the work in background. All you need to do for creating a console application client is: Create a proxy class and tell it the WSDL url of the web service to be accessed.

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 Ans) a. Creating Application Pools (IIS 6.0)
With IIS 6.0 running in worker process isolation mode, you can group Web applications into application pools. Application pools allow specific configuration settings to be applied to groups of applications, and the worker processes servicing those applications. Any Web directory or virtual directory can be assigned to an application pool.

By creating new application pools and assigning Web sites and applications to them, you can make your server more efficient and reliable, and your other applications always available, even when the applications in the new application pool terminate.

Procedures To create a new application pool

1. In IIS Manager, double-click the local computer, right-click Application Pools, point to New, and then click Application Pool.

2.

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

3. Under Application pool settings, click either Use default settings for new application pool or Use existing application pool as template. 4. If you selected Use existing application pool as template, from the Application pool name list box, click the application pool to be used as a template. 5. Click OK.

B). Deploying ASP.NET Applications


ASP.NET is a unified Web application platform that provides services to help you build and deploy enterprise-class Web applications and XML-based Web services. ASP.NET is supported on the Microsoft Windows Server 2003, Standard Edition; Windows Server2003, Enterprise Edition; Windows Server2003, Datacenter Edition; and Windows Server2003, Web Edition operating systems. ASP.NET is installed with the Microsoft .NET Framework version 1.1 as a part of Windows Server 2003. However, to run ASP.NET applications, you must also install IIS 6.0. Important ASP.NET is not available on the following operating systems: Microsoft Windows XP 64-Bit Edition; the 64-bit version of Windows Server 2003, Enterprise Edition; and the 64-bit version of Windows Server 2003, Datacenter Edition. For more information, see "Features unavailable on 64-bit versions of the Windows Server 2003 family" in Help and Support Center for Microsoft Windows Server 2003. The deployment process presented in this section describes how to deploy ASP.NET applications on a newly installed IIS 6.0 Web server. Before you begin this process, complete the following steps: Install Windows Server 2003, which includes version 1.1 of the .NET Framework, with the default options. Install IIS 6.0 with the default settings in Add or Remove Programs in Control Panel. If you need to install ASP.NET applications that were written for IIS 5.0 or version 1.0 of the .NET Framework on a new Web server, see Migrating IIS Web Sites to IIS 6.0. If you want to upgrade a Web server running IIS 5.0

that is hosting existing ASP.NET applications, see Upgrading an IIS Server to IIS 6.0. When you configure IIS 6.0 to run in IIS 5.0 isolation mode, the settings in the <processModel> section of the Machine.config file are configured in the same way as they were in IIS 5.0 in the Machine.config or Web.config files. For more information about configuring ASP.NET applications when IIS 6.0 is configured to run in IIS 5.0 isolation mode, see Overview of ASP.NET Configuration. Upon completing the process described in this section, you will have a Web server running IIS 6.0 and hosting your ASP.NET applications. However, you can further configure the Web server to improve the security and availability of your ASP.NET applications. For more information about configuring your Web server to improve the security and availability of your ASP.NET applications, see Securing Web Sites and Applications and Ensuring Application Availability.

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
Ans

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; 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; } } } } }

Output: Program for addition,substraction,multiplication and division Enter your choice:1-add, 2-sub,3-mul, 4-div:1 Enter first no:5 Enter second no :3 5+3=8

Program for addition,substraction,multiplication and division Enter your choice:1-add, 2-sub,3-mul, 4-div:1 Enter first no:5 Enter second no :3 5-3=2

Program for addition,substraction,multiplication and division

Enter your choice:1-add, 2-sub,3-mul, 4-div:1 Enter first no:5 Enter second no :3 5*3=15

Program for addition,substraction,multiplication and division Enter your choice:1-add, 2-sub,3-mul, 4-div:1 Enter first no:5 Enter second no :3 5/3=1 5%3=2

B. Finding greatest of n numbers


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

namespace ConsoleApplication23 { class Program

{ static void Main(string[] args) { int i, largest;

int[] array = new int[5]; for (i = 0; i < 5; i++) { Console.WriteLine("Enter elements:{0}", i+1); array[i] = Convert.ToInt32(Console.ReadLine()); } largest = array[0]; for (i = 0; i <5; i++) { if (array[i] > largest) { largest = array[i]; } } Console.WriteLine("The Largest number is :{0}", largest); Console.ReadLine(); } }

6). Describe the steps involved in creating classes and objects with the help of a program in C#.
Ans) 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... }

EXAMPLE

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

// Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }

} /* Output: unknown John Smith */