Thursday, 25 July 2013

Behaviour of Scope in Angular JS Directives

Directive is the coolest and most crucial feature provided by Angular JS. Use of scope in directives makes the process of writing a directive challenging. Behaviour of scope depends on the way it is assigned in the directive. Following are different scenarios of using scope inside directive:

  • Scope not assigned or set to false
  • Scope set to true
  • Isolated scope

Following is a simple controller with just one value assigned to scope that we will be using in a sample page:
var app = angular.module("myApp", []);

app.controller("SampleCtrl", ['$scope', function ($scope) {
    $scope.val = 0;
}]);


Let’s have a look at each of the above scenarios individually.

Scope not assigned or set to false:
Consider the following directive:
app.directive("dirWithoutScope", function () {
    return{
        scope:false,
        link: function (scope, elem, attrs, ctrl) {
            scope.val=20;
        }
    }
});

As the directive is not making any changes, scope of this directive remains same as the scope of its parent element. The statement in the link function modifies value of the property val, which is set in the controller. Both of the following span elements will display same value, which is 20.
<span>{{val}}</span>

<span dir-without-scope>{{val}}</span>


Scope set to true:
In this case, scope of the directive would be prototypically inherited from scope of its parent element. Let’s consider the following directive:

app.directive("dirWithScopeTrue", function () {
    return{
        scope:true
    }
});

As the scope is prototypically inherited, properties of the parent scope are accessible using this scope. The following span tag will still hold the value assigned to the parent scope:
<span dir-with-scope-true>{{val}}</span>

Let’s complicate the scenario a bit by adding the following link function to the above directive:
link: function (scope, elem, attrs, ctrl) {
    scope.val=25;
}

The value 25 isn’t assigned to the val property in the parent scope. Instead, this statement creates a new property in the child scope and assigns the value to it. The span element created above will hold the value 25 now.

If the value is set through $parent property of the scope, the value gets assigned to the parent scope.

$scope.$parent.val=25;

If statement of link function is replaced with the above statement, values in all span elements will change to 25.

Isolated scope:
If a new scope is created in the directive, the scope doesn’t inherit from the parent scope anymore. Properties of the parent scope are not accessible with the new scope. Following directive contains an isolated scope:

app.directive("dirWithBlankScope", function(){
    return{
        scope:{
        },
        link:function(scope, elem, attrs, ctrl){
            scope.val=30;
        }
    }
});

The assignment statement in the link function creates a property val in the new scope. It doesn’t alter the value of the property assigned in the controller or the previous directive. Following span prints value of the new property:
<span dir-with-new-scope>{{val}}</span>

Properties of the scope of parent element are still accessible through $parent property of the scope.
<span dir-with-new-scope>{{$parent.val}}</span>



Happy coding!

Monday, 22 July 2013

Isolate your tests from dependencies with TypeMock’s Isolator

Software development process is continuously evolving. One of the most talked practices in current era is Test Driven Development (TDD). There can’t be a day when I get into twitter and not seen some tweets on TDD and Unit testing. After some days, we may see very less number of projects that don’t have unit tests written.

If a piece of code is driven by tests, the code will not only have less bugs but the developers also spend some time to refactor and make the code cleaner. This makes the job of future developers easier, as they don’t have to take pain to write unit tests for a small piece that they write to add a new feature to the existing giant code base.

But we have a huge number of legacy projects for which we don’t have unit tests written. As most of such projects were not written with layers and abstractions, one will be more than scared to write automated unit tests for them. But these projects shouldn’t be left behind. A mocking framework with capability to mock out tight dependencies will make the work easier.

TypeMock’s Isolator is a right choice to pick in such scenarios. There are three versions of Isolator; the details on these versions are available on the product page.

To start using Isolator in a unit test project, a couple of assembly references have to be added. These dlls are added to GAC once you install Isolator. In C# projects, we need the references that are highlighted in the following screenshot.



In VB.NET projects, a reference to Typemock.Isolator.VisualBasic has of be added. These namespaces have to be included in the unit test class and the test methods have to be decorated with Isolate attribute as shown:


[TestMethod, Isolated]
public void Should_Set_value_To_Orders()
{

}


This attribute is used to keep each test method independent of each other.

Isolator has a uniform interface for mocking. Meaning, the API syntax to mock abstract types and concrete types is the same. Let us see how Isolator makes the process of writing unit tests easier in action.

Mocking interfaces
Let’s consider the following interface:


public interface IOrdersView
{
        IEnumerable<Order> Orders { get; set; }
        string this[string key] {get;}
        event EventHandler<EventArgs> LoadOrders;
}


It is a very generic interface which will be implemented by a view and can be used in any type of application. Let’s assume that it is used in an ASP.NET application following Model-View-Presenter pattern. The presenter will hold a reference of this interface type. While writing tests for the presenter, we need a mock object of this interface. Following statement creates the mock for us:

IOrdersView ordersView = Isolate.Fake.Instance<IOrdersView>();


Let’s fake behaviour of each of the component now. Let’s start with the property Orders.

Isolate.WhenCalled(()=>ordersView.Orders).WillReturn(new List<Order>(){
    //Use collection initializer to set values
       });


As we see, it is quite easy to skip mock implementation and return some custom values. The same API can be used to mock a method as well. Following statement fakes the event load orders.

Isolate.Invoke.Event(() => ordersView.LoadOrders += (s, e) => { 
     //A custom mock implementation goes here
      });


It is not necessary to implement a handler; it can be skipped by assigning null to the event handler. If the event accepts parameters, they can be passed after the mock implementation.

Faking an indexer is also similar to faking methods. While faking a method accepting parameters or indexers, we must specify value of the argument. Following statement is used to return a custom value when the indexer is asked to provide value of ID:


Isolate.WhenCalled(() => orders["ID"]).WillReturn("1");


Mocking Concrete types
Most of the legacy applications don’t follow rules of separation of concerns that we talk these days. For instance, if we take an old ASP.NET web forms based application, the code behind of each of the form is very heavily loaded with code. Testing such classes is not easy. Most scary object to deal with in ASP.NET code behind is HttpContext. This single object has a bunch of properties that are set by the web server when the application starts. Isolator’s API has a method that fakes all the properties in one go.


Isolate.WhenCalled(() => HttpContext.Current).ReturnRecursiveFake();


If there is a need to return some specific values when certain properties are invoked, you can do that using same API that we used for mocking interfaces. It is shown below:

var httpContextFake = Isolate.Fake.Instance<HttpContext>();
Isolate.WhenCalled(() => httpContextFake.Session["UserId"]).WillReturn("U001");
Isolate.WhenCalled(() => HttpContext.Current).WillReturn(httpContextFake);


Many applications contain a data access layer that is responsible to hit the database to operate on data from the application. Before technologies like Entity Framework came in, most of the projects used to perform database operations using ADO.NET. While writing tests for logic involving objects of SqlConnection and SqlCommand, we must prevent the tests from hitting the database. Isolator makes it possible to replace the actual objects with mocked objects on the fly. Following snippet demonstrates it:

var sqlCommandInstance = Isolate.Fake.Instance<SqlCommand>();
Isolate.Swap.NextInstance<SqlCommand>().With(sqlCommandInstance);


The first statement that creates the fake instance of SqlCommand mocks all methods defined in the class as well. After these statements, if we instantiate the data access layer and call a method that uses ExecuteNonQuery, then the call won’t hit the physical database. It will invoke the fake method that is just created.

These are some of the most common scenarios that we face during unit testing. Isolator is capable of doing much more than what is discussed here. Some of the eye-catching features include mocking:

  1. LINQ queries
  2. Private members
  3. Static members
  4. Counting calls
  5. Extension methods

To learn more on Typemock’s Isolator, you may visit the product page and checkout the online documentation.

Happy coding!

Saturday, 20 July 2013

Basics: Architecture of Modern Client Applications

We can no longer imagine a day without an app running on one of the electronic devices that we hold in our hands. Developers are actively creating apps for different purposes. May it be social media, weather report, news, stock market, even on quotes of your favourite philosopher and many others! So there are good numbers of chances that new people getting into programming turn into app developers. In this post, we will take a look at the architecture of client applications in general and a common question that I usually get from developers.

We have different kinds of client applications available these days. Following are some examples of client applications:

  • Apps that run on smart phones like iPhone, Android, Windows phone or any such device
  • Windows 8 Store apps
  • Applications like Google talk, Yahoo messenger, MetroTwit that run on any OS

Any kind of application must have two basic components: UI and Data. In context of modern client applications, they work as follows:

  • UI of modern client applications is rendered completely on the client’s device, because of which the user gets very rich experience
  • The app can use data stored in the device or it may fetch data with help of services that are hosted on a server. These services are responsible to connect to database and operate on the data

Following is a pictorial representation of the above points:




A common question:

Developers often get a question on accessing data from client applications when they are new to this model of development. The question is, “Why can’t we use data access technologies like ADO.NET or Entity Framework directly in the app?”

This question arises due to lack of understanding of the architecture. If you look at the above figure, it is quite clear that the data resides on a remote server to which the device can contact using network. It is important to note that the database cannot be directly accessible from any other device on the network. So, there has to be an accessible layer between the database and the application. This layer is service. The service has to be hosted at a place that has permissions to perform required operations on the database.

Since database is not accessible directly, there is no point in supporting use of database APIs in such applications.

Happy coding!

Wednesday, 10 July 2013

Book Review - SignalR: Real-time Application Development

Over past few days, I was reading the book SignalR: Real-time Application Development, authored by Einar Ingebrigtsen and published by PaktPub. It is a nice, quick and effective read on SignalR. If you are looking for a simple guide to get you up to speed with the technology, then this book is a right choice.


The author did a nice job by keeping it very simple and yet covering what someone needs to know to start working on a project based on SignalR. All chapters are hands-on based with every step explained in detail. Because of this, it is extremely easy to follow the concepts and keep coding the examples at the same time.

First chapter of the book starts with stories on old terminal systems and discusses till rich clients and how they are better than any of the older client type. Immediately, the author jumps to web development, how it evolved over the years and what is expected out of web today. Here, it discusses what problems are solved by SignalR and why it is necessary to learn this technology.



After introducing the technology, the author dives into technical details of SignalR and discusses the underlying concepts in different chapters. The chapters cover following:

  • Creating server components using Persistent connections and Hubs and consuming them in Web and .NET clients
  • Creating groups on server and maintaining clients in the groups
  • Maintaining state
  • Securing hubs and applying authentication, authorization on Hub’s methods
  • Scaling out across multiple servers using different techniques
  • Monitoring traffic using tools like Fiddler
  • Hosting outside a web application using OWIN
  • Using SignalR in Windows Store applications

I hope you enjoy reading this 124-page quick read on SignalR as much as I did.

Happy coding!