Chat application using ASP.Net Signal R

ASP.Net SignalR is one of the major revolution in the development technology world these days for creating real time applications. Consider an application having a page where you are required to update the user interface with the latest data, as soon as it is available. Such applications are said to be real time applications, where the UI gets updated as soon as the latest data is available for the user.

Best example, a stock market application has to keep updating the user interface with the data as soon as stock rates are changed. Another example is a chat application, which updates the receiver with the latest message, from the sender. Some of the techniques could be making timer based requests to the server, for getting the data or use the concept of polling to get the data. A good alternative to these, is the use of SignalR. 

As we now that our model of the web applications mainly consists of a server, which hosts the application and the client, representing the end users of the applications.For creating SignalR based applications, we need to create a hub on the server, which is responsible for updating the client or the ,end users, with the latest data. This hub is nothing but a simple class inheriting from the Hub class. At the client end, we get an automatically generated javascript based proxy file (at run time), which can be used by the client for connecting with the hub. Client code also contains a javascript function, which the hub uses to provide them latest data. See the image below:

Chat application using SignalR

To explain this process in detail, our hub directly calls the client javascript functions, to provide the latest data. On the other hand, by using the auto generated javascript proxy file at the client end, client code can uses this proxy, to call the methods of the server hub, if required. The term if required is used here deliberately with the fact that client may not be required to call the hub. For example, in an application where we have user dashboard with some data from database, we can use the concept of SqlDependency and SignalR to keep the user interface updated, whenever there is any change in the database records. In this case, the client is not required to make any calls to the server for getting the updates. On the other hand, if we have a chat application, the client code will call the server hub and forward the message. Hub will than broadcast this message to the users of the application, by calling javascript method of the clients.

One very important point from the above paragraph is that the client never calls the hub for getting the latest data. Client may only call the hub so that hub can forward the message to the other connected clients. If the client code would need to make the calls for latest data to the server, than the whole purpose of using the SignalR fails and we could have used the old concepts of timer or page refresh for this.

Simple group chat application in 15 minutes using SignalR:

Yes, that’s correct. Once you are aware of the basic concept/flow of SignalR, you can do it very easily. We will be now creating a group chat, without use of any database. If we think about the flow of the application, this whole process requires a client to send message to the server, which will broadcast this message to the all the connected client users. So the server needs to have a component which can broadcast the message to the clients. This role is played by the hub class. This is the example, where the client needs to call the server hub. Let’s try to visualize this process and than we will create the application.


Create a new project named SignalRChat. Add the references to the SignalR libraries using nuget. It will automatically add the references to the OWIN hosting option libraries which allows to add the the SignalR application to the OWIN pipeline. Apart from the server libraries, it also adds client libraries required for using SignalR. See the references get added below:

Chat application using SignalR

Create OWIN host for the application

We will be using the OWIN based hosting, to host this application. Without going into depth of the OWIN hosting, let’s add a class named Startup.cs. The name has to be the Startup as per the OWIN based hosting specifications and its namespace must be decorated with the assembly attribute, specifying that Startup assembly is the starting point of the application. Next we define a method named Configuration and register the SignalR in the OWIN pipeline using app.MapSignalR().

Chat application using SignalR

Create the Hub on the server

Our next step is to create the hub on the server which is nothing but a class file. We will name it as SignalRChatHub and derive from the Hub class. It will contain a method named BroadCastMessage, with 2 parameters. Client code will use this method (using the proxy generated at its end) for communication with the hub, and the parameters as the data to be sent to the hub. Inside this method, use the Clients property of the Hub class to call the client side function. This function is a simple javascript function, which will receive the data sent by the hub and update the chat window of the user. We will define a function with the name receiveMessage at the client end (later in the code). So for now, we will use this method name.

Chat application using SignalR

A point to be noted here is that the we will not get any intellisense help for the client methods, of-course. This method will be dynamically resolved. See the image below:

Chat application using SignalR

Setup the Client code

Server setup is done. Now, we will add an html page named ChatWindow.html which will be our chat window for the user. Also we add the references to the jquery-1.6.4.min.js and jquery.signalR-2.2.0 .min,js on this pagewhich were added by the nuget package managerEarlier we discussed that SignalR automatically generates a proxy class at run time, for client code, to connect with the hub. So we also need to reference to this file. As this file is generated at run time, it does not exist physically for us. As per the SignalR tutorials on the official website, it states:

SignalR creates the JavaScript code for the proxy on the fly and serves it to the client in response to the "/signalr/hubs" URL.

So we need to add this reference also.

Chat application using SignalR

We also have the option to disable this auto-generated proxy file generation (which is out of scope for this discussion) and create the proxy ourselves. In that case, we need to reference that file accordingly. Next, let’s add some html mark-up to generate the chat window and design it using css styling.

Chat application using SignalR

Now its time for client code to connect with the hub and send the message, so that hub can broadcast to all the users. For this, we first get the proxy instance in a variable named chatProxy.Note the camel case syntax of the client code below. This is the convention to be followed while creating the SignalR application. For detailed specifications, I would recommend you to check out the official SignalR website. Without going further into the details, let’s move forward with the code. Here, signalRChatHub is the name of the hub on the server (that we created on the server earlier).

Chat application using SignalRNext, we attach the button click event (button to send message to the users), when the connection to hub is successfully started. This event will call the method of the hub, using the proxy instance, which will be receive the message and broadcast it to users. See the code below:

Chat application using SignalR

We also declare the function to which the hub will call, when it needs to update all the users with the message received. This is the function name we referred to, from the hub method, at the start of the discussion. So this function acts as a type of callback function here.

Chat application using SignalR

So all the client code is also setup and we can now run the application. So our complete client code will now looks like:

Chat application using SignalR

Now we can run the application. Copy the url and open another instance of the browser or any other browser and we can start chatting.

Chat application using SignalR

Wasn’t that easy ? So we have our own chat messenger. Happy coding…!!!

Posted in advanced concepts & industry trends, SignalR | Tagged | Leave a comment

Coalescing operator ?? in C#

?? operator in C# is a binary operator. It is also called as null coalescing operator, which returns the left hand operand if it has any value, else, returns the right hand operator. Confused, let’s see an example for this.

Suppose we have a property UserId of type int and nullable in nature. While using this property, if it has any value i.e. Not Null, then use that value, else, use some other value. So first thing that comes to mind is use the if-else, something like below:

Null Coalescing operator in C#

Null coalescing operator provides a very shorthand syntax for this, which changes the code to:

Null Coalescing operator in C#

Easy and concise to use. Happy coding…!!!

Posted in C#, Interview Questions | Tagged | Leave a comment

CORS in Web API 2

In my previous article, we discussed about the concept of Route and RoutePrefix, which was introduced as a new feature in WebApi2. Continuing on the same lines, we will now discuss about the concept of Cross Origin Resource Sharing or C.O.R.S.

CORS is a concept about permissions to make cross domain ajax calls. Before we move further, let’s understand the concept of cross domain:

Two domains can be called as different domains:

1. When they differ in schemes (i.e. http or https)
2. When they have different port numbers
3. When they have different domains or sub-domains.

In normal scenarios, an ajax call cannot be made to a resource on another domain, until the content-type is set to jsonp. Same is the case when we try to make an ajax call to a webapi in different domain. When you try to make a call to a web api hosted on another domain, than you will get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:34290/GetString?_=1420815804319. This can be fixed by moving the resource to the same domain or enabling CORS.

In order to enable cross domain request in webapi, we need to add the reference to the Microsoft ASP.Net Web API 2.2 Cross-Origin Support libraries, apart from the basic webapi libraries.

CORS in WebAPI 2

Next, in order to test this implementation, we will create a new WebApiController (in an MVC application) and a client application with an HTML page, which will send requests to this webapi. To start with, we will first try to see the issue in making cross domain ajax calls in webapi. Than we will enable the CORS feature and see the results. So let’s start by creating a webapi controller.

CORS in WebAPI 2

Next, we remove all the methods in the default api controller and add a simple method GetString, which returns a string.

CORS in WebAPI 2

Run the MVC application. This will result in hosting of the webapi on the same local development port, as the normal mvc application. Now, we add a client application and make an ajax request to the webapi url. So our code becomes:

CORS in WebAPI 2

Run the client application and also open the browser console and see the message we receive.

CORS in WebAPI 2This is the message that we discussed above in the start. An important point to note here is that your request will be hit to the web api. If you add a break-point on the webapi method it will be hit. But the response is blocked by the browser, as per the CORS policy.

In order to enable the cross domain request, we add the following code in the Register method of the WebAPIConfig.cs file.

 config.EnableCors(new EnableCorsAttribute("*", "*", "GET"));

Let’s first test the request and see the results. Than we will discuss what exactly this function does. So send the client request again and see the results.

CORS in WebAPI 2

So now we can see the results. Remember, the request gets sent and hits the api even without enabling this feature, but the issue is, we cannot see the results until this feature is enabled. So let’s discuss the statement that enabled this feature.

To start with the, config.EnableCors enables the api to receive the requests from other domains. We can do this at controller action level, entire controller level or globally on all the controllers.

EnableCors() overload with no parameter:

When we pass no parameter to this function, than we must add [EnableCorsattribute explicitily, on the api action, on which we would like to allow the cross domain requests. Simply adding the config.EnableCors at the WebApiConfig.cs level will not work.

We can also set this attribute on the controller level. In such a case, we expose all the methods of the controller to the ajax requests from outside its domains. So what if you need to disable this for one of controller method. In that case, add [DisableCors] attribute on that method.

When we enable this feature using the [EnableCors] at the controller or action level, we also need to set certain parameters, which include:

1. origins: Specifies the url from which we want to get cross domain requests. Can add multiple values in comma separated format.
2. headers: Specifies the author request headers allowed
3. methods: Specifies the type of request i.e. GET, POST, PUT etc, which should be enabled on this method.

See the code below, we enable the CORS feature in WebApiConfig.cs with no parameter and add the [EnableCors] parameter at the action level.

CORS in WebAPI 2

EnableCors() overload with parameter:

This is the version of the function which we used earlier in the start of the discussion. This will enable the cross domain access at the global level i.e. on all the api controllers, until we apply [DisableCors] attribute explicitly on the controller actions. So let’s add these settings at global level.

CORS in WebAPI 2

Here, the use of “*” means ALL, i.e. all origins types are allowed to make requests to this api, all the header types are allowed and GET request types from another domain are allowed.

Let’s test the code with [DisableCors]  attribute and global configuration to enable cross domain requests. So our code becomes:

CORS in WebAPI 2

As we have disabled the request for the method named GetSecondString(), it again results in error related to cross domain policy for this method. However, call to the method GetFirstString() works as expected. See the results for request to the second method:

CORS in WebAPI 2

And, the request for the first method works fine.

CORS in WebAPI 2

One very interesting issue you might face is that when you omit the {action} parameter in the routing template, it will cause issues, to have two or methods, with same signature and having the same type i.e. GET, POST etc. For ex, when you have two GET methods, named FindProduct and GetProduct, both taking a single input parameter of type int, than you will get the issue

"Multiple actions were found that match the request: FindProduct on type WebAPI.Controllers.ProductsControllerGetProduct on type ProductsController"

The reason being that when the action name is not specified, than it will have two methods of the same type GET. mapping to same type of parameters, and it will not be able to identify which method to be invoked. Change the signature of one of the methods, and it will work.

So this was about the feature of cross origin resource sharing in webapi.

Posted in ASP.Net web API | Tagged | Leave a comment

Route and Route prefix – Web API 2

Web api is the buzz in the market these days for providing rest based api’s. After its first release, further versions have been released, with version 2 being the one with some of the major changes. One of the very good feature introduced was the use of Attribute based routing of the web api requests. There were other feature also, but this feature is very big and useful in itself and our discussion will be for this only, in this article. Also, this article has its reference from a great write-up on this feature by Mike Wasson, here, which explains these features.

If you have worked with initial version webapi, you must be aware of concept of routing templates for the api controllers. But in its version 2, instead of defining routing templates in WebApiConfig.cs, we can define these templates at the method level i.e. on the methods of the web api controllers. This is possible through the use of the Route and RoutePrefix attributes, added to the webapi2. This does not means that we cannot use the routing template with convention of first release of webapi along with this. Both can be used side by side. So let’s discuss these.

Initial Code setup:

1. Create a new MVC web application, with web api template.
2. Add reference to the webapi2 libraries, using the nuget package.
3. Add the Postman google chrome extension (Instead of making any html or mvc page, we will be using this extension, to make the test requests to the web api)
4. In our default values controller added, clear all the methods, add a Employee class and a method to return list of employees. So our api controller will look like the following:

Route and Route Prefix in WebAPI 2

Next, open the WebApiConfig.cs file, remove the default routing templates and simply add   config.MapHttpAttributeRoutes() to enable the attribute based routing.

Route and Route Prefix in WebAPI 2

Run the application. As the application is started, it will also cause hosting of the web api on the same development server. Now start the Postman extension and add the web-api url with method name, to which we want to make REST based calls. Click Send and see the results we receive:

Route and Route Prefix in WebAPI 2

This is the result which was expected.

Route Prefix in Web API

Now, suppose we add another method to it with Route attribute as FindEmployee and we need both the methods to have a common prefix in the api request url, say Employee. So instead of adding this as prefix to Route attribute of both these methods, we add a common attribute at the class level, called RoutePrefix and set its value to required prefix i.e.Employee.  So our code now changes to:

Route and Route Prefix in WebAPI 2
Now, we can make request to both the controller methods with the same prefix Employee. See the requests below:

Route and Route Prefix in WebAPI 2

Override Route Prefix

Next we have a situation where we do not our second method to use the same prefix as the first method. One solution could be use of a separate api controller and add the method to it. But this is not a good solution as you may required to add more methods in future, which do not use this prefix. To achieve this, we have the option to prefix the Route attribute value with a tilde(~) sign at the method level, for which we do not want to have the common prefix. So we add the tilde sign to the second method and make a direct call to the method. See the code below:

Route and Route Prefix in WebAPI 2Now let’s send the request with the changed url’s and see the results.

Route and Route Prefix in WebAPI 2

Passing parameters in GET request

Now, let’s see how we can send parameters to the request url. For this, we will be required to change the Route template and add a placeholder in it, which will be replaced by the parameter from the GET request.

Route and Route Prefix in WebAPI 2

Now, let’s send the request and debug the code:

Route and Route Prefix in WebAPI 2

Bingo, we get the parameter in the code. We can also have a template, where the parameter placeholder is in between the url. So we can defined the Route template something like


Let’s change our url and send the request again.

Route and Route Prefix in WebAPI 2

That look’s great. This means we can name our url’s differently and hide the actual method names from the client code.

Constraints on URL parameters

We can even restrict the template placeholder to the type of parameter it can have. For ex, we can restrict that the request will be only served if the eid is greater than 10. Otherwise the request will not work. For this, we will apply multiple constraints in the same request:

1. Type of the parameter eid must be an integer
2. eid should be greater than 10

Let’s see how we can do this.
Route and Route Prefix in WebAPI 2

Simply specify the type along with the placeholder, separated by a colon(:). Now try to send the request with a value less than 10 and we get the 404 error.

Route and Route Prefix in WebAPI 2

Change the value to greater than equal to 10 and it starts working again.

Optional and Default parameters 

I was really about to end the discussion until I came to knew about it’s another great feature, using the optional parameters. But in this case, it becomes necessary to provide a default value to that parameter, in the method definition itself. For using optional parameters, we use the question mark(?) symbol to denote that it is an optional parameter. Let’s see how we can have optional parameters:

Route and Route Prefix in WebAPI 2

 So these were some of the great sub-features of the Route and RoutePrefix feature in web api2. Let’s summarize the features we discussed:

1. We have the Route attribute at the method level, to define routing templates.
2. We can define a common prefix for all the methods of the api controller, using RoutePrefix attribute.
3. We can override the RoutePrefix on a method, using the tilde(~) sign.
4. We can easily define parameterized templates in the attribute based routing
5. We can have parameters defined in-between the api request url
6. We can add certain constraints on the url parameters, i.e. their type or the values they can have, within the template itself.
7.  We can also have optional parameters in the methods, but with the condition that they must have a default value assigned to them.

So this was about the use of the Route and RoutePrefix attributes in webapi2. Hope you enjoyed reading it. Happy coding…!!!

Posted in ASP.Net web API | Tagged | Leave a comment

2014 in review

The stats helper monkeys prepared a 2014 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 16,000 times in 2014. If it were a concert at Sydney Opera House, it would take about 6 sold-out performances for that many people to see it.

Click here to see the complete report.

Posted in Events & Conferences | Leave a comment