Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 136,187 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,116 people online right now. Registration is fast and FREE... Join Now!




Introduction to Web Services in C#

 
Reply to this topicStart new topic

> Introduction to Web Services in C#

PsychoCoder
Group Icon



post 29 Sep, 2007 - 07:59 PM
Post #1


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:

Attached 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:

CODE

[WebService(Namespace = "http://tempuri.org/")]
[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:

CODE

public SampleService ()
{

    //Uncomment the following line if using designed components
    //InitializeComponent();
}


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:

CODE

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Data;
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:

CODE

/// <summary>
/// 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
/// </summary>
/// <returns>A dataset popululated with the Members informaiopn</returns>
[WebMethod]
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
    try
    {
        //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
       /// Utlilties.HandleConnectionState(conn);
        //set the SelectCommand Property
        ///of our SqlDataAdapter Object
        adapter.SelectCommand = cmd;
        //now we fill our DataSet
        ///using the Fill Method of
        ///the SqlDataAdapter
        adapter.Fill(dsInfo, "Members");
        //return the DataSet to the calling aspx page
        return dsInfo;
    }
    catch (Exception ex)
    {
        System.Web.HttpContext.Current.Response.Write(ex.Message);
        return null;
    }
    finally
    {
        ///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
      /// Utlilties.HandleConnectionState(conn);
    }      
}


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)

CODE

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
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:

Attached 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:

Attached 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:

CODE

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";
     gvMembers.DataBind();              
}


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

CODE

protected void Page_Load(object sender, EventArgs e)
{
     BindGrid();
}


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

CODE

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 smile.gif

Attached File  SampleWebService.zip ( 483.09k ) Number of downloads: 790
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

skyhawk133
Group Icon



post 29 Sep, 2007 - 08:13 PM
Post #2
Another excellent tutorial!


Vote for it on DZone: http://www.dzone.com/links/introduction_to...vices_in_c.html
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 12/2/08 01:17AM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month