Welcome to this tutorial on Creating and Consuming a Web Service in ASP.Net Using C#. In this tutorial we will see how to create a simple Web Service, then consume that Web Service in a .Net Page. In this tutorial I walk you through creating a basic web service that retrieves data from a database, then passes a populated DataSet back to the calling page to populate a GridView control with it.

What is a Web Service you say? Well a Web Service is very general model for building applications that can be implemented for any operating system that supports communication over the web. To some this may sound a lot like a Web Site, but that is not the case, here are the main differences between a Web Service and a Web Site:

  • Web Site has an interface – Web Service has no interface
  • Web Site is designed to interact with people – Web Service is designed to interact with other applications
  • Web Site is designed to work with web browser clients – Web Service is designed to work with any type of client or device

So you can see, though they have nearly the same purpose, they go about it in vastly different ways. A webservice uses HTTP (Hypertext Transfer Protocol) and SOAP (Simple Object Access Protocol) to transfer the data between the service and the client.

First, we need to create a Web Service application, to do this open Visual Studio, then click File > New Website:

Resized to 84% (was 600 x 421) – Click image to enlargeAttached Image

Once the next dialog opens, select Web Service from the list, then under Location select File System and Language choose Visual C#.

Attached Image

When the Project is created, you get a Service.asmx and a Service.cs. You can either delete those and add new one called SampleService.asmx, and this will also create the SampleService.cs, or you can right-click and choose Rename, the choice is really yours. When you double-click on the SampleService.cs file to open it’s code, the first thing you see is:

1 [WebService(Namespace = "http://tempuri.org/")]
2 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

This declares this as a Web Service, but what’s the Namespace? Well, Tempuri.Org defines a Web Service Namespace as:

“Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.

Your XML Web Service should be identified by a namespace that you control. For example, you can use your company’s Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.”

The next line uses WebServiceBinding to create the Web Services version of an Interface.

After that is your constructor, same as any class, you can use this to initialize objects:

1 public SampleService ()
2 {
3
4     //Uncomment the following line if using designed components
5     //InitializeComponent();
6 }

Now we get to the heart of the Web Method, which is, of course, to make it do something. If you want your method to be visible outside your Web Service you need to add the [WebMethod()] Attribute to it. Adding this Attribute tells the service that it’s ok to have that public method visible outside the Web Service itself.

Since this is just a simple, basic Web Service it only has a single method, just to show you what can be done with a Web Service. Since this service is communicating with a Sql Database, it needs access to the System.Data.SqlClient Namespace. Other namespaces the Web Service needs access to are:

So at the very top of our Web Service CS file we need to add our references:

1 using System;
2 using System.Web;
3 using System.Web.Services;
4 using System.Web.Services.Protocols;
5 using System.Data.SqlClient;
6 using System.Data;
7 using System.Configuration;

This, since it is just an introduction to Web Services, has a single method in it, GetAllUserInfo, which, when invoked, queries the database to retrieve the database for this method. The Stored Procedure is hard coded in the method, but you could actually make it very scalable by making it a parameter thats passed to the method. Once it receives the data, it uses a SqlDataAdapter to fill a DataSet, this is then returned, as rendered XML, to the client.

NOTE: Don’t worry, the client renders the XML back into the DataSet for you, you don’t need to know XML for Web Service Basics.

Now let’s take a look at that code:

01 /// <summary>
02 /// Here we're going to create a [WebMethod] that
03 /// can be called from an aspx page, then return
04 /// a populated DataSet to the calling aspx page
05 /// </summary>
06 /// <returns>A dataset popululated with the Members informaiopn</returns>
07 [WebMethod]
08 public DataSet GetAllUserInfo()
09 {
10     //Build the SqlCilent Objects we need
11     SqlConnection conn = new SqlConnection(Utlilties.GetConnectionString("WebService_Conn"));
12     SqlCommand cmd = new SqlCommand();
13     ///SqlDataAdapter to populate our DataSet
14     SqlDataAdapter adapter = new SqlDataAdapter();
15     ///DataSet to hold the users information
16     DataSet dsInfo = new DataSet();
17     ///String to hold our stored procedure
18     string query = "RetrieveUserInfo";
19     ///try...catch block to handle any unhandeled exceptions
20     try
21     {
22         //set our SqlCommands Objects
23         cmd.CommandText = query;
24         cmd.CommandType = CommandType.StoredProcedure;  //tell it its a Stored Procedure we're executing
25         //if using inline SQL change the CommandType to Text
26         //cmd.CommandType = CommandType.Text;
27         //set its connection property
28         cmd.Connection = conn;
29
30         //now handle the connection state
31         ///of our SqlConnection Object
32        /// Utlilties.HandleConnectionState(conn);
33         //set the SelectCommand Property
34         ///of our SqlDataAdapter Object
35         adapter.SelectCommand = cmd;
36         //now we fill our DataSet
37         ///using the Fill Method of
38         ///the SqlDataAdapter
39         adapter.Fill(dsInfo, "Members");
40         //return the DataSet to the calling aspx page
41         return dsInfo;
42     }
43     catch (Exception ex)
44     {
45         System.Web.HttpContext.Current.Response.Write(ex.Message);
46         return null;
47     }
48     finally
49     {
50         ///put everyting in the finally section
51         ///of the try...catch block you want executed
52         ///whether theres an exception or not, in this
53         ///case we want to close the connection no
54         ///matter what happens
55         ///close the connection
56       /// Utlilties.HandleConnectionState(conn);
57     }    
58 }

Simple method most programmers have seen, or at least some variation of it, quite often. Query the database, get all the user information, populate a DataSet, return the data. Thats the only method in our basic, simple Web Service. Now lets take a look at home we would consume this Web Service from an ASP.Net Web Application.

Next we’re going to add a web site. At the top of your tree in the Solution Explorer right-click and select Add > New Project:

Attached Image

When the New Project dialog opens we will choose ASP.Net Web Site as the project type, HTTP as the Location, and C# as the Language. When the project is created is automatically adds a Default.aspx, and Default.aspx.cs. It’s the CS file we will be doing the programming in. You always want to keep your presentation separate from your logic, thats why Microsoft offers both files for a single page in .Net.

Since this is just a sample, open Default.aspx in Design Mode, add a table to the page, then a GridView to the page. The GridView is what we’ll use to display the data returned from our Web Service. You are now finished designing our ASPX page for consuming our Web Service.

Now open our Default.aspx.cs file and the following Namespace References will be there (you wont need anymore for this example)

01 using System;
02 using System.Data;
03 using System.Configuration;
04 using System.Collections;
05 using System.Web;
06 using System.Web.Security;
07 using System.Web.UI;
08 using System.Web.UI.WebControls;
09 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;

Now we need to add a reference to our Web Service, to do this, right-click on your project name and select Web Reference to add a web reference:

Attached Image

Once you do that, the Add Web Reference dialog box will open:

Resized to 91% (was 550 x 331) – Click image to enlargeAttached Image

When that appears select Web services in this solution, it will then go through the entire solution searching for a Web Service. Click on the name of your Web Service (the sample one we just created)and it will populate the URL bar at the top, and add the name localhost to the Web reference name box in the right hand side of the dialog box:

Resized to 91% (was 550 x 331) – Click image to enlargeAttached Image

I renamed mine from localhost to Sample, the clicked the Add Reference button. Now we have a reference to our web reference in our web application, and can use it.

Next, create a simple method named BindGrid(), this is the method that will:

  • Create a reference to our Web Service
  • Create a new DataSet
  • Set our new DataSet to the GetAllUserInfo function in our Web Service
  • Bind our GridView to the returned DataSet

The code that accomplishes this looks like this:

01 private void BindGrid()
02 {
03      //create our DataSet to hold the member information returned
04      DataSet dsMembers = new DataSet();
05      //create our WebService object
06      WebServiceConsumer.Sample.SampleService sample = new WebServiceConsumer.Sample.SampleService();
07      //set our DataSet to the GetAllUsers Method of our web service
08      dsMembers = sample.GetAllUserInfo();
09      //now we need to set some properties for our data grid
10      gvMembers.AutoGenerateColumns = true;
11      gvMembers.DataSource = dsMembers.Tables["Members"].DefaultView;
12      gvMembers.DataMember = "UserID";
13      gvMembers.DataBind();           
14 }

Then in your Page_Load event call BindGrid() once the page loads, like this:

1 protected void Page_Load(object sender, EventArgs e)
2 {
3      BindGrid();
4 }

Believe it or now that’s it, thats all it takes to consume our simple Web Service. Here the line

1 WebServiceConsumer.Sample.SampleService sample = new WebServiceConsumer.Sample.SampleService();

Creates a reference to our Web Service, we then execute the GetAllUserInfo() method and assign the results to the DataSet Object we created. Now, when you save and view the page in the browser, it should, as long as you followed all these steps, display the data from the Web Service in your GridView.

In this tutorial I am also including the solution I was working from when writing this tutorial, the project also includes the SQLExpress database used for this example. All I ask is that you keep the header in tact.

NOTE: I forgot to mention, in this project, and this tutorial, I have been referencing a Utilities.cs file that I created for basic DB operations. THis file is included in the attached project.

Thank you for reading, and I hope this helps at lease one programmer 🙂

Attached File  SampleWebService.zip (483.09K)

 

Reference :http://www.dreamincode.net/forums/topic/34279-introduction-to-web-services-in-c%23/

 

Enhanced by Zemanta

One thought on “Create Simple Web Service in Visual Studio 2008 / 2010

Leave a Reply

Your email address will not be published. Required fields are marked *