Click here to Skip to main content
15,881,172 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.74/5 (11 votes)
21 May 2013CPOL4 min read 86K   2.9K   43   5
Single web service for both .NET web and desktop applications.

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.

Image 1

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.

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

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

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

Image 2

Add WebService in Desktop Application:

Go to References > Add Service Reference.

Image 3

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

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

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

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

Image 4

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)



Comments and Discussions

 
QuestionUsing the VB instead of C# for web service Pin
Member 1185102221-Jul-15 14:51
Member 1185102221-Jul-15 14:51 
QuestionSingle web service for web/desktop client is there by default Pin
HaBiX21-May-13 21:41
HaBiX21-May-13 21:41 
GeneralNote Pin
Max Planck20-Nov-12 6:51
Max Planck20-Nov-12 6:51 
GeneralRe: Note Pin
Steven M Hunt20-Nov-12 8:45
Steven M Hunt20-Nov-12 8:45 
SuggestionSuggestions PinPopular
Vasudevan Deepak Kumar20-Nov-12 4:09
Vasudevan Deepak Kumar20-Nov-12 4:09 

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.