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>