Click here to Skip to main content
13,900,451 members
Click here to Skip to main content
Add your own
alternative version


81 bookmarked
Posted 18 Mar 2015
Licenced CPOL

Monitor windows services, ASP.Net code and more, using SignalR, NancyFx and WCF

, 19 Mar 2015
Rate this:
Please Sign up or sign in to vote.
Using a tri-stack of cool tools to give live insight into the usually darkened room of Windows Services and other remote server hosted code...


Windows services are long running processes that sit in the background doing their thing and not troubling anyone ... until they go wrong, and everyone starts scrambling. Services can be difficult to debug, and gaining insight into what is happening at a moment in time can be problematic. At best visibility is usually relegated to spitting messages into the EventLog or a database and hitting refresh a dozen times (unless you have a situation where you are able to hook into remote debug, but that's another story...). The same can be true of other systems (for example that are placed live on a remote server and then some unseen bug kicks in that cant be replicated in your test environment and then.... BANG! .. .oh dear, here we go again....  <yup, been there...>.

This article demonstrates how to use a combination of Windows Communication Foundation (WCF) to send messages from any part of a system, either local, or remote, and then use SignalR and NancyFX to display the message in real time to a user (or yourself, doing the DevOps thing) in a browser. In addition to giving live insight into processes, the framework can also be used to facilitate central logging, and other general message processing.


Over the years I have had the need to be able to have a more real-time "deep view" into Windows services, plugin modules, remote applications etc ... not by digging through log tables, but by having a cool dashboard that I could put up on the wall that is a live insight to my running services and servers. This doesn't quite go that far, but does form the basis of a framework that could easily be built out to make something Matrix-like!  

Heres an overview of the technologies used:

NancyFX -> this is a lightweight, drop-in web-server that is extremely easy to use. It is a framework for serving html page requests, and sending response. It is like IIS (Internet Information server), not MVC. The reason I use it in this case is that dont want to install IIS on the machine, and its self-contained within my service (or other app). It also comes without the heavy overhead that IIS has. IIS is great - but complete overkill for this particular type of job.

WCF and SignalR preform two different functions. WCF does a lot of heavy-lifting of FTP/HTTP/TCP/Enterprise-bus, etc and is extremly useful to getting messages from the outside world into one place.

SignalR does something very powerful, very simply - it enables bi-direcitonal communication between server and browser.

The overall the process is as follows:

  • WCF listens for incoming messages on named-pipe (but could be any protocol WCF supports)
  • On receipt of message, it passes the message to SignalR.
  • SignalR takes the message and broadcasts it to any connected clients in the browser.


I'm not going to go into the background of creating windows services etc - there's enough examples on CodeProject and the Interwebs in general. The best thing to do is download the code, restore any nuget packages and play with it!   What the article will do is show you how I put this solution together and talk you through the highlights, and possibilities.  ... ok, lets get stuck in ... its quite simple, and I'm sure you'll find a use for it :)


We have three main parts of the solution.

  • WCF to accept incoming messages
  • SignalR to send messages to the browser
  • NancyFX to act as a web-host to serve the data to the browser

In my service I have a start-up method where the scaffolding framework for these three components gets constructed. 

Because there is the very slight possibility that a message might come into the stack before I am setup to deal with it, I put things together in the following order (the comments make the code self explanatory):

public void DoStart()
    // setup SignalR on port 8059
    string url = "http://localhost:8059";
    // start SignalR
    // setup NancyFX on port 8080
    string URL = "http://localhost:8080";
    Nancyhost = new NancyHost(new Uri(URL));
    // start Nancy
    // setup WCF listening server
    // nb1
    ServiceHost host = new ServiceHost(
            new Uri[]{
            new Uri("net.pipe://localhost")
    // nb2
         new NetNamedPipeBinding(), "MessageHubEndPath");

There are two things to watch here:

(1) the serviceHost I am creating is using a simple class type I created called "MessageHub" ... its important when initiating the ServiceHost you use the implementation of your class, *not* the Interface (see next..)

(2) When adding the endpoint for your WCF host, you use the Interface, not the implementation (flip flop...)
Note that in this example I am using a "named pipe" as the message transport method. This is because in this instance I want to send inter-process messages between different services/possible asp code/desktop interaction etc. The beauty of WCF however is that you can use it to send/receive messages using a host of methods (named pipes, tcp, http,ftp....). The fantastic multiple protocol implementation of WCF makes it ideal for this project, especially if you want to scale it.

The message sink

For the sake of this article, I am keeping things simple. I assume that we have one or more services we want to monitor and get insight to. The first thing is to set up a simple interface to accept messages:

public interface IMessageHub
    void MessageRelay(string ServiceName, string ProcessName, string Message,
    LogMessageType LMType);

The contract is a simple method called MessageRelay that takes in for example the name of the Service sending the message, a process that's being executed, and some message you want to view/log.

We then construct a class to handle the incoming WCF

public class MessageHub : IMessageHub
    // this is the main method that gets called by the contract
    public void MessageRelay(string ServiceName, string ProcessName, string Message,
           LogMessageType LMType = LogMessageType.Broadcast)
        // depending on the message type received, we either use SignalR to send the
        // message to the browser, or log it, or both.
        if (LMType == LogMessageType.Broadcast)
            BroadcastMessage(ServiceName, ProcessName, Message);
        else if (LMType == LogMessageType.Log)
            LogMessage(ServiceName, ProcessName, Message);
        else if (LMType == LogMessageType.BroadcastAndLog)
            BroadcastMessage(ServiceName, ProcessName, Message);
            LogMessage(ServiceName, ProcessName, Message);

So - that's the setup and message receiving taken care of ... next we'll discuss the route part, SignalR in a bit more detail

The message router

To finish the class, we implement a simple broadcast of the message using SignalR

    // take the message and send it out to all listening browser clients
    private void BroadcastMessage(string ServiceName, string ProcessName,
             string Message) {
        var context = GlobalHost.ConnectionManager.GetHubContext<logmessagehub>();
        context.Clients.All.addMessage(ServiceName, ProcessName, Message);

    // simple method to log a message - into Log4Net for example
    private void LogMessage(string ServiceName, string ProcessName, string Message)
        // log the message here if necessary for example

Note what is happening in Broadcast message. We are telling SignalR to call a *REMOTE JAVASCRIPT METHOD* in the browser, called "addMessage". We grab the context of the SignalR hub:

var context = GlobalHost.ConnectionManager.GetHubContext<logmessagehub>();

and using that context, we then broadcast the message/data received, to the listening browser method...

context.Clients.All.addMessage(ServiceName, ProcessName, Message);

NB: In this example I haven't done anything about security, you need to implement that yourself.

There is one other part to note, and that is the SignalR "hub" class that hides away but is key. It provides the "context" that we hooked into earlier in the class.

public class LogMessageHub : Hub
    public void Send(string ServiceName, string ProcessName, string Message)
        Clients.All.addMessage(ServiceName, ProcessName, Message);

There is a *big fat gotcha* here to note!.... When we get to the browser and put the client part of the communications in place, we have to refer to the SignalR hub ... from the browser/Javascript side, we must LOWER the first letter of the method name... so instead of calling "LogMessageHub", we actually call "logMessageHub" (note the lowered first letter "l" !!!!)




The host

I use NancyFX as my light-weight embedded web-server of choice. There is a link at the bottom of this page to a more in-depth article on using NancyFX in services - if you are interested, please read it. The only real gotcha for Nancy, is to ensure that when you add resources that need to be accessed by the browser (ie: html pages, css, javascript, image files etc), these MUST be marked as "Copy to output directory - copy if newer" in the property pages. If you don't, Nancy cant see them (she's a bit blind that way).


The front-end

For the article, I have kept things simple. Rather than drop in gauges and charts and dials, we are simply flowing messages into a stack, and displaying this in a table. I am using an extremely well written and useful front-end table management tool called "" .. for simple implementations it is superb. It also has some plugins to enable the user to take table data and download it in CSV, Txt and PDF format among others - very useful.

We start with a simple html table, and then hook onto the table.

<table border="1" cellpadding="5" class="stripe" id="tblLogMessages">
            <th>Process name</th>

To hook DataTables onto the table, we initialise a small bit of Jquery goodness on document ready:
NB: heres a gocha... (wow, this is getting tiresome!) ...
... you MUST input the "thead" structure when declaring the table or it wont render correctly with the plugin. (this might change, but at time of writing this was as I found it)

$(function () {
    var logTable = $('#tblLogMessages').DataTable({
        dom: '<it<t>lp>',
        "sScrollY": 400,
        "tableTools": {
            "sSwfPath": "/swf/copy_csv_xls_pdf.swf"

There are a wealth of settings for DataTables, the ones I used are:

  • dom .. this allows me to control the layout of the tables, and place headers/footers etc.
  • sScrollY .. the scroll window size the table sits in
  • tableTools .. this is the DataTables plugin that permits export of data in CSV etc.

As I want the messages then they are added to the table, to show the most recent at the top of the table, I also initialised the ordering


SignalR goodness on the frontend

Ok, now we need to implement SignalR browser-side so the messages the MessageHub receives and sends out and shown to the user. Its really simple ....

(1) Ensure that you have a script in that points back to the host/ip and port SignalR is listening on (remember we set this up on the OnStartup method of the service)

<script src="http://localhost:8059/signalr/hubs"></script>


(2) Create a connection to the "SignalR HUB" on the server (this is the "context" we discussed earlier)

//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:8059/signalr";


(3) Create a proxy that references the hub
remember the lowering of the first letter of the server-side method name? .. heres where it comes in...

var messageSink = $.connection.logMessageHub;

(3) Finally, we will create a method *that can be called by the server via SignalR fairy-dust magic* (!) to broadcast messages... and kick it to start

messageSink.client.addMessage = function (serviceName, processName, message) {

var dt = moment().format("dddd, MMMM Do YYYY, h:mm:ss:SSS a");

if (Paused) {
    logTable.row.add([dt, serviceName, processName, message]);
else {
    logTable.row.add([dt, serviceName, processName, message]).draw();

// Start the connection.

In the method above, instead of directly adding rows to our html table, we add them directly to the data-manager, and this takes care of updating the render.

The only other small thing to note is I implemented "pause" functionality. When messages are streaming down from the server, you may want to pause the flow in the browser, check something out, then let it run again. This works by telling the DataTable to draw() or not, depending on if my pause checkbox is ticked on or off.

var Paused = false;

$('#chkMessageFlow').click(function () {
    Paused = !Paused;


if (Paused) {
        // add rows, but don't draw
        logTable.row.add([dt, serviceName, processName, message]);
    else {
        // add rows, and draw!
        logTable.row.add([dt, serviceName, processName, message]).draw();

And that ladies and gentlefolk, is it for the server (and embedded web-server) side! ... its ready to test :)

Test client

Our test client is a basic console application. It sets up a WCF named-pipe client, asks the user to enter a number, and for the count of that number, sends a random message (using a GUID as the sample string) to the WCF server.

ChannelFactory<imessagehub> pipeFactory =
    new ChannelFactory<imessagehub>(
        new NetNamedPipeBinding(),
            new EndpointAddress(
            // important! ... note the endpoint "name" must match WCF serverside
// can use any other WCF binding for http/ftp etc
// wrap with try/catch
IMessageHub pipeProxy = pipeFactory.CreateChannel();

Console.WriteLine(@"Enter a valid number of times to send a random message eg: 25 <enter>");
int numCount = Int32.Parse(Console.ReadLine());

for (int i = 0; i < numCount; i++)
    Guid gu = Guid.NewGuid();
    pipeProxy.MessageRelay("PipeService", "ClientProcess", gu.ToString(), LogMessageType.Broadcast);

So the test-client functionality, ie: sending a short operational message, is what you replicate in your methods. Now instead of Debug.console.write for example, you can now direct these kinds of messages to a message-hub, and from there to a browser, or log file, etc. The nice thing about the system is you can use any form of message transport that WCF caters for.

The end result:


There you have it - a little troika of technologies that carry out quite a useful function. The core concepts here can be used easily build an extremely fancy dashboard like the one shown at the top of the article. The technologies presented here are easy to use ... so now, you have no excuse - get excited ... go do live streaming things :)


If you liked this article and found it useful please give it a vote!


In depth article on using NancyFX in a self-hosted / windows service project


Version 1

19/3 - updated attached projects - re-bulit using Visual Studio 2012


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United Kingdom United Kingdom
Allen is a consulting architect with a background in enterprise systems. His current obsessions are IoT, Big Data and Machine Learning. When not chained to his desk he can be found fixing broken things, playing music very badly or trying to shape things out of wood. He runs his own company specializing in systems architecture and scaling for big data and is involved in a number of technology startups.

You may also be interested in...


Comments and Discussions

QuestionBrowse default.html page from other network computers Pin
GoranDjordjevic3-Jun-15 4:59
memberGoranDjordjevic3-Jun-15 4:59 
AnswerRe: Browse default.html page from other network computers Pin
AJSON3-Jun-15 10:31
mvaAJSON3-Jun-15 10:31 
GeneralRe: Browse default.html page from other network computers Pin
GoranDjordjevic3-Jun-15 10:51
memberGoranDjordjevic3-Jun-15 10:51 
AnswerRe: Browse default.html page from other network computers Pin
AJSON3-Jun-15 10:55
mvaAJSON3-Jun-15 10:55 
GeneralRe: Browse default.html page from other network computers Pin
GoranDjordjevic4-Jun-15 3:26
memberGoranDjordjevic4-Jun-15 3:26 
GeneralMy vote of 5 Pin
anilchanna20-Mar-15 4:31
memberanilchanna20-Mar-15 4:31 
GeneralMy vote of 5 Pin
mahabirsingh.kis19-Mar-15 19:34
membermahabirsingh.kis19-Mar-15 19:34 
QuestionVery nice article! Pin
Mr. Javaman19-Mar-15 4:28
memberMr. Javaman19-Mar-15 4:28 
AnswerRe: Very nice article! Pin
AJSON19-Mar-15 5:15
mvaAJSON19-Mar-15 5:15 
QuestionMy vote of 5 Pin
Gaurav Aroraa19-Mar-15 3:17
professionalGaurav Aroraa19-Mar-15 3:17 
AnswerRe: My vote of 5 Pin
AJSON19-Mar-15 3:23
mvaAJSON19-Mar-15 3:23 
AnswerRe: My vote of 5 Pin
AJSON19-Mar-15 7:21
mvaAJSON19-Mar-15 7:21 
GeneralRe: My vote of 5 Pin
Gaurav Aroraa19-Mar-15 20:46
professionalGaurav Aroraa19-Mar-15 20:46 
GeneralMy vote of 5 Pin
SahilGarg 721019-Mar-15 0:23
groupSahilGarg 721019-Mar-15 0:23 
AnswerRe: My vote of 5 Pin
AJSON19-Mar-15 0:26
mvaAJSON19-Mar-15 0:26 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun18-Mar-15 21:46
memberHumayun Kabir Mamun18-Mar-15 21:46 
AnswerRe: My vote of 5 Pin
AJSON19-Mar-15 0:00
mvaAJSON19-Mar-15 0:00 
QuestionNeed help regarding your article Pin
Tridip Bhattacharjee18-Mar-15 21:14
professionalTridip Bhattacharjee18-Mar-15 21:14 
AnswerRe: Need help regarding your article Pin
AJSON18-Mar-15 23:50
mvaAJSON18-Mar-15 23:50 
GeneralRe: Need help regarding your article Pin
Tridip Bhattacharjee19-Mar-15 21:39
professionalTridip Bhattacharjee19-Mar-15 21:39 
AnswerRe: Need help regarding your article Pin
AJSON19-Mar-15 23:45
mvaAJSON19-Mar-15 23:45 
GeneralRe: Need help regarding your article Pin
Tridip Bhattacharjee20-Mar-15 2:52
professionalTridip Bhattacharjee20-Mar-15 2:52 
AnswerRe: Need help regarding your article Pin
AJSON20-Mar-15 3:03
mvaAJSON20-Mar-15 3:03 
Questionsource code file link broken Pin
Tridip Bhattacharjee18-Mar-15 21:11
professionalTridip Bhattacharjee18-Mar-15 21:11 
AnswerRe: source code file link broken Pin
AJSON19-Mar-15 0:00
mvaAJSON19-Mar-15 0:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190306.1 | Last Updated 20 Mar 2015
Article Copyright 2015 by AJSON
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid