Saturday, March 21, 2015

Real time data update using SignalR

In my last article, we discussed about the concept of SignalR and how we can use it to create a simple web based group chat. It included a good deal of explanation of how SignalR works and why it is a good candidate to create a real time application. We will not get into details again and before you start with it, I would recommend you to read my previous article here. Our this discussion will be another practical implementation of what we had learnt in the last article.
Let's create another sample application to understand the use of SignalR. This application will be an html page, which displays some data from the database.  At the back-end of this sample, we will have another application, say any form, windows service or RSS feed, which will insert the new data into the database. As soon as the new data is added to the database, that will be reflected on this html page.
An important point before we start the discussion is that this example will not only use the SignalR, but also the concept of SqlDependency, so that our server hub get's notified about any change in the database and broadcast the latest data to the users. To describe the logic briefly, our hub will subscribe to SqlServer for any change in its data in the database, get notified, fetch the latest data and broadcast it to the html page. So our application will consist of following 3 separate components.
§  Sample table called Users in a Sql database, with its ServiceBroker enabled.
§  An application with a html page to display the list of users from the database. This application will also include
1.  A webapi which receive data from a third application and save it into the database.
2. A 
SignalR component to broadcast the latest data to the users.
§  An application with an html page to submit new data to the database by making calls to the webapi.
So our overall application flow will be like the following:

Database setup: Create a new table named Users, in a sample database. In order to use the SqlDepedency, we need to enable the ServiceBroker for the database. This can be done by using the following command:
 ALTER DATABASE Database_Name SET ENABLE_BROKER
or, from the UI by selecting the database, right click on its properties, go to the Options, navigate to the Service Broker section and change the value to True for Broker Enabled property.


Create the main application: This application will consist of following components:
1. Webapi to receive the data from the data feed application and save into the database.
2. An
 html page to display the data from the database.
2.
 SignalR component which will refresh the html page with latest data, as soon as the new data is added to the database.
Let's create a Webapi which can receive the data from the user and store it in the database. For this, we add the references to the WebApi2 and OWIN packages, using the nuget package manager. Once the references are added, we add a new class file of type Web API Controller class. Let's call it DataFeedController.cs. Add a POST method to receive the data from the user and store it in the database, using the entity framework.So our controller would look like below:

Now in order to host the Webapi and SignalR, we add a file named Startup.cs and add the routing template for Webapi and register both the webapi and SignalR to the OWIN pipeline. When we start the application, it will result in hosting of the Webapi at the back-end.

Now in order to add the real-time functionality to the application we add a class named RealtimeDataHub.cs, derived from the Hub class and will be used as a middleware between the database and the html page (which is used to display the data). This class will have a method named GetUsers() which will get the data from the database and broadcast it to the connected users. Inside this method, the hub also subscribes to the sql for getting notifications for change in the database, using the OnDependency change event of the SqlDependency class. See the code below:

Create data feed application: Create a new  empty project and add an html page to it. This html page will have 3 textboxes and a button to store the data in the database, by calling the WebApi created in step 1 above. We will call it as data feeder application. In a real time scenario, we can have any windows service which is fetching data using some api and storing it in the database. So our html mark up will be like below:

Next, use the ajax call to send the data to the webapi controller, which stores it in the database.

Note that here we have used the localhost url to refer to the location where the web api is hosted. You can replace it with the actual url of the WebApi location.
So our setup is complete now. In order to start the application, first run the html page of the main application, which displays the data from the database. When this application is started, its corresponding web api also gets hosted. First time, there will be no data. So let's start the data feeder application also and add some data. Add the new data and Save it. As soon as the new data is added, it immediately gets reflected in the main applications home page. See below:

So now need to use timer based calls. Use the SignalR functionality and create real time applications. Hope you enjoyed reading it. Happy coding...!!!

Sunday, March 8, 2015

Implicit vs Explicit interface implementations in C#

It's a very small but very important concept to be learnt. It's very normal to use the interfaces in our applications. But at the same time, it's very important to make sure that these interfaces are implemented correctly. So whenever we implement an interface in C#, we get two different to implement it i.e. either Implicitly or Explicitly:

But what's the difference between the two. To understand it in better way, let's first create two classes and implement an interface implicitly for ClassA and explicitly for ClassB.

Now let's create another class ClassC and try to access the GetData method of both these classes i.e. ClassA and ClassB. Can we access that method for both ? See the code below:

We can do it for ClassA but not for ClassB. This is the main difference between the two implementations. For any explicitly implemented interface, you cannot access the interface methods until you create the instance of the class to be of particular interface type. Now let's instantiate the ClassB instance as ISampleInterface type and try to access the method.

This time it's accessible. Now the question is when to use explicit interface implementation. Following are some of the points that can help us to decide which to use when.
1.  Suppose you have a DLL of some API for your clients. This includes a class which implements two interfaces ISampleA and ISampleB. ISampleA is using the methods of ISampleB for some functionality, however the client has no concern with ISampleB methods as he is using ISampleA. Now is this wise enough to expose the methods of ISampleB through the use of the implicit interface implementation. So the idea should be to use implicit implementation for ISampleA and explicit implementation for ISampleB.
But of-course, if the client get's to know about ISampleB interface, he can create the instance of the class to be of type ISampleB and access its methods.
2. Another scenario, both your interfaces have a common method GetData() or even your class has a method named GetData(). Implicit implementation of interfaces will not allow you to do this. You will error something like the one below:
The call is ambiguous between the following methods or properties: 'InterfaceImplementations.ClassA.GetData()' and 'InterfaceImplementations.ClassA.GetData()' 
So these are two cases which I think help you decide whether to use implicit or explicit interface implementation.If you have any other than do share with us. Happy coding...!!!

Thursday, March 5, 2015

Tuples in C#

Any function we use in C# can return maximum of single value which can be string, int or any other type, as per our requirements. If more than one value is to be returned, we use different types of approaches, like using any Dictionary with key-value pair, or any new container class, with properties of this class being the data/parameters we would like to be returned from that function or use the out or ref based parameters. All these are good if they are fulfilling our requirements. But C# provides a Tuple class, which can be used as more efficient way of returning multiple values from a function.
Tuples were introduced in C# 4.0. In simple terms, you can define a tuple as a single record of different types of data. For example, a single record with UserId, FirstName, LastName, Salary etc can be called as a tuple. It's not necessary that all these attributes are of the same user. UserId can be of one user, FirstName could be of another user, Salary could be of third user and so on.
Enough of theory, let's do some practical. There are two different ways how a tuple can be created. First is simply creating a new instance of the Tuple class and explicitly specifying the types of elements this tuple can have. The values to be stored in this tuple are passed in its parameterized constructor. See the code below:



Accessing the parameters is very easy. Just use _tuple.Item1, tuple.Item2 where Item1 and Item2 are the elements at the first and second position of the tuple. See the code below:

So the complete code becomes:



Another way to create a tuple is use the 
Create method of the tuple class. However, the method to access the elements remains the same. See the code below:

So these were two different ways of creating a tuple. An important point, there is a limit of 7 elements that a tuple can hold. The eighth element can only be another tuple. Although if you try to declare an eighth element of any type other than a tuple type, there will be no compile time error. But it will break at run-time with the error:
The last element of an eight element tuple must be a Tuple
So if you need to have more than 7 elements in a tuple, you can use the eighth placeholder as a nested tuple. To access its element, you have a property named Rest, which further contains the elements of the nested tuple as Item1, Item2 etc. See the code below:

So this was about the concept of tuples. Hope it helps you. Happy coding...!!!

Sunday, March 1, 2015

WebAPI self hosting using OWIN

In one of my previous articles, we discussed `. Continuing on the same paths, we will now discuss how we can self host the web api, using OWIN custom host. So let's start with it.
Add a new Console application and let's call it WebAPIOWINHosting.

Next, in order to create a webapi and use OWIN custom host, we add references to Microsoft.AspNet.WebApi.OwinSelfHost, using nuget package manager. This will not only add the references for the webapi but also the OWIN components, along with the other required dependencies.


Add a new webapi controller class. We remove all the methods and add a simple GET method to get sum of two random numbers.




Add a new class named Startup.cs. This is as per the OWIN specifications. Use the HttpConfiguration class to create the webapi routing template and add it to the request pipeline using the appBuilder.UseWebApi method, where appBuilder is of type IAppBuilder.

Open the Program.cs file and start the server using the WebApp.Start method, spcifying StartUp class as the entry point for the settings required. This is the OWIN specification of starting the server in the custom host.

Now simply run the application and the server is started. 



To test the webapi, we will use the Chrome browser Postman extension. So enter the url of the webapi, which we specified in the Program.cs and Send the request. See the results are received.

Easy to host, isn't it. If you learnt it than do share it. Source code of the example is also attached here. Happy coding...!!!