Web Service Step by Step

22
Making the Web Service First, start your Visual Studio .NET, and in the project type, select ASP.NET WebService. In the left pane, choose the language of your choice. In this example, I will be using Visual C#.NET. Once you select the project, a page will appear which will be more like a design page, switch to its code view. In the code view, you can see lot of comments and C# code already written for you. You will also see that at the bottom, there is a method HelloWorld which is written for you by default, so you can test your service and of course say hello to the world. After removing the unwanted code and comments, your code will look like this: using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; namespace WebServiceExample { public class Service1 : System.Web.Services.WebService { public Service1() { InitializeComponent(); }

Transcript of Web Service Step by Step

Page 1: Web Service Step by Step

Making the Web Service

First, start your Visual Studio .NET, and in the project type, select ASP.NET WebService. In

the left pane, choose the language of your choice. In this example, I will be using Visual

C#.NET. Once you select the project, a page will appear which will be more like a design

page, switch to its code view. In the code view, you can see lot of comments and C# code

already written for you. You will also see that at the bottom, there is a method HelloWorld

which is written for you by default, so you can test your service and of course say hello to

the world. After removing the unwanted code and comments, your code will look like this:

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.Web;

using System.Web.Services;

namespace WebServiceExample

{

public class Service1 : System.Web.Services.WebService

{

public Service1()

{

InitializeComponent();

}

// Add the Description Attribute so you

// will know the purpose of your WebService

[WebMethod(Description="This Method prints HelloWorld")]

public string HelloWorld()

{

Page 2: Web Service Step by Step

return "Hello World";

}

}

}

Let's dig into this small code. [WebMethod] Attribute denotes that this method will be used

by the clients, also this method has to be public in order for a client to use it. Description

inside the WebMethod Attribute just gives the method more meaning. Don't worry about the

InitializeComponent() method since it's written by default.

Running the Web Service

OK, now you have made your first kick ass WebService (without even writing a single line of

code). Let's run it and check whether it gives the correct result or not. In the Solution

Explorer, right click on the .asmx file, and select View in Browser as shown below:

Page 3: Web Service Step by Step

Once you click on "View in Browser", the next screen you will see will be something like this:

Page 4: Web Service Step by Step

have erased most of the stuff, so you can only see the method that you need in this

example. Below, you can see the method HelloWorld and the description you wrote for the

method.

Now, click on the HelloWorld method. I don't want to scare you with all the SOAP and HTTP

code produced, so I am only going to paste the screen shot which will be relevant to this

example.

Alright, so far so good. Now, just press the Invoke button to see the result of your method

named HelloWorld().

Page 5: Web Service Step by Step

This is cool. You have just tested your first webservice and it ran since you didn't coded it. I

know what you are thinking right now. Is the client going to see the result like this strange

format (this is XML format). Well, of course not. That's why you need to make a Proxy class

which consumes this service.

Making the Web Service Client

Let's make a Console application which consumes this service. You can use any language

and platform to consume this service, that's the purpose of XML WebService. Now, this

procedure requires some mouse clicking :). So I will write down the steps instead of pasting

the screen shots.

1.Start a new project which will be a Console Application in Visual C#.NET.

2.Once you see the code view in the Console application, right click on the project

name from the Solution Explorer. Remember that project name will be written in

bold.

3.Click on "Add Web Reference".

4.Paste the URL of your WebService. You can get the URL of your WebService when

you view your webservice in IE or any other browser.

5.Click GO.

6.Your webservice will be loaded. In the Web Reference Name textbox, write

"MyService" and click Add Reference.

7.You will see that the web reference has been added in your Solution Explorer,

meaning that webservice is ready to kick some butt.

Now, all you have to do is to make the instance of the WebService class using the reference

name that you provided, which is "MyService".

Page 6: Web Service Step by Step

using System;

namespace MyClient

{

class Class1

{

[STAThread]

static void Main(string[] args)

{

// Make an instance of the WebService Class

// using the Web Reference you provided

MyService.Service1 service = new MyService.Service1();

// Assign message what ever is returned

// from HelloWorld in this case "HelloWorld"

string message = service.HelloWorld();

// Prints out the message on the screen

Console.WriteLine(message);

}

}

}

And that's it. You use the webservice class just like any other class. Something you need to

keep in mind is that if you decide to make a new method in your webservice and want to

make it available to the client, then always remember to build your webservice solution so

that the assembly can be updated. If you don't build your webservice, you won't be able to

see the methods on the client side.

Page 7: Web Service Step by Step

Best Example

Writing a Web Service

Following is our first Web Service; it exposes two methods (Add and SayHello) as Web

Services to be used by applications. This is a standard template for a Web

Service. .NET Web Services use the .asmx extension. Note that a method exposed as a

Web Service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS

virtual directory (as explained in configuring IIS; for example, c:\MyWebSerces).

FirstService.asmx <%@ WebService language="C" class="FirstService" %>

using System; using System.Web.Services; using System.Xml.Serialization;

[WebService(Namespace="http://localhost/MyWebServices/")] public class FirstService : WebService { [WebMethod] public int Add(int a, int b) { return a + b; }

[WebMethod] public String SayHello() { return "Hello World"; } }

Page 8: Web Service Step by Step

Post a comment

Email Article

Print Article

Share Articles

Digg

del.icio.us

Newsvine

Facebook

Google

LinkedIn

MySpace

Reddit

Slashdot

StumbleUpon

Technorati

Twitter

Windows Live

YahooBuzz

FriendFeed

To test a Web Service, it must be published. A Web Service can be published either on

an intranet or the Internet. We will publish this Web Service on IIS running on a local

machine. Let's start with configuring the IIS.

Open Start->Settings->Control Panel->Administrative tools->Internet Services Manager.

Expand and right-click on [Default Web Site]; select New ->Virtual Directory.

The Virtual Directory Creation Wizard opens. Click Next.

The "Virtual Directory Alias" screen opens. Type the virtual directory name—for example,

MyWebServices—and click Next.

The "Web Site Content Directory" screen opens. Here, enter the directory path name for the

virtual directory—for example, c:\MyWebServices—and click Next.

The "Access Permission" screen opens. Change the settings as per your requirements. Let's

keep the default settings for this exercise. Click the Next button. It completes the IIS

configuration. Click Finish to complete the configuration.

To test that IIS has been configured properly, copy an HTML file (for example, x.html) in

the virtual directory (C:\MyWebServices) created above. Now, open Internet Explorer

and type http://localhost/MyWebServices/x.html. It should open the x.html file. If it does

not work, try replacing localhost with the IP address of your machine. If it still does not

Page 9: Web Service Step by Step

work, check whether IIS is running; you may need to reconfigure IIS and Virtual

Directory.

To test our Web Service, copy FirstService.asmx in the IIS virtual directory created

above (C:\MyWebServices). Open the Web Service in Internet Explorer

(http://localhost/MyWebServices/FirstService.asmx). It should open your Web Service

page. The page should have links to two methods exposed as Web Services by our

application. Congratulations; you have written your first Web Service!!!

Testing the Web Service

As we have just seen, writing Web Services is easy in the .NET Framework. Writing

Web Service consumers is also easy in the .NET framework; however, it is a bit more

involved. As said earlier, we will write two types of service consumers, one Web- and

another Windows application-based consumer. Let's write our first Web Service

consumer.

Web-Based Service Consumer

Write a Web-based consumer as given below. Call it WebApp.aspx. Note that it is an

ASP.NET application. Save this in the virtual directory of the Web Service (c:\

MyWebServices\WebApp.axpx).

This application has two text fields that are used to get numbers from the user to be

added. It has one button, Execute, that, when clicked, gets the Add and SayHello Web

Services.

WebApp.axpx <%@ Page Language="C#" %> <script runat="server"> void runSrvice_Click(Object sender, EventArgs e) { FirstService mySvc = new FirstService(); Label1.Text = mySvc.SayHello(); Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString(); } </script> <html>

Page 10: Web Service Step by Step

<head> </head> <body> <form runat="server"> <p> <em>First Number to Add </em>: <asp:TextBox id="txtNum1" runat="server" Width="43px">4</asp:TextBox> </p> <p> <em>Second Number To Add </em>: <asp:TextBox id="txtNum2" runat="server" Width="44px">5</asp:TextBox> </p> <p> <strong><u>Web Service Result -</u></strong> </p> <p> <em>Hello world Service</em> : <asp:Label id="Label1" runat="server" Font-Underline="True">Label</asp:Label> </p> <p> <em>Add Service</em> : & <asp:Label id="Label2" runat="server" Font-Underline="True">Label</asp:Label> </p> <p align="left"> <asp:Button id="runSrvice" onclick="runSrvice_Click" runat="server" Text="Execute"></asp:Button> </p> </form> </body> </html>

After the consumer is created, we need to create a proxy for the Web Service to be

consumed. This work is done automatically by Visual Studio .NET for us when

referencing a Web Service that has been added. Here are the steps to be followed:

Page 11: Web Service Step by Step

Create a proxy for the Web Service to be consumed. The proxy is created using the wsdl utility

supplied with the .NET SDK. This utility extracts information from the Web Service and creates a

proxy. Thus, the proxy created is valid only for a particular Web Service. If you need to consume

other Web Services, you need to create a proxy for this service as well. VS .NET creates a proxy

automatically for you when the reference for the Web Service is added. Create a proxy for the

Web Service using the wsdl utility supplied with the .NET SDK. It will create FirstSevice.cs in the

current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.

c:> WSDL http://localhost/MyWebServices/

FirstService.asmx?WSDL

c:> csc /t:library FirstService.cs

Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\

MyWebServices\bin). IIS looks for the proxy in this directory.

Create the service consumer, which we have already done. Note that I have instantiated an

object of the Web Service proxy in the consumer. This proxy takes care of interacting with the

service.

Type the URL of the consumer in IE to test it (for example,

http://localhost/MyWebServices/WebApp.aspx).

Webservice with Ajax

Step 1:First Create Asp.net web application.

Step 2:Right Click The project name then choose "Add New Item".Add New Item window will display and choose

"Web Service".

Step 3:Give Name of That web serviece(Default WebService1.asmx) and choose C# Language.

Step 4:Add The following code in WebService.cs file.

Page 12: Web Service Step by Step

using System;

using System.Collections;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Xml.Linq;

using System.Web.Script.Services;

/// <summary>

/// Summary description for WebService

/// </summary>

Page 13: Web Service Step by Step

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo =

WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script,

using ASP.NET AJAX, uncomment the following line.

// [System.Web.Script.Services.ScriptService]

[ScriptService]

public class WebService : System.Web.Services.WebService

{

public WebService () {

Page 14: Web Service Step by Step

//Uncomment the following line if using designed

components

//InitializeComponent();

}

[WebMethod]

public string HelloWorld() {

return "This Message Coming From Server0-" +

DateTime.Now.ToString();

}

}

Page 15: Web Service Step by Step

Step 5:drag and drop the Scriptmanager control to your asp.net file.

Step 6:Add The ServiceReference with in scriptmanager control.

<asp:ScriptManager ID="ScriptManager1"

runat="server">

<Services><asp:ServiceReference

Path="~/WebService.asmx" /></Services>

</asp:ScriptManager>

Step 7:Add The one button control to your asp.net web page.this control is used to call the webservice.

Step 8:Create one javascript function to call the HelloWorld().

function HelloWorld()

{

Page 16: Web Service Step by Step

WebService.HelloWorld(OnSucceeded);

return false;

}

function OnSucceeded(result)

{

alert(result);

}

The entire code of the Aspx file is

<%@ Page Language="C#" AutoEventWireup="true"

CodeFile="Default.aspx.cs" Inherits="_Default" %>

Page 17: Web Service Step by Step

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-

transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

<script type="text/javascript">

function HelloWorld()

{

WebService.HelloWorld(OnSucceeded);

Page 18: Web Service Step by Step

return false;

}

function OnSucceeded(result)

{

alert(result);

}

</script>

</head>

<body>

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1"

runat="server">

Page 19: Web Service Step by Step

<Services><asp:ServiceReference

Path="~/WebService.asmx" /></Services>

</asp:ScriptManager>

<div>

<asp:Button ID="Button1" runat="server"

Text="Call WebService Method"

OnClientClick="HelloWorld()" />

</div>

</form>

</body>

</html>