Wednesday, February 25, 2009

Simple Web Services Application: Populating Grid view, Data Access.

Introduction:


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 new 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 are powerful technologies that provide 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 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 article is to learn what a web service is? How to create a web service in .NET, How to access the database using web services? How to populate Grid View using web services?

Let’s see first what is 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 service standards, includes
• Simple Object Access Protocol (SOAP),
• Web Services Description Language (WSDL), and
• Universal Description, Discovery and Integration (UDDI)

SOAP is based on XML and 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 you web service in a minute. After creating your web service write a simple method for testing your web services. Here in this article I written a simple public method called DisplayTextMsg() this will written 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 a XML document. Here in this article I have written that method as like this 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 lets see how we can access this web services in your 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. Here let’s see how the WebMethod are called in your ASP.NET WebPages. First initialize the web service in your class.
localhost.Service myService1 = new localhost.Service();
After initializing your web service, you can invoke WebMethod from that web services in your ASP.NET pages. First let’s see how the DisplayTextMsg() is invoked in your ASP.NET page. In this article I called 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 demonsration.
Let’s see how a gridview control is populated using a web services and in this demonstration the web services will access the database and then it will populate the gridview. The WebMethod GetDataFromDB() will return a XML Document, I inserted 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 snippets will populate your gridview control using data’s from Web Services. And now you can build your own web services and use it in any application you want. Now a small reference diagram how web services works, the architectural diagram.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home