Friday, December 25, 2015

Deregister an AngularJS $watch Expression

As you know $watch registers a listener callback that is executed whenever the watch expression changes.

The $watch function returns a deregister function. Calling this deregister function will deregister the $watch expression

Here is an example on registering and deregistering the $watch expression

//registering the $watch listener. It returns a deregister function
var deregister = $scope.$watch('name', function(newValue, oldValue) {
  //code here
});

//calling the deregister function
deregister();

AngularJS Cancel $timeout

$timeout returns a promise. This promise is resolved when delay is passed and the timeout function is executed.

To cancel the timeout request, call $timeout.cancel(promise).

Here is an example on how to cancel the $timeout

//setting timeout and storing the return value in a local variable
var promise = $timeout(function () {
    //code to be executed after 50 milliseconds
}, 50);

//Cancelling the above timeout by passing the promise

$timeout.cancel(promise)

Update NPM for Visual Studio 2015

Below are the steps to update NPM for Visual Studio:
  • Download latest Node package (which includes NPM) from the below link

o   In the above link click on the latest version (currently it is latest-v5.x)
o   From the latest version download the latest 64 bit (node-v5.3.0-x64.msi) or 32 bit msi(node-v5.3.0-x86.msi)
  • Run the msi to install the Node & NPM
  • Once Node and NPM is installed, open the VS2015 Developer Command Prompt
  • Type npm to find the path where npm is installed

  • As you can see npm location on my laptop. We need to specify this path in Visual Studio
  • Open Visual Studio and go to Tools > Options > Projects and Solutions > External Web Tools
 
  • Add the path of npm in Visual Studio (remove the last part of the path "node_modules/npm"
  • With the above steps your npm is updated in the global path and the correct path is set in Visual Studio.
In future if you want to update npm you just need run the below command


npm install npm stable -g

Monday, November 30, 2015

Multi-Tenant Claim Based Identity in ASP.NET Core

Recently I have implemented a multi-tenant architecture in one my products. I have used ASP.NET Identity and claims based access control for this. I have implemented authentication, authorization and navigation from database.

In this series of blogs, I will blog on how I did it and the corresponding code for this. Here are the posts in this series:
The complete code for this Multi-Tenant implementation can be found on my GitHub site: MegaMine.Services.Security

Thursday, October 1, 2015

ASP.NET 5 and camelCase JSON

As you know in .NET we all use PascalCase and in JavaScript we use camelCase. In order to sync the ASP.NET and SPA application that use JavaScript, we have CamelCasePropertyNamesContractResolver. Here is the code on how to configure this contract resolver in ASP.NET 5.0

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

    }); 

Tuesday, September 29, 2015

Resolve Angular promises multiple times

As you know that a promise can only be resolved once. While building a framework for my application, I came into a requirement that I need to resolve the same promise multiple times. In order to resolve the same promise multiple times, I found a hack solution that works.

First I clone the original promise object (actually the promise state). I will then clone this promise and then keep resolving this when needed. Here is the code that does this:

    if (promiseState === undefined)
        promiseState = angular.copy(deferred.promise.$$state);
    angular.extend(deferred.promise.$$state, promiseState)
    deferred.resolve();

In the above code, I am using promiseState to keep a copy of the original promise state. I am using kind of singleton pattern to store the promise state. Before resolving the promise, I clone the original promise state and override the current promise state. With this trick I was able to resolve the same promise multiple times.

