Generate JSON Data Using Web Service And SQL Server Stored Procedure

Let’s know about Web Service

Web Services are used for enabling an application to invoke a method of another application. These applications can be on the same computer or different computers. Web Services use protocols like HTTP, XML, and SOAP. Since these are open and well known protocols, the applications built on any platform can interoperate with Web Services. For example, a PHP application can interoperate with a Web Service built using .NET. Similarly, a web service built using different platform can be consumed by a .NET application.

Hyper Text Transfer Protocol (HTTP) is the protocol widely used by web services to send and receive messages. The messaging protocol is SOAP (Simple Object Access Protocol). SOAP messages are in XML format. Web Services have .asmx extension. For this reason, the web services are also often called as ASMX web services. 

To know more about SOAP request and response, visit the below reference site.

https://www.w3.org/2003/06/soap11-soap12.html

A web service is a web-based functionality accessed using the protocols of the web to be used by the web applications. There are three aspects of web service development,

  1. Creating the web service
  2. Creating a proxy
  3. Consuming the web service

Introduction to proxy in ASP.NET Web Service

A proxy is a major part for the web service codes. Before using the web service, a proxy must be created. The proxy is registered with the client application. Then, the client application makes call to the web service as if it were using a local method. The proxy takes the calls, wraps it in proper format, and sends it as a SOAP request to the Server. SOAP protocol is then used for exchanging web service data.

When the Server returns the SOAP package to the client, the proxy decodes everything and presents it to the client application.

Relationship between Visual Studio and Proxy

Visual Studio generates a proxy class using the Web Service Description Language (WSDL) document of the web service. The Web Service Description Language document formally defines a web service. It includes, 

  • All the methods that are exposed by the web service
  • The parameters and their types
  • The return types of the methods
This information is then used by VS to create the proxy class. The client application calls the proxy class method. The proxy class will then serialize the parameters, prepare a SOAP request message, and send it to the web service. The web service executes the method and returns a SOAP response message to the proxy. The proxy class will then deserialize the SOAP response message and hands it to the client application. We don't have to serialize or deserialize .NET CLR objects to and from SOAP format. The proxy class takes care of serialization and deserialization and makes the life of a developer much easier. 

Top Important Notes While Write Code For Web Services:

  1. To use asp.net session object in a web service, the web service class must inherit from System.Web.Services.WebService class and EnableSession property of WebMethod attribute must be set to true. Hyper Text Transfer Protocol (HTTP) is the protocol widely used by web services to send and receive messages .The messaging protocol is SOAP. SOAP stands for Simple Object Access Protocol. SOAP messages are in XML format.

  2. Notice that a web service is a class that is decorated with [WebService] attribute and inherits from System.Web.Services.WebService base class. The [WebService] attribute tells that this class contains the code for a web service. Web Service Namespace is used to uniquely identify your web service on the internet from other services that are already there on the Web. Web Service Namespace can be any string, but it is common to give it a company's internet domain name as they are usually unique.

    To allow a web service to be called from Javascript , using ASP.NET AJAX, then decorate the web service class with [System.Web.Script.Services.ScriptService] attribute.

  3. Web Method attribute used to specify description for the web service method.

  4. BufferResponse is a boolean property. Default is true. When this property is true, the response of the XML Web service method is not returned to the client until either the response is completely serialized or the buffer is full. On the other hand, when this property is false, the response of the XML Web service method is returned to the client as it is being serialized.

    In general, set BufferResponse to false, only when the XML Web service method returns large amounts of data. 

  5. CacheDuration is the property, if you want to cache the results of a web service method. This is an integer property, and specifies the number of seconds that the response should be cached. The response is cached for each unique parameter. 

  6. Web Methods in a web service can also be overloaded based on the number of parameters. Method overloading possible in web services by using MessageName property of WebMethod attribute. MessageName property is used to uniquely identify the individual XML Web service methods.

  7. Call the web service using ASP.NET AJAX, which allows partial page post back. With partial page post back, only specific portion of the page is updated without reloading the entire page.

  8. For smaller amounts of data, web service performance is better when BufferResponse is set to true.

  9. In Web.Config file When allowCookies attribute is set to true, the client application accepts the cookie returned from the ASMX web service, and copies it into all future requests that are made to the web service. This ensures that the same session is maintained between the client and the web service.

  10. To use asp.net session object in a web service, the web service class must inherit from System.Web.Services.WebService class and EnableSession property of WebMethod attribute must be set to true.

Steps to Create a Simple Application To Understand Better

Step1

Create one table named “tblEmployees”.

Script 

  1. Create table tblEmployees  
  2. (  
  3.     Id int primary key identity,  
  4.     Name nvarchar(50),  
  5.     Gender nvarchar(10),  
  6.     Salary int  
  7. )  
  8. Go   

Enter some Dummy Records into this table.

Script 

  1. Insert into tblEmployees values ('Satya1''Male', 55000)  
  2. Insert into tblEmployees values ('Satya2''Female', 68000)  
  3. Insert into tblEmployees values ('Satya3''Male', 57000)  
  4. Insert into tblEmployees values ('Satya4''Female', 53000)  
  5. Insert into tblEmployees values ('Satya5''Male', 60000)  
  6. Insert into tblEmployees values ('Satya6''Male', 60000)  
  7. Insert into tblEmployees values ('Satya7''Male', 60000)  
  8. Go   

Step2

Create one Stored Procedure named “AngularDB”.

Script 

  1. Create Procedure AngularDB  
  2. As  
  3. Begin  
  4. select * from tblEmployees  
  5. End   

Then, execute this Stored Procedure to check the records.

  1. exec AngularDB  

SQL Server

Step3

Then, create an  ASP.NET application named “WebService”.

Step4

Then, add connection string in Web.Config file.

Code Ref 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!--  
  3.   For more information on how to configure your ASP.NET application, please visit  
  4.   http://go.microsoft.com/fwlink/?LinkId=169433  
  5.   -->   
  1. <configuration>  
  2.   <connectionStrings>  
  3.     <add name="MyDB" providerName="System.Data.SqlClient" connectionString="Add Your Connection string here"/>  
  4. </connectionStrings>  
  5.   <system.web>  
  6.     <webServices>  
  7.       <protocols>  
  8.         <add name="HttpGet"/>  
  9.       </protocols>  
  10.     </webServices>      
  11.     <compilation debug="true" targetFramework="4.0" />  
  12.   </system.web>  
  13. </configuration>   

Code Description

Here, I have mentioned the name of the connection string as “MyDB”. 

  1. <connectionStrings>  
  2.     <add name="MyDB" providerName="System.Data.SqlClient" connectionString="Add Your Connection string here"/>  
  3.   </connectionStrings>  

Created ASMX web service that can perform a HTTP GET request. 

  1. <webServices>  
  2.       <protocols>  
  3.         <add name="HttpGet"/>  
  4.       </protocols>  
  5. </webServices>   

Enable an ASP.NET Web Service for HTTP POST and GET requests. 

  1. <system.web>  
  2.   <webServices>  
  3.     <protocols>  
  4.       <add name="HttpGet"/>  
  5.       <add name="HttpPost"/>  
  6.     </protocols>  
  7.   </webServices>  
  8. </system.web>   

Step5

Then, create a class file named “Employee.cs”.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace WebService  
  7. {  
  8.     public class Employee  
  9.     {  
  10.         public int id { get; set; }  
  11.         public string name { get; set; }  
  12.         public string gender { get; set; }  
  13.         public int salary { get; set; }  
  14.     }  
  15. }   

Code Description

I have declared 4 entities using get and set properties inside Employee class.These 4 entities should be same as Columns inside the earlier mentioned table “tblEmployees”. 

  1. public int id { get; set; }  
  2. public string name { get; set; }  
  3. public string gender { get; set; }  
  4. public int salary { get; set; }  

SQL Server

Step6

Add a new Web Service i.e. ASMX file . Name it as EmployeeService.asmx.

SQL Server

Code Ref -

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. using System.Web.Script.Serialization;  
  6. using System.Web.Services;  
  7.   
  8. namespace WebService  
  9. {  
  10.     [WebService(Namespace = "http://tempuri.org/")]  
  11.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  12.     [System.ComponentModel.ToolboxItem(false)]  
  13.     [System.Web.Script.Services.ScriptService]  
  14.     public class EmployeeService : System.Web.Services.WebService  
  15.     {  
  16.         [WebMethod]  
  17.         public void GetAllEmployees()  
  18.         {  
  19.             List<Employee> listEmployees = new List<Employee>();  
  20.   
  21.             string cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;  
  22.             using (SqlConnection con = new SqlConnection(cs))  
  23.             {  
  24.                 SqlCommand cmd = new SqlCommand();  
  25.                 cmd.Connection = con;  
  26.                 cmd.CommandType = System.Data.CommandType.StoredProcedure;  
  27.                 cmd.CommandText = "AngularDB";  
  28.                 con.Open();  
  29.                 SqlDataReader rdr = cmd.ExecuteReader();  
  30.                 while (rdr.Read())  
  31.                 {  
  32.                     Employee employee = new Employee();  
  33.                     employee.id = Convert.ToInt32(rdr["Id"]);  
  34.                     employee.name = rdr["Name"].ToString();  
  35.                     employee.gender = rdr["Gender"].ToString();  
  36.                     employee.salary = Convert.ToInt32(rdr["Salary"]);  
  37.                     listEmployees.Add(employee);  
  38.                 }  
  39.             }  
  40.   
  41.             JavaScriptSerializer js = new JavaScriptSerializer();  
  42.             Context.Response.Write(js.Serialize(listEmployees));  
  43.         }  
  44.     }  
  45. }   

Code Description

This namespace is very much required for this web service related code. 

  1. using System.Web.Services;   

I have created one web method named “GetAllEmployees()”. 

  1. public void GetAllEmployees()   

I have used one strongly typed List of objects using Employee.cs class to manipulate , search and sort the lists. 

  1. List<Employee> listEmployees = new List<Employee>();   

I have used my connection string name here. 

  1. string cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;   

Then, all ADO.NET objects and properties are mentioned with their vast roles like SqlConnection , SqlCommand , SqlDataReader etc. 

  1. string cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;  
  2.             using (SqlConnection con = new SqlConnection(cs))  
  3.             {  
  4.                 SqlCommand cmd = new SqlCommand();  
  5.                 cmd.Connection = con;  
  6.                 cmd.CommandType = System.Data.CommandType.StoredProcedure;  
  7.                 cmd.CommandText = "AngularDB";  
  8.                 con.Open();  
  9.                 SqlDataReader rdr = cmd.ExecuteReader();  
  10.                 while (rdr.Read())  
  11.                 {  
  12.                     Employee employee = new Employee();  
  13.                     employee.id = Convert.ToInt32(rdr["Id"]);  
  14.                     employee.name = rdr["Name"].ToString();  
  15.                     employee.gender = rdr["Gender"].ToString();  
  16.                     employee.salary = Convert.ToInt32(rdr["Salary"]);  
  17.                     listEmployees.Add(employee);  
  18.                 }  
  19.             }   

I have put my Stored Procedure “AngularDB” here. 

  1. cmd.CommandType = System.Data.CommandType.StoredProcedure;  
  2. cmd.CommandText = "AngularDB";   

Mention all the fields using object of Employee class. 

  1. Employee employee = new Employee();  
  2. employee.id = Convert.ToInt32(rdr["Id"]);  
  3. employee.name = rdr["Name"].ToString();  
  4. employee.gender = rdr["Gender"].ToString();  
  5. employee.salary = Convert.ToInt32(rdr["Salary"]);   

Then, add all field values of Employee object “employee” to List class object “listEmployees”. 

  1. listEmployees.Add(employee);   

Provide the serialization and deserialization functionality of AJAX-enabled application. 

  1. JavaScriptSerializer js = new JavaScriptSerializer();   

Then, convert the listEmployees object values into JSON string. 

  1. Context.Response.Write(js.Serialize(listEmployees));   

WebService Namespace can be any string, but it is common to give it a company's internet domain name as they are usually unique. Something like 

  1. [WebService(Namespace = "http://tempuri.org/")]   

If you want the method exposed as part of the Web service, then the method must be public and should be decorated with [WebMethod] attribute. This attribute has got several properties which can be used to configure the behavior of the XML Web service method.

SQL Server

Step7

Check for Asp.Net web service Using Stored Procedure Works ?

Right Click On “EmployeeService.asmx” , Then View In Browser.

SQL Server

The below link is the Web Service URL :

http://localhost:52057/EmployeeService.asmx

Then Click On GetAllEmployees Link.

SQL Server

Then, to test the data whatever inserted in the above mentioned table, click on "Invoke" button.

Also, to test the operation using the HTTP POST protocol, click the 'Invoke' button.

SQL Server

Then your URL path is changed.

http://localhost:52057/EmployeeService.asmx/GetAllEmployees

TABLE’S DATAS IN JSON FORMAT 

  1. [{"id":1,"name":"Satya1","gender":"Male","salary":55000},{"id":2,"name":"Satya2","gender":"Female","salary":68000},{"id":3,"name":"Satya3","gender":"Male","salary":57000},{"id":4,"name":"Satya4","gender":"Female","salary":53000},{"id":5,"name":"Satya5","gender":"Male","salary":60000},{"id":6,"name":"Satya6","gender":"Male","salary":60000},{"id":7,"name":"Satya7","gender":"Male","salary":60000},{"id":8,"name":"Satya8","gender":"Male","salary":60000},{"id":9,"name":"Satya8","gender":"Male","salary":60000},{"id":10,"name":"Satya9","gender":"Female","salary":60000},{"id":11,"name":"Satya10","gender":"Male","salary":60000}]   

OUTPUT

You can see all data in JSON format.

SQL Server

Important Notes

This web service retrieves the data from SQL Server database table, and returns it in JSON format.

Up Next
    Ebook Download
    View all
    Learn
    View all