About Me

My photo
जिंदगी की परीक्षा में कोई नम्बर नहीं मिलते है लोग आपको दिल से याद करे तो समझ लेना आप पास हो गए....

Wednesday 5 December 2012

MC0081 Solved Assignment


Master of Computer Application (MCA) – Semester 5

MC0081 – . (DOT) Net Technologies – 4 Credits

(Book ID: B0974)

Assignment Set – 1 (40 Marks)




1. 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
*/

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.
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 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 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. 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. 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.
Figure 2 shows the sample login Web Form that you will use.




































Figure : Sample showing how to enter data and display it back into a label control


To build a Login form
  1. Open Visual Studio and, on the Start page, click Create New Project.
  2. Highlight Visual Basic Projects from the treeview on the left.
  3. In the Templates window, click Web Application.
  4. For the Name of this project, type WebForms101.
  5. Choose the location of the machine where you wish to create this Web site.
  6. Click OK to begin the process of creating the new Web Application project.
  7. You should now have a Web Form named WebForm1.aspx in your Visual Studio project. Rename this form to Login.aspx.
  8. 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 5.
Table . Controls used to build the Login form
Control Type
Property
Value
Label
Name
Label1

Text
First Name
TextBox
Name
txtFirst

Text

Label
Name
Label2

Text
Last Name
TextBox
Name
txtLast

Text

Button
Name
btnSubmit

Text
Login
Label
Name
lblName

BorderStyle
Insert

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.
  1. Press F5 to run this sample application.
  2. 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.
  1. End the program by closing down the browser.
  2. 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.
  3. 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 txtFirst 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.

3. Describe the following with respect to State Management in ASP.Net:
a. Cookies in ASP.NET
b. Session State
c. Application State
Ans.
a)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"
%>
It is also possible to assign properties to a cookie, like setting a date when the cookie should expire:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2012#
%>


Retrieve a Cookie value

The "Request.Cookies" command is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "firstname" and display it on a page:
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
Output: Firstname=Alex

A Cookie with Keys

If a cookie contains a collection of multiple values, we say that the cookie has Keys.
In the example below, we will create a cookie collection named "user". The "user" cookie has Keys that contains information about a user:
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>


Read all Cookies

Look at the following code:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
Assume that your server has sent all the cookies above to a user.
Now we want to read all the cookies sent to a user. The example below shows how to do it (note that the code below checks if a cookie has Keys with the HasKeys property):
<!DOCTYPE html>
<html>
<body>

<%
dim x,y
for each x in Request.Cookies
  response.write("<p>")
  if Request.Cookies(x).HasKeys then
    for each y in Request.Cookies(x)
      response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
      response.write("<br>")
    next
  else
    Response.Write(x & "=" & Request.Cookies(x) & "<br>")
  end if
  response.write "</p>"
next
%>

</body>
</html>
Output:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25

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-of-process 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 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.


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.
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.
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";
        }
    }
}
A default method HelloWorld is generated and commented out. Simply uncomment and build the project. Hey Presto, you have a walking talking WebService.
A WebService should be associated with a namespace. Your Wizard-generated service will have the name space http://tempuri.org. If you compile and run the service as-is you'll get a long involved message indicating you should choose a new namespace, so we add the namespace, and the WebService description as follows:

[WebService(Namespace="http://codeproject.com/webservices/",
            Description="This is a demonstration WebService.")]
public class WebService1 : System.Web.Services.WebService
{
    ...
To test the service you can right click on WebService1.asmx in the Solution Explorer in Visual Studio and choose "View in Browser". The test page is shown below,























When invoked this returns the following:






Running demo application

If you downloaded the source code with this article then you will need to create a directory 'WebServices' in yourweb site's root directory and extract the downloaded zip into there. You should then have:

\WebServices
\WebServices\bin
\WebServices\WebService1.asmx
...
Navigating to http://localhost/WebServices/WebService1.asmx won't show you the WebService because you need to ensure that the webservice's assembly is in the application's /bin directory. You will also find that you can't load up the solution file MyService.sln. To kill two birds with one stone you will need to fire up the IIS management console, open your website's entry, right click on the WebServices folder and click Properties. Click the 'Create' button to create a new application the press OK. The /WebServices directory is now an application and so the.NET framework will load the WebService assembly from the /WebServices/bin directory, and you will be able to load and build the MyService.sln solution.

































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.


for any issue write me  @ rsravishri30@gmail.com

No comments:

Post a Comment