Monday, 14 November 2016

Creating Custom service for manipulating string in Angular

Service
It is simply means an object that perform some task.

Use of Service
contains reusable code that can be used at multiple places in a project just by referencing it.

Let's see with an example:

Step 1: This is going to be the structure.Include angular.js or angular.min.js file. The file circled are going to be used


Step 2: Create UsingCustomService.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="AngularModule">
<head>
    <title></title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/UsingCustomService.js"></script>
    <script src="Service/StringManipulationService.js"></script>
</head>
<body ng-controller="AngularController">
    <table border="1">
        <tr>
            <td>Enter Text :</td>
            <td><input type="text" ng-model="InputText"/></td>
        </tr>
        <tr>
            <td>Text in UpperCase :</td>
            <td><input type="text" ng-model="OutputUpper"/></td>
        </tr>
        <tr>
            <td>Text in LowerCase :</td>
            <td><input type="text" ng-model="OutputLower" /></td>
        </tr>
        <tr>
            <td>Text Length :</td>
            <td><input type="text" ng-model="OutputLength" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" value="Manipulate String" ng-click="ManipulateString(InputText)" /></td>
        </tr>
    </table>
</body>
</html>

Step 3: Create UsingCustomService.js

/// <reference path="angular.min.js" />
var myapp = angular
    .module("AngularModule", [])
 .controller("AngularController", function ($scope, StringManipulationService) {
     $scope.ManipulateString = function (input) {
     
         var strOutput = StringManipulationService.ManipulatedString(input);//Calling Custom Service Method
         $scope.OutputUpper = strOutput.split(',')[0];
         $scope.OutputLower = strOutput.split(',')[1];
         $scope.OutputLength = strOutput.split(',')[2];
     }

 });


Step 4: Creating custom StringManipulationService.js.

/// <reference path="../Scripts/UsingCustomService.js" />
myapp.factory('StringManipulationService', function () { //Factory is used to create Custom Service
    return {
        ManipulatedString: function (input) {
            if (!input) {
                return input;
            }

            var OutputUpper = "";
            var OutputLower = "";
            var OutputLength = 0;

            OutputUpper = input.toUpperCase();
            OutputLower = input.toLowerCase();
            OutputLength = input.length;
            return OutputUpper + "," + OutputLower + "," + OutputLength;
        }
    }
});


Step 8: Let's run the application. Enter text and click on Manipulate String.




Binding Data using Web Service in Angular JS

Let's see with an example:

Table Used

select * from EmployeeTest



Step 1: This is going to be the structure.Include angular.js or angular.min.js file. The file circled are going to be used.



Step 2: Create class Employee. In Employee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AngularDemo
{
    public class Employee
    {
        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public string EmpDesignation { get; set; }

    }
}


Step 3: In Web.config


<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  <webServices>
    <protocols>
      <add name="HttpGet"/>
    </protocols>
  </webServices>
  </system.web>
  <connectionStrings>
    <add name="EmplyoeeDB" connectionString="data Source=.;database=employee; integrated security=SSPI" providerName="Sql.Data.SqlClient"/>
  </connectionStrings>
</configuration> 

Step 4: Lets Create our Web Service EmployeeService.asmx.


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace AngularDemo
{
    /// <summary>
    /// Summary description for EmployeeService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class EmployeeService : System.Web.Services.WebService
    {

        [WebMethod]
        public void GetEmployeeData()
        {
            List<Employee> employeeObj = new List<Employee>();
            String CS = ConfigurationManager.ConnectionStrings["EmplyoeeDB"].ConnectionString;
            using (SqlConnection sqlcon = new SqlConnection(CS))
            {
                SqlCommand sqlcmd = new SqlCommand("Select * from EmployeeTest", sqlcon);
                sqlcon.Open();
                SqlDataReader sqlReader = sqlcmd.ExecuteReader();
                while (sqlReader.Read())
                {
                    Employee employee = new Employee();
                    employee.EmpID = Convert.ToInt32(sqlReader["EmpID"]);
                    employee.EmpName = sqlReader["EmpName"].ToString();
                    employee.EmpDesignation = sqlReader["EmpDesignation"].ToString();
                    employeeObj.Add(employee);
                }
            }
            JavaScriptSerializer javaScriptSerializer=new JavaScriptSerializer();
            Context.Response.Write(javaScriptSerializer.Serialize(employeeObj));
        }
    }
}

Step 5 : Lets run our Web Service.





 Service is working fine.

Step 6: In stylesheet1.css


table {
    border-collapse: collapse;
    font-family: Arial;
}

td {
    border: 1px solid black;
    padding: 5px;
}

th {
    border: 1px solid black;
    padding: 5px;
    text-align: left;
    cursor: pointer;

}

Step 7: In CallingWebServiceFromJS.js

/// <reference path="angular.min.js" />
var myapp = angular
    .module("AngularModule", [])
 .controller("AngularController", function ($scope,$http) {
     $http.get('EmployeeService.asmx/GetEmployeeData')
     .then(function (response) {
         $scope.employees = response.data;
     });
 });

Step 7: In CallingWebServiceFromJS.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="AngularModule">
<head>
    <title></title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/CallingWebServiceFromJS.js"></script>
</head>
<body ng-controller="AngularController">
    <table border="1">
        <thead>
            <tr>
                <th>EmpID</th>
                <th>EmpName</th>
                <th>EmpDesignation</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="employee in employees">
                <td>{{employee.EmpID}}</td>
                <td>{{employee.EmpName}}</td>
                <td>{{employee.EmpDesignation}}</td>
            </tr>
        </tbody>
    </table>
</body>
</html>


Step 8: Let's run the application