How to Create and Consume Web Service


By Jakir Hossain
Printer Friendly Version
View My Articles

  

In this article I want to simply describe the steps how to create a web service and use it in project.



First we have to be confirmed that IIS is installed in my computer to examine this project, if not installed then it needs to be installed first. This sample project is tested in VisualStudio2005 platform.

 

1(Web Service Creation): First we will Create a web Service file (*.asmx) and put it into inetpub\wwwroot folder---

 

Name - UserInfo.asmx

 

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

 

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

 

using System.Data;

using System.Data.SqlClient;

 

//[WebService(Namespace = "http://tempuri.org/")]

//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 

public class UserInfo  : System.Web.Services.WebService {

 

    [WebMethod]

    public string HelloWorld() {

        return "Hello World";

    }

    public DataSet ShowUsers(string str)

    {

        SqlConnection dbConnection = new SqlConnection("server=192.168.201.69;uid=sa;pwd=pims;database=HRFORMS;");

 

        SqlDataAdapter objCommand = new SqlDataAdapter("select * from USERS where Department = '" + str + "' order by Name asc", dbConnection);

 

        DataSet DS = new DataSet();

 

        objCommand.Fill(DS);

 

        return DS;

 

        dbConnection.Close();

        dbConnection = null;

 

    }   

   

}

 

Here, I can change database server IP, database name and table as needs.

 

After creation and put it into wwwroot, We can test it initially by typing in browser - http://localhost/ UserInfo.asmx or http://localhost/ UserInfo.asmx?wsdl

 

2(Create proxy class file/Source file of web service): Using the following tool we will create a source class (*.cs) file.

 

 

C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin>

 

wsdl.exe /l:CS /n:WService /out:bin/GetUsers.cs http://localhost/UserInfo.asmx?WSDL

 

Note1: /l:CS – is the language you are using

Note2: /n:WService - creates the Web Service namespace so you could reference it from your .aspx page.

Note3: /out:bin/GetUsers.cs – Where and name of the class file that will be generated.

 

3(Create DLL from source file):. Now I will create the DLL file of GetUsers.cs file.

 

Run the following tool to convert class file into DLL file at command prompt)

 

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>

 

csc /t:library /out:bin\GetUsers.dll bin\GetUsers.cs /reference:System.dll,System.Data.dll,System.Web.dll,System.Web.Services.dll,System.XML.dll /optimize

 

Note1: /out:bin\GetUsers.dll – location and name of DLL file that will be generated.

Note2: bin\GetUsers.cs – location and name of class file to convert into DLL file.

 

4(Consume web service in .aspx page ):.Now we will add DLL file(GetUsers.dll) in another web project to consume my web service earlier created.

 

Name - WebServiceConsume.aspx

 

<%@ Page Language="C#" Explicit="true" Strict="true" Buffer="true"%>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<%@ Import Namespace="WService" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <title>Untitled Page</title>

</head>

<script language="C#" runat="server">

 

void Page_Load(Object sender, EventArgs e) { Response.Flush();}

 

void SubmitBtn_Click (object src, EventArgs e){

 

int RcdCount;

string Department = DropDown1.SelectedItem.Text;

 

 

//Instantiate DLL

WService.UserInfo  userInfo = new WService.UserInfo();

 

 

//Pass parameter into DLL function

DataSet MyData = userInfo.ShowUsers(Department);

 

 

MyDataGrid.DataSource = MyData.Tables[0].DefaultView;

MyDataGrid.DataBind();

 

RcdCount = MyData.Tables[0].Rows.Count;

if (RcdCount <= 0) {

 

Message.InnerHtml = "<b>No results were found for <FONT Color=Red><i>" + Department + "</i></font>";

MyDataGrid.Visible = false; //Hide Results until needed

 

}else{

 

    Message.InnerHtml = "<b><FONT Color=Red><i>" + Department + "</i></font> has " + RcdCount + " Users</b>";

MyDataGrid.Visible = true;

}

}

 

</script>

<body style="font: 10pt verdana">

 

<h4>Accessing Data with Web Services</h4>

 

<form id="Form1" runat="server">

 

<asp:DropDownList id="DropDown1" runat="server">

<asp:ListItem>IT</asp:ListItem>

<asp:ListItem>NOC</asp:ListItem>

<asp:ListItem>Customer Service</asp:ListItem>

</asp:DropDownList>

<asp:button ID="Button1" text="Submit" OnClick="SubmitBtn_Click" runat="server"/>

<p>

<span id="Message" runat="server"/>

 

</p>

 

 

<ASP:DataGrid id="MyDataGrid" runat="server"

AutoGenerateColumns="True"

Width="100%"

BackColor="White"

BorderWidth="1"

CellPadding="1"

CellSpacing="1"

Font-Size="10pt"

HeaderStyle-BackColor="White"

HeaderStyle-ForeColor="Blue"

AlternatingItemStyle-BackColor="White"

AlternatingItemStyle-ForeColor="Black"

ShowFooter="false"

/>

 

</form>

 

</body>

</html>

 

 

**(Discovering web service):.Here, we can also use disco.exe tool for discovering web service ..

1. Run this following tool at command prompt---

disco http://localhost/UserInfo.asmx?DISCO

 

If that web service is discovered at specific URL then it will be created a discomap file. Discomap contains the path of UserInfo.wsdl file.

 

Then we can run this following tool to create proxy class file as we did earlier in step2.

 

wsdl.exe /l:CS /n:WService /out:bin/GetUsers.cs http://localhost/UserInfo.wsdl

 

Then we can create DLL at next step as we did earlier in step3.

 

csc /t:library /out:bin\GetUsers.dll bin\GetUsers.cs /reference:System.dll,System.Data.dll,System.Web.dll,System.Web.Services.dll,System.XML.dll /optimize


Here is link of sample source code - http://www.eggheadcafe.com/fileupload/1639792319_WebServiceDemo.zip




button
 
Article Discussion: How to Create and Cosume Web Service
Jakir Hossain posted at 04-Jul-08 03:15
Original Article

promotion
Silverlight    WPF    WCF    WWF    LINQ   
JavaScript    AJAX    ASP.NET    XAML   
C#    VB.NET    VB 6.0    GDI+    IIS    XML   
.NET Generics    Anonymous Methods    Delegate   
Visual Studio .NET    Expression Blend    Virus   
Windows Vista    Windows XP    Windows Update   
Windows 2003 Server    Windows 2008 Server   
SQL Server    Microsoft Excel    Microsoft Word   
SharePoint    BizTalk    Virtual Earth   
.NET Compact Framework    Web Service   

"Everything" RSS / ATOM Feed Parser
How to send and receive messages through message queuing in .Net
How to Read text file as database
SQL Server 2005 Paging Performance Tip
Display code of web page.
Fully Scalable Excel File Importer class for .net using Microsoft Jet driver
Generic Chart Color Manager class that can be used for any charts
Helper class to style the infragistics wingrid
Using Reflection to detemine as Assembly Info in and out.
Helper class to play with Window (Owners and position)
Resolving displayname from the culture using the XmlLanguage and LanguageSpecificStringDictionary class
Manipulate file attributes in VB.NET
Forms Based Authentication Filtered Content Editor for SharePoint
How to create a Tree View of the Windows Folder and extract all the file-folder info.
How to use AssemblyInfo.cs file in win forms to provide much needed information on Assemblies
Sorting In Datagrid
Helper class to work with NativeMethods in the native api's
Silverlight Line Of Business Applications With Offline WPF Versions
C# : Database monitoring system using XML file
C# : Adding ComboBox to ListView SubItem
Sum of Numbers Captcha: Keeping it Simple
C# Create a Piechart for the specified Hard Disk Drive Utilization
Extension Methods for DataSet and DataTable that makes tasks easier
Accessing IIS Hosted WCF Services from PHP
Helper class that provides most commonly used Extension Methods for DateTime object
Helper class to work with a Status Bar in WPF.
Finding Unmatched Records in Dataset Tables Using Linq
Silverlight Toolkit: Autocomplete TextBox Stock Symbols and Chart
COOL Auto Complete textbox using javascript
Creating a Serializable Log Entry for Microsoft Enterprise Library to log to a Database
ASP.NET Searching Values in Datagrid