Monday, 29 January 2018

AngularJS –Access Scope from outside function ($apply)

We know angularjs has a data binding between scope and html, which means what ever data changes we make in our controller scope it gets reflected to our html. But things change when we use a 3rd party library or external events to make changes to our scope.

Lets take an example to see how this happens

HTML
<body ng-app='MainApp'>
    <div ng-controller='MainCtrl'>
      <div>
        <div>{{text}}</div>
        <button id='click_button' type='button' >Click Me</button>
        <p>When You Click, only alert shows but text doesn't update</p>
      </div>
    </div>
</body>

ANGULARJS
var mainMod = angular.module('MainApp', []);
mainMod.controller('MainCtrl', ['$scope',
    function ($scope) {
         
         $scope.text = 'Hey';
         $('#click_button').click(function(){
           alert('Click!');
           $scope.text = new Date();
         });
    }
]);

In the above, code I have taken a simple scope variable “text” and used jquery library to demonstrate an outside function. So using jquery’s click function, when you click on the “Click Me” button i have changed the scope “text” variable to current date. If you run the code you will see that it will not work.

Access Angular Scope From Outside Function or 3rd Party Library
AngularJS exposes a method “$apply” for this purpose. This function is used to inform angular that changes have been made to $scope variable from an outside function or event.

Here is code for the same

ANGULARJS
var mainMod = angular.module('MainApp', []);
mainMod.controller('MainCtrl', ['$scope',
    function ($scope) {
         
         $scope.text = 'Hey';
         $('#click_button').click(function(){
           alert('Click!');
           $scope.$apply(function(){
             $scope.text = new Date();
           });
         });
    }
]);

Now we see Date gets updated on button click.
The only change made to above code was

$scope.$apply(function(){
  $scope.text = new Date();
});

So we made the $scope changes inside the $apply function. This tell answer to run the $digest cycle to check for any changes in $scope.

Difference Between $apply and $apply(fn)

There are two ways to use the $apply function, taking the above example

 Method1:

$scope.$apply(function(){
             $scope.text = new Date();
           });

Method2:

$scope.text = new Date();
$scope.$apply();

In most cases both the above will give you the same desired effect, but there are difference between the two. As per angular documentation, pseduo code for $apply is

function $apply(expr) {
  try {
    return $eval(expr);
  catch (e) {
    $exceptionHandler(e);
  } finally {
    $root.$digest();
  }
}

So the Method1 takes care of exception handling and always run the digest cycle. So method1 is always preferred to method2.

   
Continue Reading →

Sunday, 28 January 2018

AngularJS – $watch $digest $apply Life Cycle

At the heart of angularjs is data binding, in this blog post we will see how angular implements this and what is the life cycle of angular scope. This is very important to understand if you want to optimize your application for performance.

AngularJS Dirty Checking
Dirty checking is a very simply process to check if the value of an expression/variable has changed. Its basically just comparing old value with a new value to see if it has changed. AngularJS uses dirty checking to see if a value of a expression/variable in it’s scope has changed or not, and if it has changed it does the required operation (updating DOM etc).

$watch
$watch is angular method, for dirty checking. Any variable or expression assigned in $scope automatically sets up a $watchExpression in angular. You can create a watch express yourself as well

$scope.$watch('variable',function(newValue,oldValue){
  
});

So assigning a variable to $scope or using directives like ng-if, ng-show, ng-repeat etc all create watches in angular scope automatically. e.g $scope.text = ''; creates a $watch for ‘text’ automatically in angular.

$digest
$digest() is angular method, which is invoked internally by angularjs in frequent intervals. In $digest method, angular iterates overall $watches in its scope/child scoples.If any changes are found the resulting DOM operation is done.

$apply
$apply() is a angular method, internally invokes $digest. This method is used when you want to tell angular manually start dirty checking (execute all $watches).

$destroy
$destory is both a method and event in angularjs. $destory() method, removes a scope and all its children from dirty checking. $destory event is called by angular when ever a $scope or $controller is destroyed.

$scope.$on('$destory',function(){
   //do clean up here
});

So we see the $digest and $watch are critical to the working on angularjs.



Continue Reading →

AngularJS – $compile $parse $interpolate

AngularJS provide three useful services which it uses internally., $compile, $parse, $interpolate. These service are mainly used to evaluate expression and rendering UI.

$compile: This service converts a html string in a fully functional DOM element. The resulting DOM would have all linking, events working just like a DOM element. This uses $parse internally for evaluating expressions. e.g usage of $compile would be

var html = '<div ng-click='clickme();'>{{text}}</div>';
$compile(html)($scope);

$compile is mostly used inside custom directives and doesn’t have much use outside.

$interpolate : This service is used to evaluate angular expressions. You can run an entire string against a scope, and interpolate will give the result. e.g would be

var string = 'My Suraj is {{name}}';
$scope.name = 'Suraj';
$interpolate(string)($scope); //this will result in My Name is Suraj

$parse : This service is used as a getter/setter for single variables only. e.g would be

$scope.text = 'abc';
$parse('text')($scope);  //this will result in abc
$parse('text').assign($scope,'xyz');
Continue Reading →

Saturday, 30 December 2017

SingleOrDefault Vs FirstOrDefault

 SingleOrDefault() Vs. FirstOrDefault() in LINQ Query


Single() / SingleOrDefault()
First () / FirstOrDefault()
Single() - There is exactly 1 result, an exception is thrown if no result is returned or more than one result. 
SingleOrDefault() – Same as Single(), but it can handle the null value.
First() - There is at least one result, an exception is thrown if no result is returned.
FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
Single() asserts that one and only one element exists in the sequence.
First() simply gives you the first one.
When to use
Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.
When to use
Developer may use First () / FirstOrDefault() anywhere,  when they required single value from collection or database.
Single() or SingleOrDefault() will generate a regular TSQL like "SELECT ...".
The First() or FirstOrDefault() method will generate the TSQL statment like "SELECT TOP 1..."
In the case of Fist / FirstOrDefault, only one row is retrieved from the database so it performs slightly better than single / SingleOrDefault. such a small difference is hardly noticeable but when table contain large number of column and row, at this time performance is noticeable.
Continue Reading →

Wednesday, 27 December 2017

Web API Filters

Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.

Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System.Web.Http.Filters namespace. However, System.Web.Http.Filters includes other interfaces and classes that can be used to create filter for specific purpose.

The following table lists important interfaces and classes that can be used to create Web API filters.

Filter TypeInterfaceClassDescription
Simple FilterIFilter-Defines the methods that are used in a filter
Action FilterIActionFilterActionFilterAttributeUsed to add extra logic before or after action methods execute.
Authentication FilterIAuthenticationFilter-Used to force users or clients to be authenticated before action methods execute.
Authorization FilterIAuthorizationFilterAuthorizationFilterAttributeUsed to restrict access to action methods to specific users or groups.
Exception FilterIExceptionFilterExceptionFilterAttributeUsed to handle all unhandled exception in Web API.
Override FilterIOverrideFilter-Used to customize the behaviour of other filter for individual action method.
As you can see, the above table includes class as well as interface for some of the filter types. Interfaces include methods that must be implemented in your custom attribute class whereas filter class has already implemented necessary interfaces and provides virtual methods, so that they can be overridden to add extra logic. For example, ActionFilterAttribute class includes methods that can be overridden. We just need to override methods which we are interested in, whereas if you use IActionFilter attribute than you must implement all the methods.

Visit MSDN to know all the classes and interfaces available in System.Web.Http.Filters.

Let's create simple LogAttribute class for logging purpose to demonstrate action filter.

First, create a LogAttribute class derived from ActionFilterAttribute class as shown below.

Example: Web API Filter Class

public class LogAttribute : ActionFilterAttribute 
 {
    public LogAttribute()
    {

    }
       

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }
}

In the above example, LogAttribute is derived from ActionFilterAttribute class and overrided OnActionExecuting and OnActionExecuted methods to log in the trace listeners. (You can use your own logging class to log in textfile or other medium.)

Another way of creating LogAttribute class is by implementing IActionFilter interface and deriving Attribute class as shown below.

Example: Web API Filter Class

public class LogAttribute : Attribute, IActionFilter
{
    public LogAttribute()
    {

    }
    public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");

        var result = continuation();

        result.Wait();
            
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");

        return result;
    }

    public bool AllowMultiple
    {
        get { return true; }
    }
} 

In the above example, deriving from Attribute class makes it an attribute and implementing IActionFilter makes LogAttribute class as action filter. So now, you can apply [Log] attributes on controllers or action methods as shown below.

Example: Apply Web API Filter on Controller

[Log]
public class StudentController : ApiController
{
    public StudentController()
    {
            
    }

    public Student Get()
    {
        //provide implementation  
    }
}

So now, it will log all the requests handled by above StudentController. Thus you can create filters for cross-cutting concerns.

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives