……………………………………………….Expertise in .NET Technologies

  • Categories

  • Advertisements

Access Database Using Web Services

Posted by Ravi Varma Thumati on October 21, 2009


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. An ASP.NET Web service 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.


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
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
public XmlDocument GetDataFromDB()
    string errorMessage = "";
    XmlDocument myDatas = new XmlDocument();
    //Connection string is stored
    //in the web.config file as an appSetting
    string connectionString =
    SqlConnection dbConnection = null;
    // Open a connection to the database
        dbConnection = new SqlConnection(connectionString);
    catch (Exception ex)
        errorMessage = ex.Message;
    if (errorMessage == "")
        // Build an insert command
        string SQL = "select * From ProfileContact";
        SqlCommand GetCustomerCmd = new SqlCommand(SQL, dbConnection);

            SqlDataAdapter custDA = new SqlDataAdapter();
            custDA.SelectCommand = GetCustomerCmd;
            DataSet custDS = new DataSet();
            custDA.Fill(custDS, "ProfileContact");

        catch (System.Exception ex)
            errorMessage = ex.Message;

    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

   GridView1.DataSource = myDataSet.Tables[0];

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

web Services10

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:

web Services11


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.


One Response to “Access Database Using Web Services”

  1. Could not thank you adequately for the blogposts on your website. I know you place a lot of time and energy into these and truly hope you know how deeply I appreciate it. I hope I’ll do something identical man or woman sooner or later.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: