Latest Posts

Tuesday, December 1, 2015

WCF Duplex Communication in Windows Service

namespace WindowsServiceApp
{

    [ServiceContract(CallbackContract = typeof(IWcfServiceCallBack))]
    public interface IWcfService
    {
        [OperationContract]
        void getAuth(string auth);
        [OperationContract]
        double getPrice(string auth);
    }
    [ServiceContract]
    public interface IWcfServiceCallBack
    {
        [OperationContract(IsOneWay = true)]
        void getCallBack(string returnAurth);
    }
}


namespace WindowsServiceApp
{

    public class WcfService : IWcfService
    {
        
        public static string errorMessage = "";
        public void getAuth(string auth)
        {
            WindowsServiceApp.WinService.FormScan formScan = new WinService.FormScan();
         
        }

        public double getPrice(string auth)
        {
            double a = 1;
            return a;
        }

    }
}


namespace WindowsServiceApp
{
    public partial class WinService : ServiceBase
    {
        ServiceHost host;
        private static string errorMessage = "";
        public WinService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            host = new ServiceHost(typeof(WcfService));
            host.Open();
        }

        protected override void OnStop()
        {
            host.Close();
        }
     }
}




<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WindowsServiceApp.WcfServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsDualHttpBinding>
        <binding name="WSDualHttpBindingConfig"
          clientBaseAddress="http://localhost:8733/" >
          <security mode="None"/>
        </binding>
      </wsDualHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="WindowsServiceApp.WcfServiceBehavior"  name="WindowsServiceApp.WcfService">
        <endpoint address="" binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBindingConfig"  contract="WindowsServiceApp.IWcfService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
</configuration>

Saturday, September 19, 2015

Return Dynamic Object From Web Api

    public HttpResponseMessage Contactz()
        {
            var data = new List();
            data.Add("abc");
            data.Add("abc");
            data.Add("abc");
            data.Add("abc");
            return new HttpResponseMessage
            {
                Content = new StringContent(JArray.FromObject(data).ToString(), Encoding.UTF8, "application/json")
            };
        }

Wednesday, September 9, 2015

MVC Custom Authetication

  public class HomeController : Controller
    {
        [CustomRole]
        public ActionResult Index()
        {
            return View();
        }

  
    }



 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class CustomRole : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase context)
        {
            //Call from db
            var a = 3;
            if (a==2)
            {
                return true;
            }
            else { return false; }
        }
    }

Sunday, August 2, 2015

Angular Js Server Side And Client Side Authentication for web api

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example - example-$route-service-production</title>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-route.js"></script>
    <script>


        var app = angular.module('ngRouteExample', ['ngRoute']);

        app.factory('rootingfact', function ($http, $q) {
            return {
                getPerson: function (entity) {
                    var deferred = $q.defer();
                    $http.get('/api/Home/getvalue', {
                        // params: { op: 'get' },
                        headers: { "AUTH_TOKEN": entity.token }
                    }).success(function (data) {
                        deferred.resolve({
                            title: data.title,
                            cost: data.price
                        });
                    }).error(function (msg, code) {
                        deferred.reject(msg);
                        $log.error(msg, code);
                    });
                    return deferred.promise;
                }
            }
        });
        app.controller('RootControllerCreate', function ($scope, $http, rootingfact) {

            rootingfact.getPerson($scope.entity).then(
                      function (result) {
                          alert('authorized');
                      },
                      function (error) {
                          alert('error');
                      }
                  );
        });

        app.controller('RootControllerDetail', function ($scope) {




        });

        app.controller('RootControllerUpdate', function ($scope) {





        });

        app.config(function ($routeProvider, $locationProvider) {
            $routeProvider
             .when('/Routing/Detail', {
                 templateUrl: 'Routing/Detail',
                 controller: 'RootControllerDetail'
             })
            .when('/Routing/Create', {
                templateUrl: 'Routing/Create',
                controller: 'RootControllerCreate'
            })
           .when('/Routing/Update', {
               templateUrl: 'Routing/Update',
               controller: 'RootControllerUpdate'
           })
            .otherwise({
                redirectTo: '/'
            });

            // configure html5 to get links working on jsfiddle
            // $locationProvider.html5Mode(true);
        });

        app.run(function ($rootScope, $location) {
            $rootScope.$on("$routeChangeStart", function (args) {
                var path = $location.path().split('/');
                $rootScope.entity = {};
                /* $rootScope.entity.ctrl = path[1];
                 $rootScope.entity.action = path[2];*/
                $rootScope.entity.token = "124_sdfssdfsdfsdf_" + path[1] + "_" + path[2];
            })
            //$rootScope.$on("$routeChangeSuccess"....

            //$rootScope.$on("$routeChangeError"....
        });

    </script>

</head>
<body ng-app="ngRouteExample">
    Choose:
    <a href="/#/Routing/Create">Create</a> |
    <a href="/#/Routing/Detail">Detail</a> |
    <a href="/#/Routing/Update">Update</a> |
    <div ng-view></div>

</body>
</html>





  public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);            
        }
        void Application_BeginRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            var request = context.Request;
            string url = request.Url.LocalPath;
            if (url.IndexOf("api/") != -1)
            {
                IEnumerable<string> headerValues = request.Headers.GetValues("AUTH_TOKEN");
                if (headerValues != null)
                {
                    string[] token = headerValues.ToArray();
                    string[] all = token[0].Split('_');
                    // var dbId = dbContext.abc.FirstOrDefault(x => x.token == token);
                    if ("sdfssdfsdfsdf" != all[1])
                    {
                        throw new Exception("User now exists");
                    }

                }
                else
                {
                    throw new Exception("Error");
                }
            }


        }
    }



  public class test
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public string name { get; set; }
        public decimal? allowance { get; set; }
        public bool paid { get; set; }
    }
    public class abc
    {
        public int id { get; set; }
        public string token { get; set; }
    }
    public class context : DbContext
    {
        public DbSet<abc> abc { get; set; }
    }
 
    public class HomeController : ApiController
    {
     



        [HttpGet]
        public HttpResponseMessage getvalue()
        {
            string abc = "";


            return new HttpResponseMessage
            {
                Content = new StringContent(abc,
                                       System.Text.Encoding.UTF8, "application/json")
            };
        }

    }


Friday, July 10, 2015

ng grid with multiple column filter

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="utf-8">
    <title>ng grid paging</title>
    <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
    <style>
        .gridStyle {
            border: 1px solid rgb(212,212,212);
            width: 600px;
            height: 300px;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
    <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', ['ngGrid']);
        app.controller('MyCtrl', function ($scope, $http) {
            $scope.filterOptions = {};
            var myHeaderCellTemplate = '<div>{{col.displayName}}</div>'
               + '<input type="text" ng-model="gridOptions.filterOptions[col.displayName]"/>';


            $scope.totalServerItems = 0;
            $scope.pagingOptions = {
                pageSizes: [250, 500, 1000],
                pageSize: 250,
                currentPage: 1
            };

            $scope.getPagedDataAsync = function (pageSize, page, filterOptions) {
                var searchStr = JSON.stringify(filterOptions);
                setTimeout(function () {
                    $http.get('/api/home/getJson?pageSize=' + pageSize + '&page=' + page + '&searchStr=' + searchStr).success(function (largeLoad) {
                        $scope.myData = largeLoad.data;
                        $scope.totalServerItems = largeLoad.count;
                        if (!$scope.$$phase) {
                            $scope.$apply();
                        }
                    });

                }, 100);
            };

            $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);

            $scope.$watch('pagingOptions', function (newVal, oldVal) {
                if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
                    $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions);
                }
            }, true);
            $scope.$watch('filterOptions', function (newVal, oldVal) {
                if (newVal !== oldVal) {
                    $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions);
                }
            }, true);

            $scope.gridOptions = {
                data: 'myData',
                enablePaging: true,
                rowHeight: 36,
                headerRowHeight: 60,
                showFooter: true,
                totalServerItems: 'totalServerItems',
                pagingOptions: $scope.pagingOptions,
                filterOptions: $scope.filterOptions,
                columnDefs: [{ field: 'name', displayName: 'name', headerCellTemplate: myHeaderCellTemplate },
                             { field: 'allowance', displayName: 'allowance', headerCellTemplate: myHeaderCellTemplate },
                             { field: 'paid', displayName: 'paid', headerCellTemplate: myHeaderCellTemplate }]
            };
        });
    </script>
</head>
<body ng-controller="MyCtrl">
    <div class="gridStyle" ng-grid="gridOptions"></div>
</body>
</html>





public class test
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public string name { get; set; }
        public decimal? allowance { get; set; }
        public bool paid { get; set; }
    }
    public class HomeController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage getJson(int pageSize, int page, string searchStr)
        {

            test searchParms = searchStr == "undefined" ? new test() : new JavaScriptSerializer().Deserialize<test>(searchStr);

            string jsonstr = "[{ \"name\": \"Moroni\", \"allowance\": 505050505050505050, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false }]";


            List<test> jsonList = new List<test>();
            jsonList = new JavaScriptSerializer().Deserialize<List<test>>(jsonstr);


            var result1 = searchParms.name == "" || searchParms.name == null ? jsonList : jsonList.Where(x => x.name.Contains(searchParms.name));


            var result2 = searchParms.allowance == 0 || searchParms.allowance == null ? result1 : result1.Where(x => x.allowance.Equals(searchParms.allowance));

            //result = searchParms.paid == null ? jsonList : result.Where(x => x.paid.Equals(searchParms.paid));

            var totalcount = result2.Count();

           var finalresult = result2.Skip((page - 1) * pageSize).Take(pageSize);
           string jsonstr2 = new JavaScriptSerializer().Serialize(finalresult);


            StringBuilder sb = new StringBuilder();

            sb.Append("{\"data\":").Append(jsonstr2).Append(", \"count\":").Append(totalcount).Append("}");

            //dynamic stuff = JObject.Parse("{ 'name': 'Moroni', 'allowance': 505050505050505050, 'paid': true }");
            return new HttpResponseMessage
            {
                Content = new StringContent(sb.ToString(),
                                       System.Text.Encoding.UTF8, "application/json")
            };
        }
    }

Wednesday, July 8, 2015

ng grid with paging

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="utf-8">
    <title>ng grid paging</title>
    <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
    <style>
        .gridStyle {
            border: 1px solid rgb(212,212,212);
            width: 600px;
            height: 300px;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
    <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', ['ngGrid']);
        app.controller('MyCtrl', function ($scope, $http) {

            $scope.totalServerItems = 0;
            $scope.pagingOptions = {
                pageSizes: [5, 10, 20],
                pageSize: 5,
                currentPage: 1
            };
            $scope.getPagedDataAsync = function (pageSize, page) {
                setTimeout(function () {
                        $http.get('/api/home/getJson?page=' + page + '&pageSize=' + pageSize + '').success(function (largeLoad) {

                            $scope.myData = largeLoad.data;
                            $scope.totalServerItems = largeLoad.count;
                            if (!$scope.$$phase) {
                                $scope.$apply();
                            }
                        });
                }, 1000);
            };

            $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);

            $scope.$watch('pagingOptions', function (newVal, oldVal) {
                if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
                    $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
                }
            }, true);

            $scope.gridOptions = {
                data: 'myData',
                enablePaging: true,
                showFooter: true,
                totalServerItems: 'totalServerItems',
                pagingOptions: $scope.pagingOptions
            };
        });
    </script>
</head>
<body ng-controller="MyCtrl">
    <div class="gridStyle" ng-grid="gridOptions"></div>
</body>
</html>




 public class test
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public string name { get; set; }
        public decimal allowance { get; set; }
        public bool paid { get; set; }
    }
    public class HomeController : ApiController
    {
        public HttpResponseMessage getJson(int page, int pageSize)
        {
            string jsonstr = "[{ \"name\": \"Moroni\", \"allowance\": 505050505050505050, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false },{ \"name\": \"Jacob\", \"allowance\": 27, \"paid\": false },{ \"name\": \"Nephi\", \"allowance\": 29, \"paid\": false },{ \"name\": \"Enos\", \"allowance\": 34, \"paid\": false },{ \"name\": \"Ether\", \"allowance\": 42, \"paid\": false },{ \"name\": \"Alma\", \"allowance\": 43, \"paid\": true },{ \"name\": \"Jared\", \"allowance\": 21, \"paid\": true },{ \"name\": \"Moroni\", \"allowance\": 50, \"paid\": true },{ \"name\": \"Tiancum\", \"allowance\": 53, \"paid\": false }]";


            List<test> jsonList = new List<test>();
            jsonList = new JavaScriptSerializer().Deserialize<List<test>>(jsonstr);

            var totalcount = jsonList.Count();

            var result = jsonList.Skip((page - 1) * pageSize).Take(pageSize);
            string jsonstr2 = new JavaScriptSerializer().Serialize(result);


            StringBuilder sb = new StringBuilder();

            sb.Append("{\"data\":").Append(jsonstr2).Append(", \"count\":").Append(totalcount).Append("}");

            //dynamic stuff = JObject.Parse("{ 'name': 'Moroni', 'allowance': 505050505050505050, 'paid': true }");
            return new HttpResponseMessage
            {
                Content = new StringContent(sb.ToString(),
                                       System.Text.Encoding.UTF8, "application/json")
            };
        }
    }

Friday, July 3, 2015

Angular Js Scope and rootScope

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example - scope and rootscope</title>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-route.js"></script>
    <script>


        angular.module('ngRouteExample', ['ngRoute'])
            .run(function ($rootScope) {
                $rootScope.test = "from on execute run";
            })
         .controller('RootControllerCreate', function ($scope, $rootScope) {
           
             $scope.test = "from create control";
            
         })

         .controller('RootControllerDetail', function ($scope, $rootScope) {
 
             $rootScope.test = "from detail control";
            
         })

         .controller('RootControllerUpdate', function ($scope, $rootScope) {
   
             //$rootScope.test = "from update control";
            
         })

        .config(function ($routeProvider, $locationProvider) {
            $routeProvider
             .when('/Routing/Detail', {
                 templateUrl: 'Routing/Detail',
                 controller: 'RootControllerDetail'
             })
            .when('/Routing/Create', {
                templateUrl: 'Routing/Create',
                controller: 'RootControllerCreate'
            })
           .when('/Routing/Update', {
               templateUrl: 'Routing/Update',
               controller: 'RootControllerUpdate'
           })
            .otherwise({
                redirectTo: 'Routing/Index'
            });

            // configure html5 to get links working on jsfiddle
            // $locationProvider.html5Mode(true);
        });

    </script>

</head>
<body ng-app="ngRouteExample">
    Choose:
    <a href="/#/Routing/Create">Create</a> |
    <a href="/#/Routing/Detail">Detail</a> |
    <a href="/#/Routing/Update">Update</a> |
    <h3>{{test}}</h3>
    <div ng-view></div>

</body>
</html>

Thursday, July 2, 2015

Angular Js Routing with multiple controllers

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example - example-$route-service-production</title>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-route.js"></script>
    <script>


        angular.module('ngRouteExample', ['ngRoute'])

         .controller('RootControllerCreate', function ($scope) {

             $scope.title = "Create";
            
         })

         .controller('RootControllerDetail', function ($scope) {
 
             $scope.title = "Detail";
            
         })

         .controller('RootControllerUpdate', function ($scope) {
   
             $scope.title = "Update";
            
         })

        .config(function ($routeProvider, $locationProvider) {
            $routeProvider
             .when('/Routing/Detail', {
                 templateUrl: 'Routing/Detail',
                 controller: 'RootControllerDetail'
             })
            .when('/Routing/Create', {
                templateUrl: 'Routing/Create',
                controller: 'RootControllerCreate'
            })
           .when('/Routing/Update', {
               templateUrl: 'Routing/Update',
               controller: 'RootControllerUpdate'
           })
            .otherwise({
                redirectTo: 'Routing/Index'
            });

            // configure html5 to get links working on jsfiddle
            // $locationProvider.html5Mode(true);
        });

    </script>

</head>
<body ng-app="ngRouteExample">
    Choose:
    <a href="/#/Routing/Create">Create</a> |
    <a href="/#/Routing/Detail">Detail</a> |
    <a href="/#/Routing/Update">Update</a> |
    <div ng-view></div>

</body>
</html>


c#

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

namespace MvcAngularJs.Controllers
{
    public class RoutingController : Controller
    {
        // GET: Routing
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Create()
        {
            return View();
        }
        public ActionResult Detail()
        {
            return View();
        }
        public ActionResult Update()
        {
            return View();
        }

       
    }
}

Monday, June 29, 2015

jsPdf Print without browser history

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>AngularJS Tutorial</title>
    <script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
   <script type="text/javascript">

       function load() {

           var doc = new jsPDF();

           doc.setFontSize(12);
           doc.text(35, 25, "Welcome to JsPDF");
           doc.autoPrint();
           var string = doc.output('datauristring');
           
           var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"

           var x = window.open();
           x.document.open();
           x.document.write(iframe);
           x.document.close();
          
       };
   </script>
</head>
<body >
    <input onclick="load()" type="button" value="click" />
</body>
</html>

Sunday, June 28, 2015

Bootstrap list group example

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>AngularJS Tutorial</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
    <script>
        angular.module('app', []);

        angular.module('app').controller("MainController", function () {
            var vm = this;
            vm.title = 'AngularJS List Group Example';
            vm.searchInput = '';
            vm.shows = [
                {
                    title: 'title 1',
                    year: 2001,
                    favorite: true
                },
                {
                    title: 'title 2',
                    year: 2002,
                    favorite: false
                },
                {
                    title: 'title 3',
                    year: 2003,
                    favorite: true
                },
                {
                    title: 'title 4',
                    year: 2014,
                    favorite: true
                },
                {
                    title: 'title 5',
                    year: 2005,
                    favorite: false
                }
            ];
        });
    </script>
</head>
<body ng-app="app" ng-controller="MainController as main">
    <div class="container">
        <h1>{{main.title}}</h1>
        <h3>A list of TV shows</h3>
        <ul class="list-group">
            <li class="list-group-item" ng-repeat="show in main.shows"><span class="glyphicon glyphicon-star" ng-if="show.favorite"></span> {{show.title}} <span class="badge">{{show.year}}</span></li>
        </ul>
        
    </div>
</body>
</html>

Bootstrap Login Responsive Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple Responsive Login Form</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    @*<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">*@
    @*<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>*@

</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-4">
                <div class="form-border">
                    <h2>Login Form</h2>
                    <form id="loginform" class="form-horizontal" role="form">

                        <div style="margin-bottom: 25px" class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                            <input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username or email">
                        </div>

                        <div style="margin-bottom: 25px" class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                            <input id="login-password" type="password" class="form-control" name="password" placeholder="password">
                        </div>



                        <div class="input-group">
                            <div class="checkbox">
                                <label>
                                    <input id="login-remember" type="checkbox" name="remember" value="1"> Remember me
                                </label>
                            </div>
                        </div>


                        <div style="margin-top:10px" class="form-group">
                            <!-- Button -->

                            <div class="col-sm-12 controls">
                                <a id="btn-login" href="#" class="btn btn-primary">Login  </a>
                                <a id="btn-fblogin" href="#" class="btn btn-primary">Login with Facebook</a>

                            </div>
                        </div>

                    </form>
                </div>

            </div>
            <div class="col-md-8">
            </div>
        </div>
    </div>
</body>
</html>  

Saturday, June 27, 2015

ng Grid Change cell Color

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
    <style type="text/css">
        .gridStyle {
            border: 1px solid rgb(212,212,212);
            width: 400px;
            height: 300px;
        }

        .red {
            background-color: red;
            color: white;
        }

        .green {
            background-color: green;
            color: white;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
    <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', ['ngGrid']);
        app.controller('MyCtrl', function ($scope) {
            $scope.myData = [{ name: "Name1", age: 1 },
                             { name: "Name2", age: 2 },
                             { name: "Name3", age: 3 },
                             { name: "Name4", age: 4 },
                             { name: "Name5", age: 5 }];
            $scope.gridOptions = {
                data: 'myData',
                columnDefs: [{
                    field: 'name',
                    displayName: 'Name'
                }, {
                    field: 'age',
                    displayName: 'Age',
                    cellTemplate: '<div class="ngCellText" ng-class="{\'green\' : row.getProperty(\'age\') == \'5\' }">{{ row.getProperty(col.field) }}</div>'
                }]
            };


        });
    </script>
</head>
<body ng-controller="MyCtrl">
    <div class="gridStyle" ng-grid="gridOptions"></div>
</body>
</html>

Simple ng Grid

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
    <style type="text/css">
        .gridStyle {
            border: 1px solid rgb(212,212,212);
            width: 400px;
            height: 300px;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
    <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', ['ngGrid']);
        app.controller('MyCtrl', function ($scope) {
            $scope.myData = [{ name: "Name1", age: 1 },
                             { name: "Name2", age: 2 },
                             { name: "Name3", age: 3 },
                             { name: "Name4", age: 4 },
                             { name: "Name5", age: 5 }];
            $scope.gridOptions = { data: 'myData' };
        });
    </script>
</head>
<body ng-controller="MyCtrl">
    <div class="gridStyle" ng-grid="gridOptions"></div>
</body>
</html>

Thursday, June 25, 2015

AngularJS and Twitter Bootstrap and search glyphicon

<!DOCTYPE html>
<html lang="en">


<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<script>
    angular.module("simpleapp", [])
        .controller("SimpleController", function ($scope) {
            $scope.entity = {};
            $scope.entity.title = "A simple AngularJS app";
        });
</script>
<body ng-app="simpleapp">


    <div ng-controller="SimpleController">

        <h2>Hello, {{entity.title}}</h2>

    </div>

    <div class="input-group">
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-search"></span>
        </span>
        <input type="text" class="form-control" ng-model="main.searchInput">
    </div>

</body>

</html>

Tuesday, June 23, 2015

A simple AngularJS app

<!DOCTYPE html>
<html lang="en">


<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="simpleapp">


    <div ng-controller="SimpleController">

        <h2>Hello, {{entity.title}}</h2>

    </div>


    <script>
angular.module("simpleapp", [])
    .controller("SimpleController", function($scope) {
        $scope.entity = {};
        $scope.entity.title = "A simple AngularJS app";
    } );
    </script>



</body>

</html>

Sunday, June 21, 2015

Angular Js $index, $odd and $even with ng-if directive

<!DOCTYPE html>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="customersCtrl">

        <table>
            <tr ng-repeat="x in names">
                <td ng-if="$odd" style="background-color:#a1a1a1; color:#ffffff">
                    {{$index + 1  }}
                </td>
                <td ng-if="$even">
                    {{ $index + 1  }}
                </td>
                <td ng-if="$odd" style="background-color:#a1a1a1; color:#ffffff">
                    {{ x.Name }}
                </td>
                <td ng-if="$even">
                    {{ x.Name }}
                </td>
                <td ng-if="$odd" style="background-color:#a1a1a1; color:#ffffff">
                    {{ x.Country }}
                </td>
                <td ng-if="$even">
                    {{ x.Country }}
                </td>
            </tr>
        </table>

    </div>

    <script>
        angular.module('myApp', [])
           .factory('customersService', function ($http, $q) {
               var deferred = $q.defer();

               return {
                   getPerson: function () {
                       return $http.get("/api/Home/getperson")
                           .then(function (response) {
                               // promise is fulfilled
                               deferred.resolve(response);
                               return deferred.promise;
                           }, function (response) {
                               deferred.reject(response);
                               return deferred.promise;
                           })
                       ;
                   }
               }

           })
           .controller("customersCtrl", function ($scope, $q, customersService) {

               customersService.getPerson().then(
                       function (result) {
                           $scope.names = result.data;
                       },
                       function (error) {
                           // handle errors here
                           alert('error');
                       }
                   );
           });

    </script>

</body>
</html>

Tuesday, June 16, 2015

Angular Js Factory and $q

<!DOCTYPE html>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="customersCtrl">

        <ul>
            <li ng-repeat="x in names">
                {{ x.Name + ', ' + x.Country }}
            </li>
        </ul>

    </div>

    <script>
        angular.module('myApp', [])
           .factory('customersService', function ($http, $q) {
               var deferred = $q.defer();

               return {
                   getPerson: function () {
                       return $http.get("/api/Home/getperson")
                           .then(function (response) {
                               // promise is fulfilled
                               deferred.resolve(response);
                               return deferred.promise;
                           }, function (response) {
                                deferred.reject(response);
                              return deferred.promise;
                           })
                       ;
                   }
               }

           })
           .controller("customersCtrl", function ($scope, $q, customersService) {

               customersService.getPerson().then(
                       function (result) {
                           $scope.names = result.data;
                       },
                       function (error) {
                           // handle errors here
                           alert('error');
                       }
                   );
           });

    </script>

</body>
</html>

Friday, June 12, 2015

Retrieve Data in Angular Js from Web Api as HttpResponseMessage

<!DOCTYPE html>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="customersCtrl">

        <ul>
            <li ng-repeat="x in names">
                {{ x.Name + ', ' + x.Country }}
            </li>
        </ul>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function ($scope, $http) {
            $http.get("/api/Home/getperson").success(function (data) {
                alert(JSON.stringify(data));
                $scope.names = data;
            });
        });
    </script>

</body>
</html>






    public class records
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }
    public class HomeController : ApiController
    {
        public HttpResponseMessage getperson()
        {
            var data = new List();
            records item1 = new records();
            item1.Name = "Name1";
            item1.City = "City1";
            item1.Country = "Country1";
            data.Add(item1);
            records item2 = new records();
            item2.Name = "Name2";
            item2.City = "City2";
            item2.Country = "Country2";
            data.Add(item2);
            records item3 = new records();
            item3.Name = "Name3";
            item3.City = "City3";
            item3.Country = "Country3";
            data.Add(item3);

            return Request.CreateResponse(HttpStatusCode.OK, data);
        }
    }

Thursday, June 11, 2015

Angular Js Upper Case And Lower Case

<!DOCTYPE html>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="personCtrl">

        <p>The name is {{ firstName | uppercase }}</p>
        <p>The name is {{ lastName | lowercase }}</p>

    </div>

    <script type="text/javascript">
        angular.module('myApp', []).controller('personCtrl', function ($scope) {
            $scope.firstName = "jobin";
            $scope.lastName = "jonny";
        });
    </script>
</body>
</html>

Monday, April 6, 2015

File Download using Java Script


<script>
        function saveTextAsFile() {
            var textToWrite = document.getElementById("inputTextToSave").value;
            var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
            var fileNameToSaveAs = "myNewFile.txt";
            var downloadLink = document.createElement("a");
            downloadLink.download = fileNameToSaveAs;
            downloadLink.innerHTML = "My Hidden Link";
            window.URL = window.URL || window.webkitURL;
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = destroyClickedElement;
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
            downloadLink.click();
        }

        function destroyClickedElement(event) {
            document.body.removeChild(event.target);
        }
    </script>
</head>
<body>
    <textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
    <button onclick="saveTextAsFile()">Save Text to File</button>
</body>

Saturday, March 28, 2015

Encryption and Decryption in javascript and c#

javascript
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js "></script>
    <script type="text/javascript">

        function SubmitsEncry() {

            debugger;
            var txtUserName = "Please enter UserName";

            var key = CryptoJS.enc.Utf8.parse('8080808080808080');
            var iv = CryptoJS.enc.Utf8.parse('8080808080808080');

            var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(txtUserName), key,
            {
                keySize: 128 / 8,
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
            var decrypted = CryptoJS.AES.decrypt(encrypted, key,
               {
                   keySize: 128 / 8,
                   iv: iv,
                   mode: CryptoJS.mode.CBC,
                   padding: CryptoJS.pad.Pkcs7
               });
            alert(decrypted.toString(CryptoJS.enc.Utf8));
        }
        SubmitsEncry();

    </script>

c#

 public ActionResult Index()
        {
            string s = "The brown fox jumped over the green frog";
            //string k = "urieurut";
            var encry = EncryptStringAES(s);
            var sss = DecryptStringAES(encry);
            return View();
        }
        public static string DecryptStringAES(string cipherText)
        {
            var keybytes = Encoding.UTF8.GetBytes("8080808080808080");
            var iv = Encoding.UTF8.GetBytes("8080808080808080");

            var encrypted = Convert.FromBase64String(cipherText);
            var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);
            return string.Format(decriptedFromJavascript);
        } 
        private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
        {
            // Check arguments.  
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }

            // Declare the string used to hold  
            // the decrypted text.  
            string plaintext = null;

            // Create an RijndaelManaged object  
            // with the specified key and IV.  
            using (var rijAlg = new RijndaelManaged())
            {
                //Settings  
                rijAlg.Mode = CipherMode.CBC;
                rijAlg.Padding = PaddingMode.PKCS7;
                rijAlg.FeedbackSize = 128;

                rijAlg.Key = key;
                rijAlg.IV = iv;

                // Create a decrytor to perform the stream transform.  
                var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                try
                {
                    // Create the streams used for decryption.  
                    using (var msDecrypt = new MemoryStream(cipherText))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {

                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                // Read the decrypted bytes from the decrypting stream  
                                // and place them in a string.  
                                plaintext = srDecrypt.ReadToEnd();

                            }

                        }
                    }
                }
                catch
                {
                    plaintext = "keyError";
                }
            }

            return plaintext;
        }

        public static string EncryptStringAES(string plainText)
        {
            var keybytes = Encoding.UTF8.GetBytes("8080808080808080");
            var iv = Encoding.UTF8.GetBytes("8080808080808080");

            var encryoFromJavascript = EncryptStringToBytes(plainText, keybytes, iv);
            return Convert.ToBase64String(encryoFromJavascript);
        }  


        private static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
        {
            // Check arguments.  
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            byte[] encrypted;
            // Create a RijndaelManaged object  
            // with the specified key and IV.  
            using (var rijAlg = new RijndaelManaged())
            {
                rijAlg.Mode = CipherMode.CBC;
                rijAlg.Padding = PaddingMode.PKCS7;
                rijAlg.FeedbackSize = 128;

                rijAlg.Key = key;
                rijAlg.IV = iv;

                // Create a decrytor to perform the stream transform.  
                var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption.  
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.  
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            // Return the encrypted bytes from the memory stream.  
            return encrypted;
        }

Monday, January 5, 2015

Tree View Structure From DataBase

        [HttpGet]
        public List getValue(int id)
        {

            var dataList = nodeList().Where(x => x.parentID == 0).ToList();
            List nList = new List();
            foreach (var item in dataList)
            {
                node i = new node();
                i.name = item.name;
                FillChild(i, item.ID);
                nList.Add(i);
            }

            return nList;
        }

        public static List nodeList()
        {
            var nodeList = new List();
            var node1 = new nodeDB();
            node1.ID = 1;
            node1.name = "node1";
            node1.parentID = 0;
            nodeList.Add(node1);
            var node2 = new nodeDB();
            node2.ID = 2;
            node2.name = "node2";
            node2.parentID = 1;
            nodeList.Add(node2);
            var node3 = new nodeDB();
            node3.ID = 3;
            node3.name = "node3";
            node3.parentID = 2;
            nodeList.Add(node3);
            var node4 = new nodeDB();
            node4.ID = 4;
            node4.name = "node4";
            node4.parentID = 0;
            nodeList.Add(node4);
            var node5 = new nodeDB();
            node5.ID = 5;
            node5.name = "node5";
            node5.parentID = 4;
            nodeList.Add(node5);
            return nodeList;
        }
        public int FillChild(node parent, int ID)
        {
            var data = nodeList().Where(x => x.parentID == ID).ToList();
            if (data.Count > 0)
            {
                foreach (var item in data)
                {
                    node child = new node();
                    child.name = item.name;
                    int tempID = item.ID;
                    parent.nodes.Add(child);
                    FillChild(child, tempID);
                }
                return 0;
            }
            else
            {
                return 0;
            }
        }

Saturday, January 3, 2015

AngularJs Bootstrap TreeView

<!DOCTYPE html>



<html ng-app="plunker">
<head>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script>
    <script src="http://ci.angularjs.org/job/angularui-bootstrap/ws/dist/ui-bootstrap-tpls-0.1.1-SNAPSHOT.js"></script>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" />
     @*<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">*@


   
    <script src="~/Script/app/Home/DialogDeomoCtrl.js"></script>
    <link href="~/CSS/stytree.css" rel="stylesheet" />
</head>
<body>
    <div ng-controller="DialogDemoCtrl" >
        <div class="span5 article-tree">
            <div ng-style="{'overflow': 'auto'}" >

                <script type="text/ng-template" id="tree_item_renderer" >

            <span  ng-click="nodeClicked(data)"  >
         
             <i class="{{ switcher( isLeaf(data), '', 'icon-minus-sign' )}}"></i> 
            {{showNode(data)}}
            </span>
             <a href="">{{data.name + ' Edit'}}</a> 
            
            <ul class="some" ng-show="data.show">       
           
            <li ng-repeat="data in data.nodes" class="parent_li"  ng-include="'tree_item_renderer'" tree-node></li>
            </ul>
            </script>

                <div class="tree well">



                    <ul>
                        <li ng-repeat="data in displayTree" ng-include="'tree_item_renderer'" data-ng-click="loadconfig()"></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

</body>
</html>







angular.module('plunker', ['ui.bootstrap', 'ngResource']);
function DialogDemoCtrl($scope, $dialog, $resource) {

    //$scope.isExecuted = false;
   
   
    //buildEmptyTree();
    $scope.title = "visible";
    $scope.count = 0;
    $scope.loadconfig = function () {
        if ($scope.count == 0)
        {
            treeConfig();
            $scope.count = 1;
        }
        console.log('load: ' + new Date().getMilliseconds());
       
    }
    
    read('getvalue', { id: 123 });
    $scope.selectedNode = "";
   


    $scope.showNode = function (data) {

        //console.log(data);

        return data.name;

    };

    $scope.isClient = function (selectedNode) {

        if (selectedNode == undefined) {
            return false;
        }

        if (selectedNode.device_name != undefined) {
            return true;
        }

        return false;
    };
    
    function read(action, params) {
        console.log('read: ' + new Date().getMilliseconds());
        var resource = $resource('api/Home/' + action, params, { action: { method: 'GET', isArray: true } });
        resource.action(params).$promise.then(function (d) {
            $scope.displayTree = d;

        });
    };


}

function treeConfig() {



    var title = $('.tree li:has(ul)').find('.parent_li').find(' > span').attr('title');
    if (title == undefined) {
        // alert(title + "   out");
        $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
    }

    $('.tree li.parent_li > span').on('click', function (e) {
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            var title = $(this).attr('title');
            //   alert(title + "   visible");
            if (title == "Collapse this branch") {
                children.hide('fast');
                $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
            }
        } else if (children.is(":hidden")) {
            var title = $(this).attr('title');
            //   alert(title + "   hidden");
            if (title == "Expand this branch") {
                children.show('fast');
                $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
            }
        }
        e.stopPropagation();

    });
}




.tree {
    min-height:20px;
    padding:19px;
    margin-bottom:20px;
    background-color:#fbfbfb;
    border:1px solid #999;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px;
    -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);
    -moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);
    box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05)
}
.tree li {
    list-style-type:none;
    margin:0;
    padding:10px 5px 0 5px;
    position:relative
}
.tree li::before, .tree li::after {
    content:'';
    left:-20px;
    position:absolute;
    right:auto
}
.tree li::before {
    border-left:1px solid #999;
    bottom:50px;
    height:100%;
    top:0;
    width:1px
}
.tree li::after {
    border-top:1px solid #999;
    height:20px;
    top:25px;
    width:25px
}
.tree li span {
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
    border:1px solid #999;
    border-radius:5px;
    display:inline-block;
    padding:3px 8px;
    text-decoration:none
}
.tree li.parent_li>span {
    cursor:pointer
}
.tree>ul>li::before, .tree>ul>li::after {
    border:0
}
.tree li:last-child::before {
    height:30px
}
.tree li.parent_li>span:hover, .tree li.parent_li>span:hover+ul li span {
    background:#eee;
    border:1px solid #94a0b4;
    color:#000
}

Category