Page 1 of 1

Introduction to Web Services in C#

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1638
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Post icon  Posted 29 September 2007 - 08:59 PM

*
POPULAR

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:

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

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:

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:

/// <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)

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:

 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:

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

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)
Number of downloads: 19747

Is This A Good Question/Topic? 5
  • +

Replies To: Introduction to Web Services in C#

#2 skyhawk133  Icon User is offline

  • Head DIC Head
  • member icon

Reputation: 1865
  • View blog
  • Posts: 20,278
  • Joined: 17-March 01

Posted 29 September 2007 - 09:13 PM

Another excellent tutorial!


Vote for it on DZone: http://www.dzone.com...vices_in_c.html
Was This Post Helpful? 0
  • +
  • -

#3 Guest_jdalicandro*


Reputation:

Posted 12 April 2010 - 07:40 AM

Appreciated the tutorial, and I am having difficulty with the Utlilties.GetConnectionString line. What project did you make the project, as I cannot read it into VS2008.

Thanks.
Was This Post Helpful? 0

#4 Guest_Asif Iqbal*


Reputation:

Posted 07 May 2010 - 01:57 PM

View Postjdalicandro, on 12 April 2010 - 06:40 AM, said:

Appreciated the tutorial, and I am having difficulty with the Utlilties.GetConnectionString line. What project did you make the project, as I cannot read it into VS2008.

Thanks.


using System;
using System.Configuration;

public class Utilities
{
    public static string GetConnectionString(string connectionString)
    {
        return ConfigurationManager.ConnectionStrings[connectionString].ConnectionString;
    }

    public Utilities()
    {
 	//
	// TODO: Add constructor logic here
	//
    }
}



I just tried to help you out, maybe it would helpful for you.
Follow me: @webwizo

Was This Post Helpful? -1

#5 Guest_shilpa jain*


Reputation:

Posted 15 June 2010 - 05:30 AM

Hi PhsycoCode,

I tried to download and run your sample project but it gives me error saying that " the project WebconsumerService.csproj cannot be opened. The project type is not supported by this installation "
I have Visual Studio 2005 TE.

Please help.

Thanks & Regards,
Shilpa
Was This Post Helpful? 0

#6 Guest_Azfar*


Reputation:

Posted 06 August 2010 - 01:48 AM

I created an object then call a method but dont know how to read the response/result returned from the service which is type integor.

svcServerAdmin.svcServerAdmin service = new svcServerAdmin.svcServerAdmin();

service.GetSpoolMessageCount("admin", "ew1234");
Was This Post Helpful? 0

#7 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Posted 06 August 2010 - 07:27 AM

If your web method is returning an Integer, then just assign the return value to an Integer variable.

int messageCount = service.GetSpoolMessageCount("admin", "ew1234");

Was This Post Helpful? 0
  • +
  • -

#8 Guest_Amir*


Reputation:

Posted 20 December 2010 - 11:13 PM

Yes

Thank You!

it really Helped me.
Was This Post Helpful? 0

#9 Guest_Bhawna*


Reputation:

Posted 12 February 2011 - 06:17 AM

hi there seems to be an error while i was running the code
and providing the perimeter.is there some mistake
here is the code.
public DataSet GetAllUserInfo(string ConfigManagerConnectionString,string TableName)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ConfigManagerConnectionString].ConnectionString);
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet dsInfo = new DataSet();
        string querry = "select * from " + TableName;
        try
        {
            cmd.CommandText = querry;
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            da.SelectCommand = cmd;
            da.Fill(dsInfo);
            return dsInfo;
        }
        catch
        { 
        
        }
    }


it shows the following error
Service.GetAllUserInfo(string, string)': not all code paths return a value.
Was This Post Helpful? 0

#10 Guest_web dev*


Reputation:

Posted 16 February 2011 - 04:02 PM

View PostBhawna, on 12 February 2011 - 06:17 AM, said:

it shows the following error
Service.GetAllUserInfo(string, string)': not all code paths return a value.


Add a return statement in the catch block similar to:

catch
{
    return Content(string.Empty);
}



Just return what you wish.
Was This Post Helpful? 0

#11 Guest_Bhawna*


Reputation:

Posted 17 February 2011 - 09:29 AM

sir i just want to send the connection string and the name of the table as a perimeter so that the same webservice can be used for many working tables and for that purpose i am also defining the connection string and sending it as a perimeter and returning the result in form of dataset. is it possible.i hope i am not doing anything wrong.


View Postweb dev, on 16 February 2011 - 04:02 PM, said:

View PostBhawna, on 12 February 2011 - 06:17 AM, said:

it shows the following error
Service.GetAllUserInfo(string, string)': not all code paths return a value.


Add a return statement in the catch block similar to:

catch
{
    return Content(string.Empty);
}



Just return what you wish.

Was This Post Helpful? 0

#12 divyah1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-January 12

Posted 19 January 2012 - 11:53 AM

Hi, request anybody to please tell me from where can I download the sample code file for this project?
Was This Post Helpful? 0
  • +
  • -

#13 liwenz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 12-August 13

Posted 12 August 2013 - 07:30 AM

I like this one, I need a mark to here.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1