Consume WCF Service into Angular JS Application


In this video tutorial we will learn how to Consume WCF Service into Angular JS   application (CRUD). To continue with this session you must have knowledge about Object Oriented Programming Languages (C#) because we will be using c# programming languages to write the code . 


Software Required :


1.Microsoft SQL Server .
2.Microsoft SQL Management Studio.
3.visual studio 2017 .  


Here is the script to create table .

CREATE TABLE [dbo].[Current_Account_Details](
[Account_Number] [int] IDENTITY(1,1) NOT NULL,
[Account_Creation_Date] [nvarchar](50) NOT NULL,
[Account_Type] [nvarchar](50) NOT NULL,
[Branch_Sort_Code] [nvarchar](50) NOT NULL,
[Account_Fees] [money] NULL,
[Account_Balance] [money] NULL,
[Over_Draft_Limit] [money] NULL
)


Here is entity relation model diagram .



Here is the interface ..


        [OperationContract]
        [WebInvoke(Method = "GET",
         RequestFormat = WebMessageFormat.Json,
         ResponseFormat = WebMessageFormat.Json,
         UriTemplate = "/GetCreateCurrentAccount/")]
        List<Current_Account_Details> GetCreateCurrentAccountList();


        [OperationContract]
        [WebInvoke(Method = "POST",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/CreateCurrentAccount")]
        bool CreateCurrentAccount(Current_Account_Details current_Account_Details);


         [OperationContract]
        [WebInvoke(Method = "PUT",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/UpdateCreateCurrentAccount")
        void UpdateCreateCurrentAccount(Current_Account_Details                        current_Account_Details);


        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json,
       ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "/GetCreateCurrentAccount/{Id}")]
        Current_Account_Details GetCreateCurrentAccount(string Id);

        [OperationContract]
        [WebInvoke(Method = "DELETE",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "DeleteCreateCurrentAccount/{Id}")]
        void DeleteCreateCurrentAccount(string Id);


Here is the Method Implementation.


   public bool CreateCurrentAccount(Current_Account_Details current_Account_Details)
        {
            {
                using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
                {
                    Current_Account_Details createUser = new Current_Account_Details();

                    createUser.Account_Creation_Date = current_Account_Details.Account_Creation_Date;

                    createUser.Account_Type = current_Account_Details.Account_Type;
                    createUser.Branch_Sort_Code = current_Account_Details.Branch_Sort_Code;
                    createUser.Account_Fees = current_Account_Details.Account_Fees;
                    createUser.Account_Balance = current_Account_Details.Account_Balance;
                    createUser.Over_Draft_Limit = current_Account_Details.Over_Draft_Limit;
                    //createUser.Account_Holder_Id = current_Account_Details.Account_Holder_Id;




                    context.Current_Account_Details.Add(createUser);
                    context.SaveChanges();
                }
                return true;
            }
        }

        public List<Current_Account_Details> GetCreateCurrentAccountList()
        {
            using (HalifaxDatabaseEntities ctx = new HalifaxDatabaseEntities())
            {
                var query = (from a in ctx.Current_Account_Details
                             select a).Distinct();

                List<Current_Account_Details> userList = new List<Current_Account_Details>();

                query.ToList().ForEach(rec =>
                {
                    userList.Add(new Current_Account_Details
                    {
                        Account_Number = rec.Account_Number,
                        Account_Creation_Date = rec.Account_Creation_Date,
                        Account_Type = rec.Account_Type,
                        Branch_Sort_Code = rec.Branch_Sort_Code,
                        Account_Fees = rec.Account_Fees,
                        Account_Balance = rec.Account_Balance,
                        Over_Draft_Limit = rec.Over_Draft_Limit

                    });
                });

                return userList;
            }
        }

        public void UpdateCreateCurrentAccount(Current_Account_Details current_Account_Details)
        {
            try
            {

                int Account_Number = current_Account_Details.Account_Number;
                Current_Account_Details std = ctx.Current_Account_Details.Where(rec => rec.Account_Number == Account_Number).FirstOrDefault();
                std.Account_Creation_Date = current_Account_Details.Account_Creation_Date;
                std.Account_Type = current_Account_Details.Account_Type;

                std.Branch_Sort_Code = current_Account_Details.Branch_Sort_Code;
                std.Account_Fees = current_Account_Details.Account_Fees;
                std.Account_Balance = current_Account_Details.Account_Balance;
                std.Over_Draft_Limit = current_Account_Details.Over_Draft_Limit;
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }

        }

        public Current_Account_Details GetCreateCurrentAccount(string Id)
        {
            Current_Account_Details student1 = new Current_Account_Details();

            try
            {
                int ID = Convert.ToInt32(Id);
                var query = (from a in ctx.Current_Account_Details
                             where a.Account_Number.Equals(ID)
                             select a).Distinct().FirstOrDefault();

                student1.Account_Number = Convert.ToInt32(query.Account_Number);
                student1.Account_Creation_Date = query.Account_Creation_Date;
                student1.Account_Type = query.Account_Type;
                student1.Branch_Sort_Code = query.Branch_Sort_Code;
                student1.Account_Fees = query.Account_Fees;
                student1.Account_Balance = query.Account_Balance;
                student1.Over_Draft_Limit = query.Over_Draft_Limit;

            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
            return student1;
        }

        public void DeleteCreateCurrentAccount(string Id)
        {
            try
            {
                int strId = Convert.ToInt32(Id);
                Current_Account_Details std = ctx.Current_Account_Details.Where(rec => rec.Account_Number == strId).FirstOrDefault();
                ctx.Current_Account_Details.Remove(std);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
        }


Here is the code in Script. js file .

/// <reference path="../angular.min.js" />  



var app = angular.module("WebClientModule", [])

    .controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {

        $scope.OperType = 1;
        GetAllRecords();
        //To Get All Records  
        function GetAllRecords() {
            var promiseGet = myService.getAllStudent();
            promiseGet.then(function (pl) { $scope.Users = pl.data },
             
                function (errorPl) {
                    $log.error('Some Error in Getting Records.', errorPl);
                });
        }
        //1 Mean New Entry  

        //To Clear all input controls.  
        function ClearModels() {
            $scope.OperType = 1;
            $scope.Account_Number = "";
            $scope.Account_Creation_Date = "";
            $scope.Account_Type = "";
            $scope.Branch_Sort_Code = "";
            $scope.Account_Fees = "";
            $scope.Account_Balance = "";
            $scope.Over_Draft_Limit = "";
           

        }



        $scope.login = function () {
            var User = {
                Account_Creation_Date: $scope.Account_Creation_Date,
                Account_Type: $scope.Account_Type,
                Branch_Sort_Code: $scope.Branch_Sort_Code,
                Account_Fees: $scope.Account_Fees,
                Account_Balance: $scope.Account_Balance,
                Over_Draft_Limit: $scope.Over_Draft_Limit
             
            };
            if ($scope.OperType === 1) {
                var promisePost = myService.post(User);
                promisePost.then(function (pl) {
                    $scope.Account_Number = pl.data.Account_Number;
                    $scope.Message = "Record is Inserted;"
                    GetAllRecords();
                    $scope.rowCount = 3;
                    ClearModels();
                }, function (err) {
                    $scope.msg = "Password Incorrect !";
                    console.log("Some error Occured" + err);
                });
            } else {
                //Edit the Record
                debugger;
                User.Account_Number = $scope.Account_Number;
                var promisePut = myService.put($scope.Account_Number, User)
                promisePut.then(function (p1) {
                    $scope.Message = "Record is Update;"
                    GetAllRecords();
                    ClearModels();

                }, function (err) {
                    console.log("Some Error Occured." + err);
                });
            }

        };
        //To Get Student Detail on the Base of Student ID  
        $scope.get = function (User) {
            var promiseGetSingle = myService.get(User.Account_Number);
            promiseGetSingle.then(function (pl) {
                var res = pl.data;
                $scope.Account_Number = res.Account_Number;
                $scope.Account_Creation_Date = res.Account_Creation_Date;
                $scope.Account_Type = res.Account_Type;
                $scope.Branch_Sort_Code = res.Branch_Sort_Code;

                $scope.Account_Fees = res.Account_Fees;
                $scope.Account_Balance = res.Account_Balance;
                $scope.Over_Draft_Limit = res.Over_Draft_Limit;


                $scope.OperType = 0;
            },
                function (errorPl) {
                    console.log('Some Error in Getting Details', errorPl);
                });
        }
        //To Delete Record  
        $scope.delete = function (User) {
            var promiseDelete = myService.delete(User.Account_Number);
            promiseDelete.then(function (pl) {
                $scope.Message = "User Deleted Successfuly";
                GetAllRecords();
                ClearModels();
            }, function (err) {
                console.log("Some Error Occured." + err);
            });
        }

    }]);

app.service("myService", function ($http) {


   
    this.post = function (User) {
        var request = $http({
            method: "post",
            url: "http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccount",
            data: JSON.stringify(User)
        });
        return request;

    };


    this.getAllStudent = function () {
        return $http.get("http://localhost:52098/HalifaxIISService.svc/GetCreateCurrentAccount");
    }
    //Update the Record  
    this.put = function (Account_Number, User) {
        debugger;
        var request = $http({
            method: "put",
            url: "http://localhost:52098/HalifaxIISService.svc/UpdateCreateCurrentAccount",
            data: User
        });
        return request;
    }

    //Get Single Records  
    this.get = function (Account_Number) {
        return $http.get("http://localhost:52098/HalifaxIISService.svc/GetCreateCurrentAccount/" + Account_Number);
    }

    //Delete the Record  
    this.delete = function (Account_Number) {
        var request = $http({
            method: "delete",
            url: "http://localhost:52098/HalifaxIISService.svc/DeleteCreateCurrentAccount/" + Account_Number
        });
        return request;
    }

})


Here is the Html ..


@{
    Layout = null;
}

<html data-ng-app="WebClientModule">
<head title="ASAS">
    <title></title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/RegistrationScript/EditAccountDetails.js"></script>
 


</head>
<body>
    <table id="tblContainer" data-ng-controller="Web_Client_Controller">
        Rows to display :
        <input type="number" step="1"
               ng-model="rowCount" max="10" min="0" />

        <tr>
            <td>
                <table style="border: solid 2px Green; padding: 5px;">
                    <tr style="height: 30px; background-color: skyblue; color: maroon;">
                        <th></th>
                        <th>Account Number</th>
                        <th>Account Creation Date</th>
                        <th>Account Type</th>
                        <th>Branch Sort Code</th>
                        <th>Account Fees</th>
                        <th>Account Balance</th>
                        <th>Over Draft Limit</th>

                        <th></th>
                        <th></th>
                    </tr>
                    <tbody data-ng-repeat="user in Users| limitTo:rowCount ">
                        <tr>
                            <td></td>
                            <td><span>{{user.Account_Number}}</span></td>
                            <td><span>{{user.Account_Creation_Date}}</span></td>
                            <td><span>{{user.Account_Type}}</span></td>
                            <td><span>{{user.Branch_Sort_Code}}</span></td>

                            <td><span>{{user.Account_Fees | currency:"£" }}</span></td>
                            <td><span>{{user.Account_Balance| currency:"£"}}</span></td>
                            <td><span>{{user.Over_Draft_Limit| currency:"£" }}</span></td>
                            <td>
                                <input type="button" id="Edit" value="Edit" data-ng-click="get(user)" />
                            </td>
                            <td>
                                <input type="button" id="Delete" value="Delete" data-ng-click="delete(user)" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
            <tr>
                <td></td>
            </tr>
            <tr>
                <td>
                    <table style="border: solid 4px Red; padding: 2px;">
                        <tr>
                            <td></td>
                            <td>
                                <span>Account Number</span>
                            </td>
                            <td>
                                <input type="text" id="account_number" readonly="readonly" data-ng-model="Account_Number" />
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <span>Account Creation Date</span>
                            </td>
                            <td>
                                <input type="text" id="account_creation_date"  data-ng-model="Account_Creation_Date" required="" />
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <span>Account Type</span>
                            </td>
                            <td>
                                <input type="text" id="account_type" required data-ng-model="Account_Type" require="" />
                            </td>
                        </tr>

                        <tr>
                            <td></td>
                            <td>
                                <span>Branch Sort Code</span>
                            </td>
                            <td>
                                <input type="text" id="branch_sort_code" data-ng-model="Branch_Sort_Code" required="" />
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <span>Account Fee</span>
                            </td>
                            <td>
                                <input type="text" id="account_fees" required data-ng-model="Account_Fees" require="" />
                            </td>
                        </tr>

                        <tr>
                            <td></td>
                            <td>
                                <span>Account Balance</span>
                            </td>
                            <td>
                                <input type="text" id="account_balance" data-ng-model="Account_Balance" required="" />
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <span> Over Draft Limit</span>
                            </td>
                            <td>
                                <input type="text" id="over_draft_limit" required data-ng-model="Over_Draft_Limit" require="" />
                            </td>
                        </tr>


                        <tr>
                            <td></td>
                            <td></td>
                            <td>
                                <input type="button" id="Login" value="Insert" data-ng-click="login()" />
                            </td>
                        </tr>
                    </table>
                    <div style="color: red;">{{Message}}</div>

                </td>
            </tr>
        </table>
   
</body>
</html>
<script src="~/RegistrationScript/EditAccountDetails.js"></script>


Here is the Screen shot when you run the application .











2 comments:

  1. I copy same and paste it into visual studio but when i run this code i got following errors .

    1.Invalid parameters error ..
    2. Module not found ...

    ReplyDelete
    Replies
    1. you have to make sure you pass the correct parameters when you post the request. for example the method values account_type must match angular js account_type parameters .

      second things you did mot register the module that's why its showing this error.

      Delete