Monday, 26 August 2013


SignalR .net

In this post I am sharing magical stuff which I have learned recently and it will be very useful..Let's dive!!!

SignalR is a groundbreaking open-source project from .NET community. It offers real-time communication to a variety of platforms, is easy to use and to set up, and scales immensely.

Initially it was developed for and later it was scaled to Silverlight and WPF technologies for real time notification/Push mechanism.Pushing data from the server to the client (not just browser clients) has always been a tough problem. SignalR makes it dead easy and handles all the heavy lifting for you.

What is ASP.NET SignalR?

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time.

You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same.

SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients' browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

What can you do with ASP.NET SignalR?

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements Ajax long polling to retrieve new data, is candidate for using SignalR.

It also enables completely new types of applications, that require high frequency updates from the server, e.g. real-time gaming. ShootR game is a great example

For more information and about the latest news you can go to SignalR.

I have did a beginning hands on code which was inspired from the instruction video.The example is to move a rectangular shape in one client and that has to reflect in all the connected clients(browser).The server and the client side code are in the same project.Client code will be in Javascript file and Server code is in C#.Before trying out the sample please install the SignalR package into your project.To install SignalR refer Getting SignalR-Ready.

Step 1:

Create a new empty web application and Right click the project and click Manage NuGet Packages.Then search for SignalR and install the ASP.Net SignalR sample now the sample stockticker application will be downloaded into your application and that will compile successfully and now create a folder MoveShapeDemo and create the 3 files as shown in the second image.

Manage Nuget Package

MoveShapeDemo Files

Step 2:

Now you can code your server side code in MoveShape.cs file as show in the image below.Please see the comment in the code for your better understanding.

Step 3:

Now you can code your client side code in MoveShape.js file as show in the image below.
Please see the comment in the code for your better understanding.

Step 4 :

Now you can code you view(HTML) page in MoveShape.htm file as show in the image below.
Please see the comment in the code for your better understanding.

That's you can run your application in browser (IE > 8) at least 2 browser and then try it by moving the square in one browser and that should reflect in the other clients(browsers) too.

Hope you enjoyed this post.

Thanks for Reading.Happy Coding!!

Tuesday, 26 March 2013

A CPU Friendly Infinite loop in C#

To run a infinite loop to do some process, we will be using While loop,System.Threading,System.Timer and so on.., each of this having its own pro's and con's and some of that will trash the CPU performance.

In this blog I am going to post the simple technique and that will utilize less CPU.To achieve this we have to use EventWaitHandle from System.Threading class.The following example will show the usage.

C# Console app Example :

private static void Main(string[] args)
EventWaitHandle waithandler = new EventWaitHandle(false, EventResetMode.AutoReset, Guid.NewGuid().ToString());do
// ToDo: Something else if desired.
} while (true);

The above example will print the " Entered " word with every one second delay interval and infinitely.

If you want to do the same in Asynchronous way ,there are lot of ways to do and you can find one of the  method in the below example.

C# Console app Example(Asynchronously) :

//Declare a delegate for Async operation.

public delegate void AsyncMethodCaller();
class Program
private static void Main(string[] args)
           // Create the delegate.

            AsyncMethodCaller caller = new AsyncMethodCaller(Program.AsyncKeepAlive);
            // Initiate the asychronous call.
            IAsyncResult result = caller.BeginInvoke(null, null);}

private static void AsyncKeepAlive()

EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, Guid.NewGuid().ToString());

 // ToDo: Something else if desired.
 } while (true);



Hope you enjoyed this post.
Thanks for Reading.Happy Coding!!

Friday, 1 March 2013


After a long time again back with some web apps stuffs and got time to share my studies on Knockout JS a JavaScript library.

Introduction to Knockout:

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

  • Elegant dependency tracking - automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings - a simple and obvious way to connect parts of your UI to your data model. You can construct a complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Trivially extensible - implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.
  • Pure JavaScript library - works with any server or client-side technology
  • Can be added on top of your existing web application without requiring major architectural changes
  • Compact - around 13kb after gzipping
  • Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others)
  • Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms
For more information you can refer here.


This blog will gives you a glance at what is Knockout, why to use it and how to use it. If you are a newcomer to KO or if you are juggling between multiple JS libraries, this cheat-sheet is a handy guide to get your KO karma flowing.

  • Knockout is a JavaScript Library (as opposed to Backbone.js which is a framework) that helps you improve the User Experience of your web application. 

  • Knockout provides two way data-binding using a ViewModel and provides DOM Templating, it doesn’t deal with sending data over to server or routing.

  • You use Knockout as a drop-in enhancement library to improve usability and user experience, whereas Framework like Backbone is used ground up in new applications (Single Page Apps is a good example).

  • You can create a KO ViewModel as a JavaScript object or as a Function (known as prototype). It’s outside the jQuery document ready.

  • ViewModel as a function
                   var myViewModel = function() {
                              this.Email = “”;
                              this.Name = “Sumit”;
                              this.LastName = “Maitra”;
                              this.WebSite = “”; }

  • ViewModel as an object: you can follow the JavaScript Object Notation –
                var myViewModel = {
                            Email: “”,
                            Name: “Sumit”,
                            LastName: “Maitra”

  • Observable Properties are functions: When dealing with observable values you have to end the property with parenthesis like a function call, because computed values are actually functions that need to be evaluated on bind.
  • Applying a ViewModel
              // In case the View Model is defined as a function
                    ko.applyBindings(new orderViewModel());
              // In case the View Model is defined as a JSON Object

             Here ko is the global reference to Knockout that you get once you add Knockout                                                  Script reference in your page.

  • Observable Properties: KO has the concept Observable properties. If you define a property as an observable, then DOM elements bound to it, will be updated as soon as the property changes.
                   var myViewMode = {
                                 Email: ko.observable(“”)

  • Observable Arrays: When you define an array of Json objects as Observable, KO refreshes DOM elements bound to it when items are added or removed from the Array.
                           var orderViewModels = function() {
                                 // Binds to an empty array
                                  this.Address = ko.observableArray([]);

          Note: When properties of an Item in the array changes then KO does not raise ‘modified’ events.

  • Assign value to observables: We saw how to declare observable Properties above. But when we have to assign a value to an observable in JavaScript we assign it as if we are calling a function, for 

  • Simple Data Binding to properties
                  <input data-bind=“value : Email” />
                  Value of input element to the Email in the ViewModel.

  • Binding to Computed Values: Binding KO to a function gives you added flexibility of defining methods that do computation and return a computed value. KO can actually bind DOM elements to these methods as well.
       For example if we wanted to bind First Name and Last Name and show it in a single    DOM element we could do something like this:
On the View Model

                        var myViewModel = function() {
                        this.Email = “”;                        this.Name = “Sumit”;                        this.LastName = “Maitra”;                        this.FullName = ko.computed(function () {                        return this.LastName() + “, ” + this.Name();                        }, this);                        }

       Binding to DOM Element

                        <label data-bind= “text: FullName” />
  • Binding to an array of objects: KO can bind the DOM to an array in the view Model. We use KO’s foreach syntax as follows
                        <table>                        <tbody data-bind= “foreach: Address”>                                                </tbody>                        </table>

        You can do the same for an Ordered <ol> List or an Unordered List <ul> too. Once you have done the foreach binding, KO treats anything DOM element inside as a part of a template that’s repeated as many times as the number of elements items in the list to which it is bound.
  • Binding elements of an array: Once you have bound an Array to a DOM element KO gives you each element in the array to bind against. So an Address object may be bound as follows:
                        <table>                        <tbody data-bind= “foreach: Address”>                        <tr> <td>                        Street: <label data-bind: “text: Street” />                        #: <label data-bind: “text: Number” />                        City: <label data-bind: “text: City” />                        State: <label data-bind: “text: State” />                        </td> </tr>                        </tbody>                        </table>
  • Binding to properties other than text and value: Now let’s say we want to bind the WebSite element of the ViewModel an anchor tag
                        <a data-bind=“attr : {href : WebSite}”>                        <span data-bind= “text: Name”</a>

      What we are doing here is using Knockout’s attribute binding technique to bind the ‘href’ attribute to the URL in the WebSite property of the View Model. Using attribute binding we can bind to any HTML attribute we Observable Properties: KO has the concept of want to.

  • Getting KO Context in jQuery: Now let’s say we want to have a Delete button for each address. The following markup will add a button 
                        <table>                        <tbody class=“addressList” data-bind= “foreach: Address”>                        <tr><td>                        Address: <label data-bind: “text: $parent.                        AddressString(Street, Number, City)” />                        </td> <td>                        <button class= “addressDeleter” ></button>                        </td> </tr>                        </tbody></table>

Now to handle the click even using jQuery. Since the button is generated on KO binding we cannot use the normal click handler assignment of jQuery. Instead we use the parent container and assign a delegate as follows

                        $(“#addressList”).delegate(“.noteDeleter”, “click”,                        function() {                        var address = ko.dataFor(this);                        // send the address to the server and delete it                        });

As we can see above the ko.dataFor(this) helper method in KO returns the object that was bound to that particular row of data. So it returns an Address object. If you need the entire ViewModel you can use ko.contextFor(this).

Thanks for reading.Happy coding!!!!