Sunday 13 August 2017

CURD operation using REST WCF service and Angularjs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/Gets"
            )]
        List<EMP> Gets();
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        EMP Get(int EID);
        [OperationContract]
        [WebInvoke(Method = "POST",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/Save")]
        string Save(EMP emp);
        [OperationContract]
        [WebInvoke(Method = "PUT",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/Update")]
        string Update(EMP emp);
        [OperationContract]
        [WebInvoke(Method = "DELETE",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/Delete")]
        string Delete(int EID);


    }
}

    
Implemented


using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    public class Service1 : IService1
    {

        public List<EMP> Gets()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return obj.EMPs.ToList();
            }
        }

        public EMP Get(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return obj.EMPs.SingleOrDefault(m => m.EID == EID);
            }
        }

        public string Save(EMP emp)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                obj.Entry(emp).State = EntityState.Added;
                obj.SaveChanges();
                return "Data Saved.";
            }
        }

        public string Update(EMP emp)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp1 = obj.EMPs.SingleOrDefault(m => m.EID == emp.EID);
                emp1.NAME = emp.NAME;
                obj.Entry(emp1).State = EntityState.Modified;
                obj.SaveChanges();
                return "Data Updated.";
            }
        }

        public string Delete(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp1 = obj.EMPs.SingleOrDefault(m => m.EID == EID);
                obj.Entry(emp1).State = EntityState.Deleted;
                obj.SaveChanges();
                return "Data Deleted.";
            }
        }
    }
}

web.confic

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="SOAP" binding="basicHttpBinding" contract="WcfService1.IService1"></endpoint>
        <endpoint address="REST" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="eb"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="eb">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true" />
  </system.webServer>
  <connectionStrings>
    <add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>



View

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="bootstrap (1)/css/bootstrap.css" rel="stylesheet" />
    <link href="bootstrap (1)/css/bootstrap-theme.css" rel="stylesheet" />
    <script src="angularjs1.6/angular.js"></script>

</head>
<body>
    <div class="container" ng-app="app" ng-controller="Ctrl" style="padding-top:20px">
        <form class="form-horizontal" novalidate name="frmEmp">
            <div class="form-group " ng-class="{'has-error':frmEmp.txtEid.$invalid,'has-success':frmEmp.txtEid.$valid}">
                <label class="control-label col-lg-4">EID</label>
                <div class="col-lg-4">
                    <input type="text" name="txtEid" class="form-control" ng-model="EMP.EID" required />
                    <span class="has-error help-block" ng-show="frmEmp.txtEid.$invalid && frmEmp.txtEid.$touched ">
                        Eid should not be blank.
                    </span>
                </div>
            </div>
            <div class="form-group " ng-class="{'has-error':frmEmp.txtName.$invalid,'has-success':frmEmp.txtName.$valid}">
                <label class="control-label col-lg-4">NAME</label>
                <div class="col-lg-4">
                    <input type="text" name="txtName" class="form-control" ng-model="EMP.NAME" required />
                    <span class="has-error help-block" ng-show="frmEmp.txtName.$invalid && frmEmp.txtName.$touched ">
                        Name should not be blank.
                    </span>
                </div>
            </div>
            <div class="form-group ">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <input type="button" value="Save" style="width:80px" class="btn btn-primary" ng-click="save(frmEmp.$valid)" />
                    <input type="button" value="Update" style="width:80px" class="btn btn-primary" ng-click="update(frmEmp.$valid)" />
                    <input type="button" value="Reset" style="width:80px" class="btn btn-primary" ng-click="reset()" />
                </div>
            </div>
            <div class="form-group ">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <table class="table table-bordered table-condensed table-hover table-responsive">
                        <thead class="bg-primary">
                            <tr>
                                <th>EID</th>
                                <th>NAME</th>
                                <th>ACTION</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="c in list">
                                <td>{{c.EID}}</td>
                                <td>{{c.NAME}}</td>
                                <td>
                                    <a ng-click="edit(c.EID)">Edit</a> |
                                    <a ng-click="del(c.EID)">Delete</a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
</body>
</html>
<script type="text/javascript">
    angular.module("app", [])
    .controller("Ctrl", function ($scope, empService, $cacheFactory) {
        $scope.cacheObject = $cacheFactory("newCacheInstance");
        function CLR()
        {
            $scope.EMP = new emp();
        } CLR();
        function fill()
        {
            empService.gets().then(function (promise) {
                $scope.list = promise.data;
            });
        } fill();
        $scope.save = function (isValid)
        {
            if (isValid)
            {
                empService.save($scope.EMP).then(function (promise) {
                 
                    alert(promise.data);
                    $scope.cacheObject.removeAll();
                    $scope.cacheObject.destroy();
                    CLR();
                    fill();
                });
            }
           
        }
        $scope.update = function (isValid) {
            if (isValid) {
                empService.update($scope.EMP).then(function (promise) {

                    alert(promise.data);
                    $scope.cacheObject.removeAll();
                    $scope.cacheObject.destroy();
                    CLR();
                    fill();
                });
            }

        }
        $scope.edit = function (s)
        {
            empService.get(s).then(function (promise) {
                $scope.EMP = promise.data;
            });
        }
        $scope.del = function (s) {
            if(confirm('Do you want to delte it ?'))
            empService.delete(s).then(function (promise) {
                alert(promise.data);
                fill();
            });
        }
        $scope.reset = function ()
        {
            $scope.EMP = new emp();
        }
    })
    .service("empService", function ($http) {
        this.save = function (EMP)
        {
       
            return $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Save',
                data: EMP,
                cache: false
            });
        }
        this.update = function (EMP) {

            return $http({
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Update',
                data: EMP,
                cache: false
            });
        }
        this.gets = function ()
        {
            return $http({
                method: 'Get',
                cache: false,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Gets'
            });
        }
       this.get = function (eid) {
            return $http({
                method: 'Get',
                cache: false,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Get?EID='+eid
            });
       }
       this.delete = function (eid) {
       
           return $http({
               method: 'DELETE',
               cache: false,
               headers: {
                   'Content-Type': 'application/json; charset=utf-8'
               },
               data:eid,
               url: 'http://localhost:49612/Service1.svc/REST/Delete'
           });
       }

    });
    function emp()
    {
        return {
            EID: null,
            NAME:null
        }
    }
</script>

No comments:

Post a Comment