Click here to Skip to main content
13,142,013 members (65,418 online)
Click here to Skip to main content
Add your own
alternative version


46 bookmarked
Posted 13 Jun 2008

Consuming Webservice In A Windows Application

, 13 Jun 2008
Rate this:
Please Sign up or sign in to vote.
This article describes how to create and use a webservice in a Windows application in C#


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.


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 = "", Name = "BlogService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

The above three lines are generated by .NET. And by default NameSpace will be "". 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;" +
                "Initial Catalog=roa; User ID=roa; Password=214C;"; 
            //SQL Connection created for establishing connection with SQL 
            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[] {
            _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, and my namespace is XMLReader so it become using;

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; // Webservice reference added
using System.Data.SqlClient;
namespace XMLReader
    public partial class Form1 : Form
        public Form1()
        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.
               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.


  • 13th June, 2008: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Amit Ranjan
Web Developer MFSI
India India
Holds MSc Information Science from BIT Mesra. Area of interest is C# and VB.Net. He loves C# and is involved in Web and Windows Development.

Area of expertise is ASP.Net, C#, AJAX, Java/Vb Script, Sql, XHTML, CSS, UI Design.

In leisure he loves hanging out with friends and pranking on them too

You may also be interested in...


Comments and Discussions

QuestionMy vote 5 Pin
AnandIndore1-Jun-15 5:09
memberAnandIndore1-Jun-15 5:09 
QuestionGetting Error in namespace " using; " Pin
Member 1158399121-Apr-15 22:41
memberMember 1158399121-Apr-15 22:41 
QuestionConsuming WebService via HTTPS. Pin
nitin_ambupe3-Sep-14 16:45
membernitin_ambupe3-Sep-14 16:45 
Questionnot good, hgvhghgh Pin
preeti@1236-Sep-12 23:24
memberpreeti@1236-Sep-12 23:24 
AnswerRe: not good, hgvhghgh Pin
Eddy Vluggen6-Sep-12 23:50
memberEddy Vluggen6-Sep-12 23:50 
GeneralRe: not good, hgvhghgh Pin
Amit Ranjan1-Oct-12 3:36
memberAmit Ranjan1-Oct-12 3:36 
GeneralMy vote of 5 Pin
abhilashelw20-Mar-12 4:00
memberabhilashelw20-Mar-12 4:00 
GeneralRe: My vote of 5 Pin
Amit Ranjan11-Apr-12 10:34
memberAmit Ranjan11-Apr-12 10:34 
GeneralMy vote of 3 Pin
shukla dhaval10-Aug-10 2:55
membershukla dhaval10-Aug-10 2:55 
GeneralError while adding webreference Pin
kazim bhai24-Feb-09 3:19
memberkazim bhai24-Feb-09 3:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 13 Jun 2008
Article Copyright 2008 by Amit Ranjan
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid