Pages

Tuesday, 21 May 2013

In last post, we implemented SignalR part of the stock ticker sample using Angular JS and modified the HTML page to use Angular’s directives. As promised earlier, we will finish the implementation in this post by incorporating UI changes using directives and filters.

Angular JS is designed with separation of concerns in mind. One of the best architectural features of Angular JS is, it makes it easier to separate HTML and JavaScript separated from each other while playing together at the same time. Features like directives and filters can be used to easily extend Angular’s expressions and behaviour of HTML elements without wasting a lot of time and energy.

In the original Stock Ticker sample, following changes are made while binding data on the page:

Change in stock value is prepended with a up or down symbol based on value

Percentage value is multiplied with 100 and % symbol is appended to it

It also has the following UI effects on the page:

jQuery Colour flash effect on rows of table and list items

List item keeps scrolling when the stock market is open

Buttons are enabled and disabled based on current market state

Creating filters to represent data more effectively

Let’s write a couple of filters to manipulate change and percent change while presenting on the screen:

As you see the above code, implementation of the filters is pretty straight forward. Value on which the filter has to act is passed into the filter function. All we need to do is, manipulate the value as needed and return it. Using these filters is very easy as well, following snippet demonstrates the usage:

The buttons Open market and Reset have to be enabled when market is closed and close market button has to be enabled when market is opened. We can simulate this behaviour using the Boolean property marketIsOpen inside expression ({{ }}).

To evaluate expressions inside a directive, we need $interpolate service. The directive also needs to watch for change of the value to immediately change state of the button. Following is the implementation of the directive:

Now open the new scroll ticker page on a browser. Open the original jQuery based implementation on another browser window and play with both the screens. Now both of them have same look and behaviour.

This sample demonstrates how to make best use of features of Angular JS with SignalR to create real-time data oriented applications. The beauty of this approach is, we have several independent components playing pretty well together. This approach eases organization of code and makes each component testable in isolation.

Code covered in this series is available on Github. Feel free to fork the code if you think that any part of it can be improved!!

Note: If you have finished reading this series and want to use your learning in a project, make a note to check this post as well: A Better Way of Using ASP.NET SignalR With Angular JS. GitHub repo for the series contains a controller and a service that fulfill the same purpose in a better way, make sure to check the code

Sunday, 19 May 2013

In my last post, we saw how to use ASP.NET SignalR and Angular JS together using a Hello World type of example. Now that we got some idea on using both the technologies together, we will take a look at a more advanced scenario to make the frameworks work better together.

I assume that you have already seen the SignalR Stock ticker sample. If not, download it from Github or add the NuGet Package to an existing ASP.NET web application. Make sure that you take some time to run the sample at least once on multiple browsers and have a glance at the code before you proceed further.

I hope you had a look at the code on both server and client side of the stock ticker sample. We will not make any modification to the server code and the layout of the page. But we will rewrite the JavaScript part using features of Angular JS. As there is a lot of client side code to convert, let’s do it in a two-part series:

Creating a custom service to communicate with hub on the server and using the service in a controller (This post)

Make a copy of the StockTicker.html file and give it a name of your choice. Add two files JavaScript files, controller.js and factory.js to the project. We will add script to these files in sometime. Modify the script reference section of the page to include the following script files:

Let’s start implementing SignalR part inside a custom service. To keep the controller free from doing anything other than providing data to the view and handle view events, we are creating a custom service to handle the hub communication logic. The service is responsible for:

Creating objects needed for communication

Configuring client functions to proxy to respond when market is opened, closed, reset or a stock value is updated

Starting a hub connection

Getting current values of stocks and current market status once the connection is started

Opening, closing or resetting market on demand

Following is the module and the factory that handles the functionality mentioned above:

Layout of the HTML page will remain unchanged. But we need to change the way data is rendered on the screen. The stock ticker sample uses poor man’s template technique to render content in the table and in the scrolling list. Since we are using Angular JS, let’s replace it with expressions. Following is the mark-up on the page in Angular’s style:

Open this page on a browser and the original stock ticker page on another browser window and play with the buttons. You will see both the screens with same data at any given point of time. The only difference would be the state of buttons, colour and scrolling list. We will fix them in the next post.

ASP.NET SignalR is a great framework to do real-time communication. I love this framework and I wrote some posts on it in the past. On the other hand, we have Angular JS, the super-heroic JavaScript library to build rich web applications. How about using these frameworks together to build an application with data getting pushed from server continuously and binding it on UI with nicely architected JavaScript code? It definitely sounds great. Let’s see it in action.

In this post, we will create a simple Hello World kind of application using SignalR and Angular JS. We will look at a more advanced scenario in a future post.

Creating Hub
Open Visual Studio (2010 or 2012) and create a new web application. Add SignalR’s NuGet package to this project. Add SignalR route to the Application_Start event of Global.asax as shown below:

On client side
A client can communicate with hub either using a proxy script generated by SignalR or without using proxy. I personally like the no-proxy approach, as it is easier to take control over certain things when we follow this approach. In an Angular JS application, it is always recommended to wrap calls to data sources in a separate service. In such service, we need to take control to add callbacks easily. For this reason, we will follow the no-proxy approach. Following are the scripts required on the page:

The page will have a button and a span. When someone clicks on the button, method on the hub will be called to send a greeting message to all clients, which will be displayed on the span. Following is the mark-up on the page:

As stated earlier, the recommended way to call any external data source in Angular JS is using a custom service. We can create a factory or service to solve this purpose. In the following snippet, we create a new module and add a factory performing all SignalR operations to it:

Notice the callback passed to initialize method. This callback is a function defined in controller to set data received from server to a scope variable.

Also, notice the way the callback is invoked in proxy.on(). It is wrapped inside $rootScope.$apply(). This is because, the callback of proxy.on() gets executed outside Angular’s realm. Model modification done inside this function will not be processed unless it is called using $apply.

As you see, the controller is pretty straight forward. As everything gets kicked off from controller, we need an object of the custom service, which is injected into the controller. The controller invokes the initialize method of the service as soon as it is instantiated. This is to start the connection and configure proxy with required callbacks.

Now open the page created above on two different browsers and click on button in one of the browser. You should be able to see a greeting message with current time.

We have the interface IQueryable to support querying against remote collections. Any collection that doesn’t reside in the program’s memory is a remote collection. It can be a table in the database, a collection exposed through a service or anything similar. Following listing shows signature of corresponding extension methods defined in IQueryable:

Notice the difference in the signatures of methods. Methods of IEnumerable accept Func and predicate, whereas the corresponding methods of IQueryable accept Expression<Func> and Expression<Predicate>.

The difference between Func and Expression<Func> is, Func is a delegate type and Expression<Func> is a data structure. An Expression is represented in the form of a tree. Each node of the tree contains some information which can be inspected. An expression can be created very easily using lambda. An example is shown below:

Expression<Func<int, bool>> compareExpression = (num) => num == 5;

Expression Tree Visualizer is a nice tool to view an expression in the form of a tree while debugging the application. To use it on a computer, one just needs to copy the library into Visual Studio visualizers folder. You can find the instructions in the codeplex site of the sample.

Following screenshot shows tree form of the expression defined above:

A simplified version of the above expression tree can be the following:

As we see, each node contains an expression. In other words, each individual part of an expression is also an expression. These expression types are defined in the namespace System.Linq.Expressions. This means, we can create a lambda expression by hand. Following code snippet demonstrates it:

If you view the above created lambdaCompareExpression using Expression Tree Visualizer, you should be able to see the same tree structure as of the previous expression. This expression can be used to query select all 5’s from an array of integers as follows:

The collection nums will have 4 5’s after execution of the above statement.
As you saw, it takes quite a bit of work to create and use expressions by hand. But it is important to understand how an expression is formed and its components as we use them almost everyday. Following are some of the scenarios where expressions are used:

Features like automatic paging and sorting list data with model binding in ASP.NET 4.5 Web Forms

Expressions are heavily used in .NET framework to provide a friendly interface to the programmers. While writing queries against LINQ to SQL or Entity Framework we feel as if the queries fetch data from in-memory collection. But there is a lot of work done under the covers. Data is extracted from each expression in the query and a SQL query is formed based on the information gathered. This query is fired against the database to fetch data.

About Me

I am a software developer working on and passionate about Microsoft Technologies and anything new in the Web world. Lately, spending a lot of time with JavaScript and finding it much deeper than what I knew for past few years. I enjoy writing code and writing about code. My contribution to community earned me a Microsoft MVP award (ASP.NET/IIS) and a DZone MVB award. When not in front of computers, like to spend time with melodious Hindi and Telugu tunes or watching Cricket