What is SignalR and why should I use it?

When I first heard about SignalR, I was not sure what was the point of it. The official description says that SignalR is a library that can be used with any ASP.NET application to add real-time communication. But since what they meant by real-time was not totally clear to me, and the only example was a chat room, I pushed it aside for a while.

When I started to work on my side project, I also started thinking about SignalR again. One of the things I want to was refresh the schedule as soon as a change was made: if a user makes a modification, it should be visible to all other users. The classic way to do something like that would be to call the server at regular intervals to get the status of the schedule, but to have pseudo real-time update your must call the server pretty often.

With SignalR, the server can call a JavaScript methods on all the clients by itself when updates are required. The library will handle the connection needed to achieve this: by default WebSocket is used, but it will fallback automatically to older connections types if WebSocket is not available in the browser. The JavaScript can also call the server: this can already be done with AJAX, but if two-way communication is needed it may be easier and cleaner to do it all with SignalR.

So, using a real-time library is the way to go if you want to build an application that requires collaboration between users. Common uses cases includes editors, social networks, chats or a schedule like my project.

Getting started wtih SignalR is pretty simple. Here is an example with my side project: sessions for an event can be modified by any user, and when a session is modified the change is visible for all the user currently logged in the application.

On the server
First, you must add the Microsoft ASP.NET SignalR package to your ASP.NET application using NuGet, along with the jQuery package if you don’t already have it.

After this, you must create a class that derives from the Hub class. All the methods of the hub can be called from JavaScript. Also, those methods can call JavaScript methods on the client.

namespace EventScheduling
{
public class SessionsHub : Hub
   {
   public void SessionModified(ScheduledSession scheduledSession)
      {
      // Call the JavaScript method sendSessionChanged on all the clients
      Clients.All.sendSessionChanged(scheduledSession);
      }
   }
}

To enable communications between the hub and the JavaScript, you must also enable SignalR in the Configuration method in the Startup class of your application.

namespace EventScheduling
{
public class Startup
   {
   public void Configuration(IAppBuilder app)
      {
      app.MapSignalR();
      }
   }
}

On the client
On the client, you must include the jquery.signalR-2.2.0.js file containing the JavaScript for the SignalR library and the package ~/signalr/hubs. This package is automatically generated from your Hub classes and contains all the JavaScript required to call the server and receive message from the server.

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<script src="~/signalr/hubs"></script>

After this, when the page is loaded and ready, you must declare the JavaScript function called by the server-side code. Since the Hub class is called SessionsHub and the SessionModified method of the hub class calls the sendSessionChanged method, this function must be declared in the $.connection.sessionsHub.client.sendSessionChanged variable.

Once this function is created, you must also connect to the hubs using the $.connection.hub.start method. You can also add initialization code in the done() callback which will be called when the connection is started.

$(document).ready(function () {
   // Create a function that the hub can call to broadcast messages.
   $.connection.sessionsHub.client.sendSessionChanged = function (session) {
      // Display the session again using the new data received from the server
      });
   };

   // Start the connection and create a function that the hub will call when loaded
   $.connection.hub.start().done($("#Sessions").on("click", ".Session", function (event) {
      var that = $(this);
      var currentSession = that.data("session");
      currentSession.Title = currentSession.Title + "Clicked";
      // Call the server, which will notify all clients of the change in the title
      $.connection.sessionsHub.server.sessionModified(currentSession);
   }));
});

In the example, when the hubs are done starting, a click handler is added to each session on the page. When the users clicks a session, the word Clicked is added to the title of that session, and all browsers showing the page are notified. Since the SessionModified method was declared in the SessionsHub class of the server, it can be called from JavaScript using using the $.connection.sessionsHub.server.sessionModified method.

With only this small bit of code, you now have two-way communications between the client and the server, which you can use to update data in real-time for your users. I will use SignalR in future projects that’s for sure!

Sign up now to get my newest articles about making applications and my ongoing side project delivered straight to your inbox.

Getting started with the Loneman’s Coder Methodology

I’ve embarked on a side project to develop an event scheduler without much planning, but every good software project needs a methodology. Since no methodology I know really suits what I’m doing, and because the world of software really needs yet another methodology, I’ll share mine here.

This methodology will be called the Loneman’s Coder Methodology in the spirit of the rugged pioneers of coding. The basic idea of this is that I’m working alone and not with a team, so my way of working should be adapted to this reality. I can leverage the power of the Internet to find solutions to my problems, but there is no other person than me that can deal with it. Also, I’m working on a product and not a project for a single client: I’m the one making the call about which features needs to go in the product.

CindyLonemanCoder

So, to prepare for my coding journey, I’ll be going through the following steps to maximize my chance of technical success and waste as little time as possible:

  • Defining the quest: To go somewhere meaningful, you need to have a clear idea of where you’re going so you’re not wandering aimlessly around. In my case, I already defined my quest: I want to build event scheduling software for conferences.
  • Painting a pretty picture: To make your path even clearer, you should mock the important parts of your product so you have something to work from. In you head, everything may fit correctly, but reality has a way of foiling expectations. It’s better to find out from a mockup that your concept is impossible than from a few weeks of coding the UI. You can check out the mockup I did for my own product in the post defining my project.
  • Testing the moving parts: You should prototypes the parts that you are not sure about and that are vital to your product so you don’t fall in the Pits of Technical Risk just when you were starting to get somewhere. This may be an unnecessary step if you’re already familiar with every technology and pattern you’re planning on using, but for most projects there is a least one or two thing really worth testing. That way, you can start coding at full speed later without having to worry too much about what’s lurking in the corner. I already wrote about the prototypes I planned in my previous blog post.
  • Writing a map: You need to map out what is needed to get your product to a usable state. Each task or feature should be kept small so you can complete it fast and keep the momentum going, especially if you’re working on this in your spare time like me. I’ll start planning my tasks when I’m done prototyping since I’ll have a better idea what needs to be done and how long it will probably take.

When everything is ready, I’ll finally be able to jump into it and build the real thing. For now, I’ll be starting with the following guidelines. Since I have not reached this part of the project yet, I’ll have to make sure this evolves as I learn new things.

  • Crank out the code: This is where you put your nose to the grindstone and do the real work of writing the code for a small feature on your map. Since all the parts in the map should be important for the final product, you should work on the task that’s best suited to your current energy level and motivation to optimize your efforts.
  • Journal your journey: I don’t believe in zero documentation. Having just enough documentation so you can remember why you did something can be very useful, especially for a project that’s worked on in small units of spare time stretched out over a long period. Since you’re working alone, you won’t have a team to help you remember, so anything you don’t remember and didn’t document is be lost forever. It doesn’t need to be long and boring: for my project, the documentation will mostly be blog posts like this one.
  • Focusing on workmanship: Each feature should be complete in itself and work without breaking anything else. What you’ll be making here is only the start, so you need to make sure you reach the end of the road with good, maintainable code. It’s better to have a few features that works well and that are properly documented than a few half-baked things that will break the first time a user tries something a bit different than what you planned.

After all of this is done, I’ll hopefully be able to ride into the sunset with a good software product that’s in a usable state. This will only be the beginning of the rest of the life of the software: the quest for users will start and the software will need to be maintained, which is a completely different game. Sign up to my newsletter to stay tuned until then, there are still a lot of steps to complete!

New post on Medium : Working one day at a time

For this week, I wrote a post on Medium about working one day at a time and the habits my side project, EventScheduling.io, is teaching me. This is my first post on Medium, you can check it out here:

https://medium.com/@CindyPtn/working-one-day-at-a-time-88e27e734617

I’m still working on prototypes with SignalR for real-time page refresh and it’s going well, I’m going to write about it soon.

The next item on the list is narrowing down the list of JavaScript framework to evaluate to something manageable. What is your favorite framework to use with ASP.NET MVC? I’m looking to use a framework mostly to handle refreshing many parts of the page with the same information.