Wednesday, December 19, 2007

Create the Web Service

First we’ll create the Web service function or method that'll you'll call (or “expose”) over the Internet as you would any object-oriented class. The difference is that we’ll have to incorporate and import all the necessary Web Services namespaces, syntax and attributes, as well as our data namespaces, in this case. As this article uses C#, any important differences regarding VB will be shown as well.

So go ahead and copy the code below to a file called suppliers.asmx. Save it to your Inetpub/wwwroot folder, and then run it in your browser using http://localhost/suppliers.asmx. What you'll see is a list of the Web Service Descriptions, including the Web service name and the exposed method.

By clicking the exposed method link, you'll be presented with the three main protocols that are available for your use. Just so you know, the file with the .asmx extension is the actual Web Service file that enables the ASP.NET runtime to return all pertinent exposed Web service methods and information.

<%@ WebService Language="C#" Class="GetInfo" %>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

[WebService(Description="My Suppliers List Web Service")]

public class GetInfo : WebService
{

[WebMethod(BufferResponse=true)]

public DataSet ShowSuppliers (string str)
{

SqlConnection dbConnection = new SqlConnection("server=(local);
uid=sa;pwd=;database=Northwind;");

SqlDataAdapter objCommand = new SqlDataAdapter("select
ContactName, CompanyName, City, Phone from Suppliers
where Country = '" + str + "' order by ContactName
asc", dbConnection);

DataSet DS = new DataSet();

objCommand.Fill(DS);

return DS;

dbConnection.Close();
dbConnection = null;

}

}

The <%@ WebService Language="C#" Class="GetInfo" %> directive sets up the file as a Web Service, gives it a name and specifies the language it uses.

No comments: