Consuming Webservice In A Windows Application






3.57/5 (15 votes)
This article describes how to create and use a webservice in a Windows application in C#
Introduction
This article will show you how to create a webservice and how to consume it in a Windows application using C#.
Using the Code
This is coded on the Visual Studio 2008 Team System, so I have uploaded only the source (*.cs) file so that you can use the code files in your earlier version Visual Studio Editions.BlogWService
is a webservice and XML Writer is a Windows application that uses that webservice.
BlogWService
Let's look into webservice first. In this, I am retrieving values of my database that are on a remote server. Earlier, I tried a lot to connect it from Windows application directly, but my remote server throws an exception that, "this SQL Server is not configured for remote connections". So, I then decided to move towards webservice, that will access my database locally and using that webservice, I will fetch data into a WinForm application. This is quite lengthy but interesting too. I am a newbie to webservice, but gained a lot while doing this. Hope you people enjoy it too.
Let's come to the app. The code of Webservice is very simple. It is the same as that of ASP.NET or Windows Application [which is the best part of the .NET Framework].
[WebService(Namespace = "http://www.r2va.com/webservice/", Name = "BlogService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
The above three lines are generated by .NET. And by default NameSpace
will be "http://www.tempuri.org". You need to change that in a real world application. This is an optional part but this is for avoiding collision between various webservices. Say, if you and I have both created some webservice, and we both forgot to change the namespace
, then there might be chances of collision between our webservices. One more thing-ASP.NET WS do not validate namespace
but it is advisable to change the namespace
.
[WebMethod (Description = "Getting Data from server")]
public DataSet GetSettings()
{
Webmethod description is used to display the description of Method on ASMX page. To check this, run your webservice[asmx page]
in the browser using IIS or VS Webserver, You will see an ASMX webpage with your method name and its description below, provided in WebMethod(Description="")
.
The other parts are as usual, retrieving data from a be_settings
table and saving it to a dataset, and the dataset is returned.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
namespace BlogWService
{
public class BlogService : System.Web.Services.WebService
{
[WebMethod (Description = "Getting Data from server")]
public DataSet GetSettings()
{
// ConnectionString used for connecting SQL Server
string _ConnectionString = "Data Source=Secureserver.net;" +
"Initial Catalog=roa; User ID=roa; Password=214C;";
//SQL Connection created for establishing connection with SQL
//Server
SqlConnection _SQLConnection = new SqlConnection(_ConnectionString);
// getting all values from table
string _SQLQuery = "SELECT * from be_Settings";
// generating sql command and executing query
SqlCommand _SQLCommand = new SqlCommand(_SQLQuery, _SQLConnection);
// command type is text
_SQLCommand.CommandType = CommandType.Text;
_SQLConnection.Open(); // opening sql connection
// This is a data reader that navigates rows and columns
SqlDataReader _SQLDataReader = _SQLCommand.ExecuteReader();
// datatable for keep image of original table
DataTable _SQLDataTable = new DataTable("BlogTable");
// column is created as same as of original table
_SQLDataTable.Columns.Add("SettingName", typeof(string));
// -do-
_SQLDataTable.Columns.Add("SettingValue", typeof(string));
// navigate reader till end of recordset
while (_SQLDataReader.Read())
{
// add values into datatable
_SQLDataTable.Rows.Add(new object[] {
_SQLDataReader["SettingName"].ToString(),
_SQLDataReader["SettingValue"].ToString()});
}
_SQLDataTable.AcceptChanges(); // commit changes and terminate reader.
DataSet _SQLDataSet = new DataSet(); // a new dataset for pushing datatable
_SQLDataSet.Tables.Add(_SQLDataTable); // datatable pushed into dataset
_SQLDataSet.AcceptChanges(); //commit changes
return _SQLDataSet; // dataset passed for outer world application to use.
}
}
}
Windows Application [XMLWriter]
The code given below is easy and I think that there is no need to explain. I have commented it. Go through the code/comments, it's quite easy. For adding a reference of webService, Jump into your Solution Explorer, Select the project -> Right Click-> Add Webreference. Then a box will appear and there, put a valid path of your desired Web service. Click go. When the search will complete, you will see the name of the Web service. Then click add to add its reference.
For adding it into your namespace
, the format is [WinForm NameSpace.location of webservice in reverse order]
. Like , I have my webservice at www.r2va.com, and my namespace
is XMLReader
so it become using XMLReader.com.r2va.www
;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;using System.Windows.Forms;
using System.Data.SqlClient;
using XMLReader.com.r2va.www; // Webservice reference added
using System.Data.SqlClient;
namespace XMLReader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)// button click event
{
BlogService BService = new BlogService(); // object of blogservice
// Call the web service and get the results.
try
{
this.Cursor = Cursors.WaitCursor;
// saving webservice dataset to local daraset
DataSet ds = BService.GetSettings();
ds.WriteXML(Application.StartupPath + "post.xml", XmlWriteMode.DiffGram);
// writing dataset to XML file. Diffgram writes entire schema
// and content to file
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message); //showing exception in message box
}
this.Cursor = Cursors.Default;
}
}
}
Run the application and check the result. You will see a post.xml in your application executable directory. I had made some changes in this code, so if you use this code and try to run it... it will throw an exception. Please make the necessary changes before using this code.
History
- 13th June, 2008: Initial post