Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Article

Web Services, a simple approach

Rate me:
Please Sign up or sign in to vote.
3.58/5 (32 votes)
24 Mar 2006CPOL5 min read 122.5K   1.5K   79   19
This articles is an introduction to web services, with a simple illustration.

Abstract

The World Wide Web is more and more used for application to application communication. The programmatic interfaces made available are referred to as Web services. The label "web services", as broadly applied, has two levels of meaning — one is specific and another one is conceptual. .NET is the distributed computing platform developed by Microsoft, and ASP.NET is its programming model for web development. With the advent of .NET and the .NET Framework, Microsoft introduced a set of new technologies in the form of Web services and .NET remoting. ASP.NET Web services is a powerful technology that provides a suitable framework for developing distributed applications.

Overview of the Solution

The main idea of this series of articles is not to make you feel as though you are learning a whole new technology altogether, but to make you realize that this new innovation is reusing existing knowledge to create a more capable and robust system in the Web world. Basically, this article is for learning what a web service is, how to create a web service in .NET, how to access the database using web services, how to populate a GridView using web services etc.

Let’s see first what a web service is. Web services are loosely coupled, reusable software components that semantically encapsulate discrete functionality, and are distributed and programmatically accessible over standard Internet protocols.

Specifically, web services are a stack of emerging standards that describe service-oriented, component-based application architecture.

Conceptually, web services represent a model in which discrete tasks within e-business processes are distributed widely throughout a value net.

Standards

Core Web services standards include:

  • Simple Object Access Protocol (SOAP),
  • Web Services Description Language (WSDL), and
  • Universal Description, Discovery, and Integration (UDDI)

SOAP is based on XML, and is not a binary protocol such as DCOM, you can inspect the data exchange in detail using a network tunneling tool and see exactly what is going on under the hood.

XML Web services are the fundamental building blocks in the move to distributed computing on the Internet. Open standards and the focus on communication and collaboration among people and applications have created an environment where XML Web services are becoming the platform for application integration.

WSDL (often pronounced whiz-dull) stands for Web Services Description Language. WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. WSDL is to SOAP what IDL is to CORBA or COM. Since WSDL is XML, it is readable and editable, but in most cases, it is generated and consumed by software.

Controls used in this application:

C#
protected System.Web.UI.WebControls.GridView GridView1;

Namespaces used in this application:

C#
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Runtime.InteropServices;
using System.Configuration;
using System.Diagnostics;
using System.EnterpriseServices;
using System.Xml;

Solution with Code

Creating a web service using Visual Studio .NET is one of the easiest tasks. By using the Visual Studio .NET wizards, you can create your web service project in a minute. After creating your web service project, write a simple method for testing your web services. Here in this article, I have written a simple public method called DisplayTextMsg() that will output a string.

C#
// Simple method :: This return a string 
[WebMethod]
public string DisplayTextMsg() 
{
    return "My First Service For Testing";
}

Attaching the WebMethod attribute to a public method indicates that you want the method exposed as part of the XML Web service. The WebMethod attribute provides the following properties:

  • BufferResponse - The BufferResponse property of the WebMethod attribute enables buffering of responses for an XML Web service method.
  • CacheDuration - The CacheDuration property of the WebMethod attribute enables caching of the results for an XML Web service method.
  • Description - The Description property of the WebMethod attribute supplies a description for an XML Web service method that will appear on the Service help page.
  • EnableSession - The EnableSession property of the WebMethod attribute enables session state for an XML Web service method.
  • MessageName - The MessageName property of the WebMethod attribute enables the XML Web service to uniquely identify overloaded methods using an alias.
  • TransactionOption - The TransactionOption property of the WebMethod attribute enables the XML Web service method to participate as the root object of a transaction.

Database Access Method:

Now, let’s write a simple method to connect to the database and fetch the data, and return it as an XML document. I have written that method as follows:

C#
// Simple method to access database :: This return a xml Document
[WebMethod]
public XmlDocument GetDataFromDB()
{
    string errorMessage = "";
    XmlDocument myDatas = new XmlDocument();
    //Connection string is stored 
    //in the web.config file as an appSetting
    string connectionString = 
      ConfigurationSettings.AppSettings["DatabaseConnectionString"];
    SqlConnection dbConnection = null;
    // Open a connection to the database
    try
    {
        dbConnection = new SqlConnection(connectionString);
        dbConnection.Open();
    }
    catch (Exception ex)
    {
        errorMessage = ex.Message;
    }
    if (errorMessage == "")
    {
        // Build an insert command
        string SQL = "select * From ProfileContact";
        SqlCommand GetCustomerCmd = new SqlCommand(SQL, dbConnection);

        try
        {
            SqlDataAdapter custDA = new SqlDataAdapter();
            custDA.SelectCommand = GetCustomerCmd;
            DataSet custDS = new DataSet();
            custDA.Fill(custDS, "ProfileContact");
            myDatas.LoadXml(custDS.GetXml());
            dbConnection.Close();
           
        }
        catch (System.Exception ex)
        {
            errorMessage = ex.Message;

        }
        finally
        {
            dbConnection.Dispose();
        }
    }
    return myDatas;
}

After writing these methods, let's see how we can access this web service in our ASP.NET web application. So first, create a new web application. In the Solution Explorer window, right-click on References and select Add Web Reference. In the Add a Web Reference window, enter the path to your Web Service (http://localhost:2034/WebServices/Service.asmx). Then, click on the Add Reference button.

Now, let’s see how the WebMethod is called in your ASP.NET web pages. First, initialize the web service in your class.

C#
localhost.Service myService1 = new localhost.Service();

After initializing your web service, you can invoke the WebMethod from that web service in your ASP.NET pages. First, let’s see how the DisplayTextMsg() is invoked in your ASP.NET page. Here, I call this WebMethod in a button click event.

C#
// Button Click Event 
protected void Button1_Click(object sender, EventArgs e)
{
    string serMsg = myService1.DisplayTextMsg();
    lbl_display.Text = serMsg.ToString();
}

The above snippet is a simple demonstration.

Let’s see how a GridView control is populated using a web service, and in this demonstration, the web service will access the database and then it will populate the GridView. The WebMethod GetDataFromDB() will return an XML document. I insert that XML document into a DataSet, and then the resulting Dataset is populated in the GridView.

C#
// Data Binding :: DataSet Appending
public void DataBindFrmWS()
{
   XmlDocument myServiceDoc = new XmlDocument();
   System.Xml.XmlNode neNode;
   //Adding the resulting XML from WebMethod to a user created XmlNode
   neNode = myService1.GetDataFromDB();
   //Creating a Dataset
   DataSet myDataSet = new DataSet();
   //The XmlNode is added to a byte[]
   byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(neNode.OuterXml);
   System.IO.MemoryStream ms = new System.IO.MemoryStream(buf);
   //The XML is readed from the MemoryStream
   myDataSet.ReadXml(ms);
   
   GridView1.DataSource = myDataSet.Tables[0];
   GridView1.DataBind();
}

The above code snippet will populate your GridView control using data from a Web Service.

Image 1

And now, you can build your own web service and use it in any application you want.

Here is a small reference diagram showing how web services work:

Image 2

Summary

This article is to initiate your skill in web services, and this is by no means a complete list of what you can do with web services. But it's a start, and it should have you on track to building distributed applications using web services in no time. And the Visual Studio .NET wizard will help you easily develop web services in no time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer at Zealots
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGreat article for beginner but... Pin
Member 1146753914-Apr-15 3:09
Member 1146753914-Apr-15 3:09 
QuestionBinding Web Method retun value to AspxGrid view Pin
Purushotham Agaraharam6-Oct-12 5:51
Purushotham Agaraharam6-Oct-12 5:51 
GeneralMy vote of 5 Pin
Balakrishnan Dhinakaran19-Feb-12 23:28
professionalBalakrishnan Dhinakaran19-Feb-12 23:28 
GeneralMy vote of 5 Pin
Naupad10-Feb-12 7:17
Naupad10-Feb-12 7:17 
GeneralThx this is what i was looking for. Pin
darkelfv25-Apr-10 23:30
darkelfv25-Apr-10 23:30 
GeneralneNode Null Pin
s_ghasemi8824-Oct-09 9:18
s_ghasemi8824-Oct-09 9:18 
GeneralneNode NULL reference Pin
usucapion19-Oct-09 23:07
usucapion19-Oct-09 23:07 
GeneralSome correction in Diagram Pin
RavindraThakur21-Aug-07 2:36
RavindraThakur21-Aug-07 2:36 
GeneralThanks Buddy Pin
mathen_vacha13-Jun-07 7:48
mathen_vacha13-Jun-07 7:48 
GeneralMemory Stream Pin
elGamal28-Mar-06 19:29
elGamal28-Mar-06 19:29 
AnswerRe: Memory Stream Pin
topcat4929-Mar-06 18:42
topcat4929-Mar-06 18:42 
GeneralRe: Memory Stream Pin
Rob Eckert25-Apr-06 6:44
Rob Eckert25-Apr-06 6:44 
GeneralBest One 4 Me... Pin
R.Viswanathan27-Mar-06 18:49
R.Viswanathan27-Mar-06 18:49 
GeneralRe: Best One 4 Me... Pin
jgama5-May-06 9:41
jgama5-May-06 9:41 
I agree, this is the best example for beginners I've seen so far and it's actually useful for developers as well. To be able to use a service to query a database is a scenario that I ran into recently and more people will find it useful as well. The diagrams and comments make this example very clear and a real world scenario with so much detail is the best gift to beginners.
Keep up the good work!



Peace,

Joseph Gama
GeneralWeb Services, a simple approach Pin
Santhosh_26-Mar-06 17:23
Santhosh_26-Mar-06 17:23 
GeneralA simple useless article Pin
Naveen Karamchetti24-Mar-06 18:10
professionalNaveen Karamchetti24-Mar-06 18:10 
GeneralGood One 4 Beginners.... Pin
LoveConsultant26-Mar-06 16:59
LoveConsultant26-Mar-06 16:59 
GeneralRe: A simple useless article Pin
jmquesada28-Mar-06 3:38
jmquesada28-Mar-06 3:38 
GeneralRe: A simple useless article Pin
Nick K6-Apr-06 22:39
Nick K6-Apr-06 22:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.