Click here to Skip to main content
Click here to Skip to main content

Web Services, a simple approach

, 24 Mar 2006
Rate this:
Please Sign up or sign in to vote.
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:

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

Namespaces used in this application:

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.

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

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

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.

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

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

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:

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)

About the Author

vivekthangaswamy
Software Developer
Australia Australia
No Biography provided

Comments and Discussions

 
QuestionBinding Web Method retun value to AspxGrid view PingroupPurushotham Agaraharam6-Oct-12 5:51 
GeneralMy vote of 5 PinmemberBalakrishnan Dhinakaran19-Feb-12 23:28 
GeneralMy vote of 5 PinmemberNaupad10-Feb-12 7:17 
GeneralThx this is what i was looking for. Pinmemberdarkelfv25-Apr-10 23:30 
GeneralneNode Null Pinmembers_ghasemi8824-Oct-09 9:18 
GeneralneNode NULL reference Pinmemberusucapion19-Oct-09 23:07 
GeneralSome correction in Diagram PinmemberRavindraThakur21-Aug-07 2:36 
GeneralThanks Buddy Pinmembermathen_vacha13-Jun-07 7:48 
A nice information for beginners...god bless
 
MJ
GeneralMemory Stream PinmemberelGamal28-Mar-06 19:29 
AnswerRe: Memory Stream Pinmembertopcat4929-Mar-06 18:42 
GeneralRe: Memory Stream PinmemberRob Eckert25-Apr-06 6:44 
GeneralBest One 4 Me... Pinmembervisu127-Mar-06 18:49 
GeneralRe: Best One 4 Me... Pinmemberjgama5-May-06 9:41 
GeneralWeb Services, a simple approach PinmemberSanthosh_26-Mar-06 17:23 
GeneralA simple useless article PinmemberNaveen Karamchetti24-Mar-06 18:10 
GeneralGood One 4 Beginners.... PinmemberLoveConsultant26-Mar-06 16:59 
GeneralRe: A simple useless article Pinmemberjmquesada28-Mar-06 3:38 
GeneralRe: A simple useless article PinmemberNick K6-Apr-06 22:39 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 24 Mar 2006
Article Copyright 2006 by vivekthangaswamy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid