Click here to Skip to main content
5,788,961 members and growing! (19,878 online)
Email Password   helpLost your password?
Languages » C# » Applications     Beginner License: The Code Project Open License (CPOL)

Consuming Webservice In A Windows Application

By Amit Ranjan

This article describes how to create and use a webservice in a Windows application in C#
C#, Windows, Dev

Posted: 13 Jun 2008
Updated: 13 Jun 2008
Views: 4,865
Bookmarked: 13 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
4 votes for this Article.
Popularity: 1.51 Rating: 2.50 out of 5
2 votes, 50.0%
1
0 votes, 0.0%
2
1 vote, 25.0%
3
0 votes, 0.0%
4
1 vote, 25.0%
5

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

License

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

About the Author

Amit Ranjan


Amit Ranjan is in programming, from his senior secondary days. He First interacted with computers in mid 1994, when he was in class VII. It was a great time for him and his frends. They used to play Chess and PacMan, rather than studying computers. He started programming from his senior secondary 1998-2000 with C and C++ programs (Oh!!! that were too tough days). Then completed BCA from IGNOU and MSc from BIT Mesra. Currently his area of interest C# (of course). He loves C# and is involved in Web and Windows Development. Presently he is working with NathCorp Inc.
Occupation: Software Developer
Company: NathCorp
Location: India India

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
  (Refresh) 
-- There are no messages in this forum --

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Jun 2008
Editor: Deeksha Shenoy
Copyright 2008 by Amit Ranjan
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project