AngularJS - Using Web Service And Stored Procedure In ASP.NET

Introduction To AngularJS

AngularJS is an MVC based framework. Google developed AngularJS is an open source project which can be used freely, and can be modified and shared by others.

Top features Of AngularJS

  • Two Way Data-Binding
    This means that any changes to the Model update the View and any changes to the View update the Model.

  • Dependency Injection
    AngularJS has a built-in Dependency Injection that makes applications easier to develop, maintain, and debug, in addition to the test.

  • Testing
    Angular will test any of its code through both unit testing and end-to-end testing.

  • Model View Controller
    Split your application into MVC components. Maintaining these components and connecting them together means setting up Angular.

To build AngularJS Applications, you should download the script file, that is angular.js. To get the script file, visit https://angularjs.org. 

To know more about AngularJS, read my other articles and blogs.

Introduction To 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, 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, web services are often called as ASMX web services also. 

To know more about SOAP request and response, do visit the following 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.

  • Creating the Web Service
  • Creating a proxy
  • Consuming the Web Service

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 the calls to the web service as 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 stands for Simple Object Access Protocol. This protocol is 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 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 Visual Studio to create the proxy class. The client application calls the proxy class method. The proxy class then serializes the parameters, prepares a SOAP request message, and sends it to the web service. The web service executes the method and returns a SOAP response message to the proxy. The proxy class then de-serializes the SOAP response message and hands it to the client application. We don't have to serialize or de-serialize .NET CLR objects to and from SOAP format. The proxy class takes care of serialization and de-serialization, and makes the life of a developer much easier. 

Top 11 notes while writing code for Web Services

  • 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.

  • 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, use ASP.NET AJAX, then decorate the web service class with [System.Web.Script.Services.ScriptService] attribute.

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

  • BufferResponse is a boolean property with default value as 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. 

  • 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. 

  • 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.

  • 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.

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

  • 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.

  • 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

Step 1

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   

Step 2

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  

ASP.NET

Step 3

Create ASP.NET web form application named “AngularWs”.

ASP.NET

Step 4

Then, add the connection string in Web.Config file.

Code Ref 

  1. <?xml version="1.0"?>  
  2. <configuration>  
  3.   <connectionStrings>  
  4. <add name="MyDB" connectionString="Put Your Connection String Using Visual Studio Server Explorer"/>  
  5.   </connectionStrings>  
  6.   <system.web>  
  7.     <webServices>  
  8.       <protocols>  
  9.         <add name="HttpGet"/>  
  10.       </protocols>  
  11.     </webServices>  
  12.     <compilation debug="true"/>  
  13.   </system.web>  
  14. </configuration>   

Code Description

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

  1. <connectionStrings>  
  2. <add name="MyDB" connectionString="Put Your Connection String Using Visual Studio Server Explorer"/>  
  3. </connectionStrings>   

Create 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>  

ASP.NET

Step 5

Now, 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 AngularWs  
  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; }  

ASP.NET

Step 6

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

ASP.NET

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 AngularWs  
  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 used one strongly type List of objects using Employee.cs class to manipulate , search and sort the lists.

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

I 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 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 the 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 

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

ASP.NET

Step 7

Check if ASP.NET web service using Stored Procedure works or not. Right click on “EmployeeService.asmx”  and View In Browser.

ASP.NET

The below link is the Web Service URL.

http://localhost:52057/EmployeeService.asmx

Then, click on GetAllEmployees Link.

ASP.NET

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.

ASP.NET

Then, your URL path is changed.

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

You can see all the data in JSON format.

ASP.NET

Table's data 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}]   

It’s working fine ….

Step 8

Add a new folder to the project. Name it "Scripts". Download angular.js script file from http://angularjs.org, and paste it in Scripts folder.

ASP.NET

ASP.NET

Step 9

Add a new JavaScript file to the Scripts folder. Name it Script.js.

ASP.NET

Code Ref 

  1. var app = angular  
  2.        .module("myModule", [])  
  3.        .controller("myController"function ($scope, $http) {  
  4.   
  5.            $http.get("EmployeeService.asmx/GetAllEmployees")  
  6.                 .then(function (response) {  
  7.                     $scope.employees = response.data;  
  8.                 });  
  9.        });   

Code Description

Creating a module in Angular is straightforward. Use the Angular object's module() method to create a module. The Angular object is provided by Angular script. The following example creates module. 

  1. var app = angular  
  2. .module("myModule", [])   

The first parameter specifies the name of the module. The second parameter specifies the dependencies for this module.

A module can depend on other modules too. The module that we are creating is not dependent on any other external modules, so I am passing an empty array as the value for the second parameter.

  1. .module("myModule", [])   

To create a controller in AngularJS, create a JavaScript function and assign it to a variable using HttpGet.

  1. .controller("myController"function ($scope, $http)   

Use module object's Controller function to register the Controller with the module. Creating the Controller and registering with the module are all done in one line. 

Using HttpGet, I assigned web service link in web service web method attribute. 

  1. $http.get("EmployeeService.asmx/GetAllEmployees")  
  2.               .then(function (response) {  
  3.                   $scope.employees = response.data;  
  4.               });   

In the example below, Profile is a simple property to show the property's value through View.

  1. $scope.employees = response.data;  

ASP.NET

Step 10

Add a new stylesheet to the project. Name it Styles.css.

ASP.NET

Style Ref 

  1. body {  
  2.     font-family: Arial;  
  3. }  
  4.   
  5. table {  
  6.             font-family: arial, sans-serif;  
  7.             border-collapse: collapse;  
  8.             width: 100%;  
  9.       }  
  10.   
  11. td, th {  
  12.             border: 1px solid #dddddd;  
  13.             text-align: left;  
  14.             padding: 8px;  
  15.        }  
  16.   
  17. tr:nth-child(even) {  
  18.             background-color: #dddddd;  
  19.         }  
  20. Style Description:  
  21. For apply style to table structure and table header data Then table row data.  
  22. table {  
  23.             font-family: arial, sans-serif;  
  24.             border-collapse: collapse;  
  25.             width: 100%;  
  26.       }  
  27.   
  28. td, th {  
  29.             border: 1px solid #dddddd;  
  30.             text-align: left;  
  31.             padding: 8px;  
  32.        }  
  33.   
  34. tr:nth-child(even) {  
  35.             background-color: #dddddd;  
  36.         }  
  37.   
  38. For apply style to body of this application.  
  39. body {  
  40.     font-family: Arial;  
  41. }  

ASP.NET

Step 11

To check for Web Service related reference file, go to Reference folder and then check for “System.Web.Services.dll”.


ASP.NET

Step 12

Add an HTML page to the ASP.NET project named “MyWebAngular.html”.

Code Ref 

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title>Satyaprakash Webservice In AngularJs</title>  
  5.     <meta http-equiv="refresh" content="40">  
  6.     <script src="Scripts/angular.js"></script>  
  7.     <script src="Scripts/Script.js"></script>  
  8.     <link href="Styles.css" rel="stylesheet" />  
  9. </head>  
  10. <body ng-app="myModule">  
  11.     <marquee behavior="alternate" bgcolor=Orange><font color="white" size="40">Records will refresh every 40 Sec!</font></marquee>  
  12.     <div ng-controller="myController">  
  13.         <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYAPRAKASH's WEB SERVICE USING ANGULARJS</h2>  
  14.         <fieldset>  
  15.             <legend style="font-family:Arial Black;color:orangered">ANGULARJS WEB SERVICE EMPLOYEE DETAILS</legend>  
  16.             <table align="center" border="1" cellpadding="4" cellspacing="4">  
  17.                 <thead>  
  18.                     <tr>  
  19.                         <th style="background-color: Yellow;color: blue">Employee Id</th>  
  20.                         <th style="background-color: Yellow;color: blue">Employee Name</th>  
  21.                         <th style="background-color: Yellow;color: blue">Employee Gender</th>  
  22.                         <th style="background-color: Yellow;color: blue">Employee Salary</th>  
  23.                     </tr>  
  24.                 </thead>  
  25.                 <tbody>  
  26.                     <tr ng-repeat="employee in employees">  
  27.                         <td>{{employee.id}}</td>  
  28.                         <td>{{employee.name}}</td>  
  29.                         <td>{{employee.gender}}</td>  
  30.                         <td>{{employee.salary}}</td>  
  31.                     </tr>  
  32.                 </tbody>  
  33.             </table>  
  34.       </fieldset>  
  35. </div>  
  36.     <footer>  
  37.         <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>  
  38.     </footer>  
  39. </body>  
  40. </html>   

Code Description

Here, I have added text for title of the browser.

  1. <title>Satyaprakash Webservice In AngularJs</title>   

To refresh the page to get latest data, if any update is there in the backend. 

  1. <meta http-equiv="refresh" content="40">   

Mention the path of AngularJS, JavaScript files, and CSS stylesheet and apply its properties in design as well as functionality part of this application. 

  1. <script src="Scripts/angular.js"></script>  
  2. <script src="Scripts/Script.js"></script>  
  3. <link href="Styles.css" rel="stylesheet"/>   

Here, I have added Controller related information. In this script file, the Controller is not manipulating the document object model directly, thus keeping that clean separation between the Model, View and the Controller. The Controller should only be used for setting up the $scope object and adding behavior in it.

Here, I have added “ng-controller” directive name i.e. “myController” in Div tag and main directive or parent directive “ng-app” directive name i.e. “myModule” in body tag. Because of this “ng-app” directive, we can access “ng-controller” directive. Both directives are mentioned in “Script.Js” file.  

  1. <body ng-app="myModule">  
  2.     <marquee behavior="alternate" bgcolor=Orange><font color="white" size="40">Records will refresh every 40 Sec!</font></marquee>  
  3.     <div ng-controller="myController">   

I have added Marquee tag to show the time after which the page will refresh.

  1. <marquee behavior="alternate" bgcolor=Orange><font color="white" size="40">Records will refresh every 40 Sec!</font></marquee>   

Then, I have added for Header Text formalities. 

  1. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYAPRAKASH's WEB SERVICE USING ANGULARJS</h2>  
  2.   
  3. <fieldset>  
  4.   
  5. <legend style="font-family:Arial Black;color:orangered">ANGULARJS WEB SERVICE EMPLOYEE DETAILS</legend>  
  6.   
  7. </fieldset>   

Then, I have added for Footer Text formalities.

  1. <footer>  
  2.         <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>  
  3. </footer>   

Then, added table header and design style.

  1. <table align="center" border="1" cellpadding="4" cellspacing="4">  
  2.                 <thead>  
  3.                     <tr>  
  4.                         <th style="background-color: Yellow;color: blue">Employee Id</th>  
  5.                         <th style="background-color: Yellow;color: blue">Employee Name</th>  
  6.                         <th style="background-color: Yellow;color: blue">Employee Gender</th>  
  7.                         <th style="background-color: Yellow;color: blue">Employee Salary</th>  
  8.                     </tr>  
  9.                 </thead>   

ng-repeat is similar to foreach loop in C#. 

For each employee we have, we want a table row. Within each cell of the table row, we want to display employee,

  1. Employee Id
  2. Employee Name
  3. Employee Gender
  4. Employee Salary

This can be achieved very easily using ng-repeat directive.

In Script.JS, the Controller function builds the Model for the View. The Model employee has the list of all employees.

In the View, we are using ng-repeat directive which loops through each employee in employees array. For each employee, we get a table row, and in each table cell of the table row, the respective employee details (Employee Id, Employee Name, Employee Gender, Employee Salary) are retrieved using the Angular binding expression. 

  1. <tr ng-repeat="employee in employees">  
  2.                         <td>{{employee.id}}</td>  
  3.                         <td>{{employee.name}}</td>  
  4.                         <td>{{employee.gender}}</td>  
  5.                         <td>{{employee.salary}}</td>  
  6. </tr>  

ASP.NET

ASP.NET

OUTPUT

The URL path of the application.

http://localhost:52057/MyWebAngular.html

ASP.NET

Already there are 11 records in it. Now, we have inserted 2 more records.

  1. Insert into tblEmployees values ('Satya11''Female', 60000)  
  2. Insert into tblEmployees values ('Satya12''Male', 60000)  
  3.   
  4. select * from tblEmployees  

ASP.NET

Then, the page will refresh after 40 seconds to show these two extra recently inserted data rows using back-end.

ASP.NET

Now, let's delete one record. It will show total 12 records after 40 seconds of refreshing the web page.

select * from tblEmployees

delete from tblEmployees where id=8

ASP.NET

Here, the employee data with id=8 is not available.

ASP.NET

The Marquee tag for showing time table to refresh records.

ASP.NET

The Footer of the web page showing today’s date.

ASP.NET

Important Notes

This web service retrieves the data from SQL Server database table, and returns it in JSON format. Call the web service using AngularJS and display employee data on the web page.

Summary

We learned the following in this article. 

  1. What Web Services are.
  2. How to use Stored Procedure In Web Services.
  3. How to connect AngularJS with Web Service.
  4. How to put AngularJS directives in HTML file In ASP.NET.


Similar Articles