Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / C#
Article

Consuming Webservice In A Windows Application

Rate me:
Please Sign up or sign in to vote.
3.57/5 (15 votes)
13 Jun 2008CPOL3 min read 153.5K   5.5K   48   10
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].

ASP.NET
[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.

ASP.NET
[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.

C#
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;

C#
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

License

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


Written By
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

Comments and Discussions

 
QuestionMy vote 5 Pin
AnandIndore1-Jun-15 5:09
AnandIndore1-Jun-15 5:09 
QuestionGetting Error in namespace " using XMLReader.com.r2va.www; " Pin
Member 1158399121-Apr-15 22:41
Member 1158399121-Apr-15 22:41 
QuestionConsuming WebService via HTTPS. Pin
nitin_ambupe3-Sep-14 16:45
nitin_ambupe3-Sep-14 16:45 
Questionnot good, hgvhghgh Pin
preeti@1236-Sep-12 23:24
preeti@1236-Sep-12 23:24 
AnswerRe: not good, hgvhghgh Pin
Eddy Vluggen6-Sep-12 23:50
professionalEddy Vluggen6-Sep-12 23:50 
GeneralRe: not good, hgvhghgh Pin
Amit Ranjan1-Oct-12 3:36
Amit Ranjan1-Oct-12 3:36 
GeneralMy vote of 5 Pin
Abhilash Hari20-Mar-12 4:00
Abhilash Hari20-Mar-12 4:00 
GeneralRe: My vote of 5 Pin
Amit Ranjan11-Apr-12 10:34
Amit Ranjan11-Apr-12 10:34 
GeneralMy vote of 3 Pin
shukla dhaval10-Aug-10 2:55
shukla dhaval10-Aug-10 2:55 
GeneralError while adding webreference Pin
kazim bhai24-Feb-09 3:19
kazim bhai24-Feb-09 3:19 
I have made a web service the way you explained in article and put on my web page as dll but when I go to add web reference I browse to the location but hsi error comes in

Error
The HTML document does not contain Web service discovery information.

I have put in my webservices folder


Service1.asmx
web.config
Webservice1.dll


Please help if I need to add some thing else

It is Kazim

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.