Here is the complete code. You can also get this code at this Plunker (http://plnkr.co/edit/HsTpGIcxAHwvYAH3UGbQ?p=preview)

<html>
<head>
    <title>Resolve Angular promises multiple times</title>
</head>
<body ng-app="multipleResolves">
    <div ng-controller="index as vm">
        Click the button below to resolve a promise. Every click will resove the same promise again, thereby resolving a promise multiple times
        <br /><br />
        <button ng-click="vm.resolve()">Resolve</button>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    <script>
        angular.module('multipleResolves', [])
        .controller("index", index);
        function index($scope, $q) {
          var deferred, promiseState

            var vm = {
              resolve: resolve
            }

            init();
            return vm;

            function init() {
                angular.extend($scope, vm);

                //creating the $q
                deferred = $q.defer();

                deferred.promise.then(function(){
                  alert('resolved');
                })
            }

            function resolve() {
                // below three lines are the key for resolving a promise multiple times
                 if (promiseState === undefined)
                     promiseState = angular.copy(deferred.promise.$$state);
                 angular.extend(deferred.promise.$$state, promiseState)
              deferred.resolve();
            }

        }
    </script>
</body>
</html>

Thursday, September 10, 2015

AngularJS Dynamic Validation and Error Messages

AngularJS directive ngMessages provides a mechanism to show the error message dynamically. The documentation of this can be found at:


Unfortunately this documentation does not provide a sample working code which links the validation and error messages. In this blog I will show how to utilize the ngMessages to show validation error messages that are not predefined, in other words dynamically showing the messages.

In my scenario, I am doing some validations on the server (asp.net) and want to show the messages returned by the server. Let’s assume that user enters a username or something in the UI and this data is posted back to the server. On server I perform some validations such as user name should be unique and then want to show those validation messages attached to the form elements, in my case the textbox. For this dynamic ngMessages is a good fit. To demo this, I extended the AngularJS example to show the dynamic error message. Here is the AngularJS example for the ngMessages


As you see the ngMessage example on AngularJS site is using required and other messages. For this I am going to add the dynamic messages as shown below

<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-repeat="errorMessage in errorMessages">
        <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div>
    </div>
</div>

The errorMessages object will contain the messages that we dynamically add to the textbox control. Further ngRepeat will provide us an ability to attach multiple error messages.

Now when we get the error messages from the server, we can add those to the errorMessages object and then set the validation of textbox control to false as shown by the below code

function getDynamicErrorMessage(control) {
    //making a http request and getting the error. Add that error to the errorMessages
    var serverErrors = [{ type:'dynamicMessage', text:'Error Message Shown Dynamically'}]
    angular.extend(vm.errorMessages, serverErrors);
    control.$setValidity('dynamicMessage', false);
}

With the above few lines of code, we can get the dynamic error messages and show them in UI using AngularJS ngMessages.

Here is the complete code:

<html>
<head>
    <title>Dynamic Messages Sample</title>
</head>
<body ng-app="dynamicMessages">
    <div ng-controller="index as vm">
        <form name="myForm" novalidate>
            <label>
                Enter your name:
                <input type="text" name="myName" ng-model="name" required />
            </label>
            <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
            <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
                <div ng-message="required">You did not enter a field</div>
                <div ng-repeat="errorMessage in errorMessages">
                    <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div>
                </div>
            </div>
            <button ng-click="getDynamicErrorMessage(myForm.myName)">Get Dynamic ErrorMessage</button>
            <button ng-click="clearDynamicErrorMessage(myForm.myName)">Clear Dynamic ErrorMessage</button>
        </form>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-messages.min.js"></script>
    <script>
        angular.module('dynamicMessages', ['ngMessages'])
          .controller("index", index);

        function index($scope) {
            var vm = {
                errorMessages: [],
                getDynamicErrorMessage: getDynamicErrorMessage,
                clearDynamicErrorMessage: clearDynamicErrorMessage
            }

            init();
            return vm;

            function init() {
                angular.extend($scope, vm);
            }

            function getDynamicErrorMessage(control) {
                //making a http request and getting the error. Add that error to the errorMessages
                var serverErrors = [{
                    type: 'dynamicMessage',
                    text: 'Error Message Shown Dynamically'
                }]
                angular.extend(vm.errorMessages, serverErrors);
                control.$setValidity('dynamicMessage', false);
            }

            function clearDynamicErrorMessage(control) {
                control.$setValidity('dynamicMessage', true);
            }
        }
    </script>
</body>
</html>

You can also view this code in Plunker


Saturday, July 11, 2015

ASP.NET Core / MVC 6 HttpContext.Current

As you know with MVC 6, HttpContext is rewritten and one of the most used functionality , HttpContext.Current is dropped. In most situations you don’t need this and you should use Controller context. But in some situations you may need access to HttpContext. In my scenario I want to pass some data using HttpContext.Items from one layer (middleware) to another (business layer).

Below are the two ways to get current HttpContext:

  • Using dependency injection we can inject the HttpContext on to the service directly. DI injects a singleton object called HttpContextAccessor which is used to retrieve the current HttpContext. Here is the sample code for this

    public class MyService
    {
        private HttpContext context;
        public MySerivce(IHttpContextAccessor contextAccessor)
        {
            this.context = contextAccessor.HttpContext;
        }

  •  Similar to HttpContext.Current we can also create a static class that holds the reference for the current HttpContext. Here is the code for this static class

    public static class HttpHelper
    {
        private static IHttpContextAccessor HttpContextAccessor;
        public static void Configure(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }

        public static HttpContext HttpContext
        {
            get
            {
                return HttpContextAccessor.HttpContext;
            }
        }
    }

This static HttpHelper class stores the singleton HttpContextAccessor and is then used to return the current HttpContext. We will configure our HttpHelper in our startup as shown below

        public void Configure(IApplicationBuilder app)
        {
            //other code
            HttpHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
        }

Finally we can get current HttpContext wherever we need using our Helper as below
HttpHelper.HttpContext

As you see using the above two approaches to get the current HttpContext.

Please see my updated post on this. I am using CallContext to pass the HttpContext and other data
ASP.NET Core Async Context Data

Tuesday, June 30, 2015

AngularJS UI Grid Vertical Resize

I was working on a scenario where I want the UI grid to take up all the available space in the browser, both vertically and horizontally. Doing horizontally is easy, I just need to set the width to 100% and specify “ui-grid-auto-resize”.

The trick is to make the grid resize vertically. For this I wrote a small script which calculates the grid height.

    function getGridHeight(gridClass, contentClass, bottomOffset) {
        var contentOffset = angular.element(document.getElementsByClassName(contentClass)).offset();
        var contentHeight = angular.element(document.getElementsByClassName(contentClass)[0]).height();
        var gridOffset = angular.element(document.getElementsByClassName(gridClass)).offset();
        if (gridOffset !== undefined) {
            var gridHeight = contentHeight - (gridOffset.top) - bottomOffset;
            return gridHeight + 'px';
        }
    }

The above function takes the following three parameters:
  • gridClass – This class is used to identify the current location of the grid in the browser
  • contentClass – This class is the container class of the grid (could be body tag) and this is needed to find the relative position of the grid with in the browser
  • bottomOffset – This specifies how much space we need to leave at the bottom of the window


Now we need to associate this function with the grid height in our angular view and controller. First let’s do the binding in the view as shown below (I am binding the gridHeight to the height of the UI-Grid)

<div ui-grid="vm.gridOptions" external-scopes="vm" ui-grid-resize-columns ui-grid-auto-resize class="patient-grid" ng-style="{'height' : vm.gridHeight }"></div>

In the controller, I will calculate the grid height whenever window resizes as shown below
function resizeGrid() {
        vm.gridHeight = utility.getGridHeight('patient-grid', ‘main-content’, 40);
}

angular.element($window).bind('resize', function () {
       resizeGrid();
});


With the above code, the UI grid would be responsive to the browser height.

Here is the Plunker for this code snippet
http://plnkr.co/edit/LcGe64WkNOAJZfqc7Ics?p=preview