Click here to Skip to main content
Click here to Skip to main content

Single web service for .NET web and desktop applications (basic concept)

By , 21 May 2013
 

Background

Sometimes we want to use a single database for the web and desktop versions of an application. In those cases we need to work with the same task, same interface, class, method in the web version and desktop version. In those cases we may need to use the same method in the web and desktop.

Again sometimes we need to work partially in web and partially in desktop. In those cases we may need to use the same method in the web and desktop.

For example: An application for food industry, more exactly a software to manage Delivery, Take Way, Table Reservation, POS, Accounts Payable and Receivable, Prints (receipt), Kitchen Monitors Orders, Customers Orders Control and Fiscal Area. In that case normally clients demand something like this:

1 - Web Area (basically does the following):

  • Show Catalog with the products
  • Customers Make Orders
  • Customers Pay for the Orders
  • etc ... as mentioned above

2 - Desktop Area

  • Manage Orders
  • Manage Customers
  • Manage Suppliers
  • Manage Accounts Payable and Receivable
  • etc ... as mentioned above

In the above web and desktop part we may need to use the same method in the web and desktop. In those cases we can use the Web Service to make it more reusable. But a web service has a different task. First I am discussing here about the Web Service.

  • What is Web Service?
  • Components of Web Service?
  • Why we need Web Service?
  • How it works ?
  • How Web Service works in .net web application and desktop application?

What is Web Service?

Web service is a technology framework which allows machine-to-machine (M2M) interaction over the network. It can call an application component. This protocol communicates with XML. It is not tied to any one operating system or programming language.

Components of Web Service

The basic Web services platform is XML + HTTP. All standard Web Services work using the following components:

  1. SOAP (Simple Object Access Protocol)
  2. UDDI (Universal Description, Discovery and Integration)
  3. WSDL (Web Services Description Language)

Learn more SOAP, UDDI, WSDL.

Why we need Web Service?

The main reason for popularity of web services is because with a web service, any application made with PHP, C++, VB, or C# etc. must adhere to a set of standardized protocols for sharing and accessing data. This way, two programs can speak to each other regardless of the operating system, database, or programming language compatibility. Everyone agrees on a set of rules by which these interactions will take place. This distinct feature is called Service-Oriented Architecture (SOA).

How Web Service works

  • The client program bundles the client page information into a SOAP message.
  • This SOAP message is sent to the Web Service as the body of an HTTP POST request.
  • The Web Service unpacks the SOAP request and converts it into a command that the application can understand. The application processes the information as required and responds with new unique data.
  • Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
  • The client program unpacks the SOAP message to obtain the results of the client page and the required process.

Web Services has two types of users:

  1. Reusable application-components
  2. Connect existing software

How I use the Web Service in a .NET web application and desktop application

First the user application and web service middle ware makes a SOAP message and communicates over HTTP. We can say that SOAP is a message format for sending messages between applications using XML. It is independent of technology, platform, and is extensible also.

About the code

Database: Create a database named TESTDB in sa mode with password sqladmin, then run the given script. In the solution create two projects, one for web and another for desktop.

Create a Web Service : Create method to get data from the database.

[WebMethod]
public DataSet GetSampleDataDT()
{
    // getting connection string
    string conStr = WebConfigurationManager.ConnectionStrings["CONN"].ConnectionString;

    DataTable dt = new DataTable();
    SqlDataReader dr = null;
    using (SqlConnection conn = new SqlConnection(conStr))
    {
        // Creating insert statement
        string sql = string.Format(@"select id,name,value1 from Table_1");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = sql;
        cmd.CommandType = CommandType.Text;
        conn.Open();

        dr = cmd.ExecuteReader();
        dt.Load(dr);

        conn.Close();
        cmd = null;

    }
    DataSet dsReturn = new DataSet();
    dsReturn.Tables.Add(dt);
    return dsReturn;
}  

In the above method I just use a normal query to get data from the database. Again create a method for inserting data in the database.

[WebMethod]
public void WB_HR_InsertMethod(int id, string name, int salary)
{
    // getting connection string
    string conStr = WebConfigurationManager.ConnectionStrings["CONN"].ConnectionString;
    int rowsInserted = 0;
    // Creating Sql Connection
    using (SqlConnection conn = new SqlConnection(conStr))
    {
        // Creating insert statement
        string sql = string.Format(@"INSERT INTO [TESTDB].[dbo].[Table_1]([id]," + 
          @"[name],[value1])VALUES('"+id+"','"+name+"','"+salary+"')");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = sql;
        cmd.CommandType = CommandType.Text;
        conn.Open();
        rowsInserted = cmd.ExecuteNonQuery();
        conn.Close();
        cmd = null;
    }
}

In the ASP.NET code behind create a method to insert and get data through the webservice and store in the DataGridView.

protected void btnSave_Click(object sender, EventArgs e)
{
    WebService1 objWebService = new WebService1();
    DataSet dtData = new DataSet();

   objWebService.WB_HR_InsertMethod(Convert.ToInt32(txtId.Text.ToString()), 
     txtName.Text.ToString(), Convert.ToInt32(txtSalary.Text.ToString()));
   dtData = objWebService.GetSampleDataDT();
   dgv_show.DataSource = dtData;
   dgv_show.DataBind();
}  

The output will be like this :

Add WebService in Desktop Application:

Go to References > Add Service Reference.

Now add an OK button. The webserver will be included.

Add a new form. Add a new method in the code-behind of form1.

protected void btnSave_Click(object sender, EventArgs e)
{
    WebService1 objWebService = new WebService1();
    DataSet dtData = new DataSet();

   objWebService.WB_HR_InsertMethod(Convert.ToInt32(txtId.Text.ToString()), 
     txtName.Text.ToString(), Convert.ToInt32(txtSalary.Text.ToString()));
   dtData = objWebService.GetSampleDataDT();
   dgv_show.DataSource = dtData;
   dgv_show.DataBind();
}

And also create a Show method to get data from the webservice:

private void Show()
{  
    WebService1SoapClient objWebService = new WebService1SoapClient();
    DataSet dsReturn = new DataSet();
    dsReturn = objWebService.GetSampleDataDT();
    DataTable dt = new DataTable();
    dt=dsReturn.Tables[0];
    dataGridView1.DataSource = dt;
} 

The same output will show in the desktop application:

The same database is used for web and desktop applications.

History

  • 20-November-2012: Version 1.

License

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

About the Author

Md. Humayun Rashed
Software Developer (Senior) Desme-Bangladesh
Bangladesh Bangladesh
Member
I am working in Desme-Bangladesh as Senior Software Engineer. I am expert in ASP.NET,C#.NET, EXT.NET, SQL 2005, Oracle 10g. I always love to solve the problem.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSingle web service for web/desktop client is there by defaultmemberHaBiX21 May '13 - 21:41 
You don't have to do anything to use the same generated client on desktop or web.... or windows service of wpf or anywhere.
 
The article is pointless or the title should be changed to something like "Hello world in WCF"
 
p.s. use svcutil, else you ask of readers to use visual studio (i'm sure 90% are using it, but what about others?)
GeneralNote [modified]memberMax Planck20 Nov '12 - 6:51 
It seems to me that nowadys it is most common to use REST web services in such cases.

modified 20 Nov '12 - 14:59.

GeneralRe: NotememberSteven.M.Hunt20 Nov '12 - 8:45 
I agree; a lot of people are using JSON with REST so that you can have your data load directly on the client-side through AJAX. SOAP is on its way out.
-- Steven

SuggestionSuggestionsmemberVasudevan Deepak Kumar20 Nov '12 - 4:09 
1) Do not recommend inline queries which sends a wrong message to beginner-readers.
2) Do not recommend Visual Studio dependant tools for proxy generation Rather try suggesting the SDK-provided commandline options like svcutil.
Vasudevan Deepak Kumar
Personal Homepage
Tech Gossips


The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep!




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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 21 May 2013
Article Copyright 2012 by Md. Humayun Rashed
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid