I posted a tutorial on my favorite programming forum </dream.in.code>, and thought Id go ahead and share it on my blog as well. One question I get all the time in programming communities, always by young, new programmers, is how to work with web Services in .Net. It was these questions that lead me to writing the tutorial I posted on Dream.In.Code.
I guess before you can show someone how to create and consume a Web Service, you need to ensure they know and understand what a Web Service actually is. The following is the easiest, simplest definition I've been able to come up for "What is a web service":
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, there are many differences between the two.
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 as you can see, a Web Service and a Web Application have almost the same role, they just go about fulfilling that role in vastly different ways. A Web Service uses HTTP (Hypertext Transfer Protocol) and SOAP (Simple Object Access Protocol) to transfer data to and from the clients. Data sent to and from the Web Service is rendered into XML so the Web Service can read it, then it is sent back to the slient, which then renders the returned XML into the format it was expecting.
First, lets take a look at creating a simple Web Service. To do this, open Visual Studio, once it loads click File > New Website, when the New Project Dialog opens, select Web Service from the list of available projects, then for Location select either HTTP or File System (your own IIS), and lastly for Language select C#.
When the project is created it creates a Service.amsx and Sercive.cs file, you can either rename these, or delete and add new ones with the name of SampleService asmx and SampleService.cs.Now double-click on SampleService.cs to open the code file, then make sure you have the following references at the top of your class:
If all the references aren't there, add the ones that are missing. Next, you will notice the first 2 lines are out of the ordinary, if you've never created a Web Service these two lines are downright weird:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
Heres whats going on here, line 1 declares the Web Service's Namespace, and you might now be wondering Well whats a namespace? Well luckily theres an answer to that: 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 of the first section of the Web Service uses the WebServiceBinding Method to create the Web Service's version of an Interface. After those 2 lines then you have your Initializer, which is, of course, the same as any other class. Here you can instantiate any objects you need used in each instance of the service:
public SampleService ()
//Uncomment the following line if using designed components
Nothing new there, now we get to jump into the heart of a Web Service, which is, of course, to make it do something, to perform some service. When you create your methods, if you want them to be visible from the client thats consuming the service, you have to add the [WebMethod()] Attribute to it. This tells the service that its ok to expose that method to the client which is consuming it.
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. There are other Namespaces the service will use, we listed them above, but lets take a closer look at them:
Since the is an example for a beginner with Web Services, our sample service has but a single method in it, GetAllUserInfo. This method is designed to:
- Query a SQL Server
- Retrieve all the information for all users in the system
- Populate a DataSet using a SqlDataAdapter
- Pass the DataSet back to the client.
Now lets take a look at the code for this method:
/// Here we're going to create a [WebMethod] that
/// can be called from an aspx page, then return
/// a populated DataSet to the calling aspx page
/// <returns>A dataset popululated with the Members informaiopn</returns>
public DataSet GetAllUserInfo()
//Build the SqlCilent Objects we need
SqlConnection conn = new SqlConnection(Utlilties.GetConnectionString("WebService_Conn"));
SqlCommand cmd = new SqlCommand();
///SqlDataAdapter to populate our DataSet
SqlDataAdapter adapter = new SqlDataAdapter();
///DataSet to hold the users information
DataSet dsInfo = new DataSet();
///String to hold our stored procedure
string query = "RetrieveUserInfo";
///try...catch block to handle any unhandeled exceptions
//set our SqlCommands Objects
cmd.CommandText = query;
cmd.CommandType = CommandType.StoredProcedure; //tell it its a Stored Procedure we're executing
//if using inline SQL change the CommandType to Text
//cmd.CommandType = CommandType.Text;
//set its connection property
cmd.Connection = conn;
//now handle the connection state
///of our SqlConnection Object
//set the SelectCommand Property
///of our SqlDataAdapter Object
adapter.SelectCommand = cmd;
//now we fill our DataSet
///using the Fill Method of
//return the DataSet to the calling aspx page
catch (Exception ex)
///put everyting in the finally section
///of the try...catch block you want executed
///whether theres an exception or not, in this
///case we want to close the connection no
///matter what happens
///close the connection
This operates as explained. It opens a connection to our database, retrieves all the user information from the users table, then populates a Dataset ans returns the DataSet to the client. Notice the [WebMethod()] attribute at the start of the method, this says that any client that consumes this Web Service will have access to that method, and the data it returns.
Believe it or not, our Web Service is complete. Now with a Web Service in a production environment will have much more meat on its bones, but for our demonstration, this is really all we need to show how a Web Service works. Next question people ask is "Ok, we have this service out there on our server, how do we access it and use it?". Well thats a good question, to use the Web Service we just created you need a consumer, a client that will connect to the service and gather the data.
In this example we will create an ASP.Net Web Application that will consume our Web Service, then display the returned data in a GridView Control. So, in your Solution Explorer window, right-click on the very top node, the solution name, then select Add > New Project. Once the New Project Dialog opens, you will this time select ASP.Net Web Site as the project type, once again either HTTP or File System for the Location and C# for 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 seperate 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 Default.aspx.cs, and make sure you have the following references at the top of your class:
Those are the only references you will need for this example. Now we need to add a reference to the Web Service we just created, to do this:
- Right-click on the project name
- Select Add Web Reference
- Once the dialog box opens select Web Services in this solution
- Once it finds your service, click on its name
- Wait for it to connect to the Web Service (when this happens the TextBox in the right-hand side of the dialog will be populated with the word localhost
- Click the Add Reference button
NOTE: Before clicking the Add Reference button I renamed my from localhost to Sample
Now we have a reference to our Web Service and can starting using it. In our ASPX page we have a single method, BindGrid(), and this method will:
- Create a referene to our Web Service
- Create a new DataSet
- Set our DataSet to the GetAllUserInfo method in our Web Service (remember, it returns a populated DataSet)
- Bind the returned DataSet to our GridView
The code for this method is:
private void BindGrid()
//create our DataSet to hold the member information returned
DataSet dsMembers = new DataSet();
//create our WebService object
WebServiceConsumer.Sample.SampleService sample = new WebServiceConsumer.Sample.SampleService();
//set our DataSet to the GetAllUsers Method of our web service
dsMembers = sample.GetAllUserInfo();
//now we need to set some properties for our data grid
gvMembers.AutoGenerateColumns = true;
gvMembers.DataSource = dsMembers.Tables["Members"].DefaultView;
gvMembers.DataMember = "UserID";
Simple enough isnt it? Now to use this, we will call this method from our Page_Load Event in our page, and that looks like this:
protected void Page_Load(object sender, EventArgs e)
Believe it or not, thats it, thats all the code required to consume our Web Service and sisplay the returned data. The one difference in our BindGrid method is this:
WebServiceConsumer.Sample.SampleService sample = new WebServiceConsumer.Sample.SampleService();
That is where we create the reference to our Web Service, then we can use sample.WhateverMethodIsThere for utilizing the methods in the Web Service, instead of typing the long name out.
I am also providing a links to the Source Code for this example, all I ask is that you keep the header intact.
Thank you for reading, and I hope you found this helpful