Embed A Web Server In A Windows Service

Introduction

A Windows Service is a long running process that sits in the background, executing when needed. Services don't interact with the desktop, and this raises many issues, including the problem of controlling the service to a finer level than simply clicking "start service" "stop service" in the services control panel. This article describes using the NancyFX framework to provide a web browser interface to your Windows Service, giving you much more control on what's going on and managing the internals for the service itself.

(The ever so lovely image on my Windows Form is taken from the NancyFX website. Yes, using it can be as simple as it says!)

The Basics

To get started, and to save the bother of spinning up a service immediately, we will start off the article using a standard Windows Form project, then convert it towards the end. I am calling this starter project "NancyWinForm".

Once you have your Windows Form project created, the first thing to do is open NuGet and add the following packages:

Nancy, Nancy.ViewEngines.Razor, Nancy.Hosting.Self. Nancy is the core package, Hosting.Self is required for self hosting in a DLL, EXE etc. without the need to sit on top of another host, and we are using the Razor engine on this occasion to parse the data in our HTML view pages.

In order to get Nancy up and running, there are a few basics that we need to put in place. Having linked in the NuGet packages, the next thing is to add some, using clauses to the top of the main form.

  1. using Nancy;  
  2. using Nancy.Hosting.Self;   
  3. using System.Net.Sockets;   
The next thing we need to do is to set up a form level object to run Nancy. 
  1. namespace NancyWinForm{  
  2. public partial class Main : Form  
  3.     {  
  4.         NancyHost host;   // < ---- form level object  
  5.         public Main()  
  6.         {  
  7.             InitializeComponent();  
  8.         }  
  9.     }  
  10. }  
Next, we initialize the Nancy host object.
  1. public Main()       {  
  2.     InitializeComponent();  
  3.     string URL = "http://localhost:8080";  
  4.     host = new NancyHost(new Uri(URL));  
  5.     host.Start();  
  6. }  
We start Nancy with a constructor that gives it a simple domain "localhost" and port "8080". You should pick something that is not already running on your system. For example, if you already have IIS or another web service running, then port 80 is most likely gone. We will discuss multiple binding and ports later in the article. Once we have told dear Nancy what to bind to, we tell her to "start" .... and if we open a browser to the URL we gave her, here's what we see...

The Nancy authors have an ethos they call the “super-duper-happy-path” ... I think we can safely say we're happy. Smile | :)

OK! The next thing is to take that little green monster out of Nancy's way and get in there ourselves..

The next step is to create a new class of type "NancyModule", and give it a default path.

  1. public class MainMod : NancyModule      
  2.   
  3. public MainMod()  
  4. {  
  5.  Get["/"] = x =>  
  6.    {  
  7.     return "Wee hoo! - no more little green monster...";  
  8.    };  
  9.   
  10.  }  

Here's a small gotcha - in a Windows Form, if you place this code above some that requires the designer (for example, a picture container with a picture of young nance), the compiler will complain that it wants to be first in line .... to fix this, just put the module class at the end of your form file.

A "NancyModule" can be added anywhere in the application and the framework will find it. It does this by iterating through the appdomain on startup looking for any NancyModules and hooking into them when they are located. Inside a NancyModule, we add "routes" or "paths". You can see that in this case, I added a root path "/". To start the ball rolling, I am simply returning a simple string to the browser. When we run, the output is as expected.


Ok, text output is great but not terribly useful. The next thing to do is to add a HTML file we can work with. For this project, I have added a folder called "views" and in there, created a new HTML file "skirts.html" (get with the program, the theme must continue!!).

Let's add some simple content to the HTML file, and adjust the module get route handler to return the file.

  1. <!DOCTYPE html>  
  2. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta charset="utf-8" />  
  5. <title>Nancy's skirts</title>  
  6. </head>  
  7. <body>  
  8.   
  9. Heylow der...  
  10. </body>  
  11. </html>   
  1. public MainMod()  
  2.  {  
  3.    Get["/"] = x =>  
  4.     {  
  5.        return View["views/skirts.html"];   //<-- sending back a view page  
  6.      };  
  7.   
  8.  }  

Hit F5 to run, stand well back...

Oh dear, the little green monster is back ...what's happened is that in Nancy, we need to tell it a bit more than that we would in IIS. In this case, we need to tell the project to include the file in its output folder.

Now, when we run, the monster is gone ... Perfect !

Having seen how to handle a GET, we will now handle POST. For this example, let's create two further HTML files "nice.html" and "very.html" - don't forget to set them to copy to output if newer. In our original HTML file, we will add a form to post...

  1. <form method="post" action="NiceNancy">    
  2.     How nice is nancy? - please select...    
  3.     
  4. <select name="HowNice">     
  5. <option value="1">Quite nice</option>    
  6. <option value="2">Very!</option>     
  7. </select>     
  8.     
  9. <button type="submit">Submit</button>     
  10.     
  11. </form>    
The idea is to send back one page if the user selects "quite nice", another if they select "very". Here is the POST code added to the Nancy module. 
  1.         Post["/NiceNancy"] = y =>  
  2. {  
  3. if (Request.Form["HowNice"].HasValue)  
  4.  {  
  5.  if (Request.Form["HowNice"] == "1")  
  6.   { return View["views/nice.html"]; }  
  7.  else if (Request.Form["HowNice"] == "2")  
  8.  { return View["views/very.html"]; }  
  9.  else return View["views/skirts.html"];  
  10. };  
  11.  else return View["views/skirts.html"];  
  12. }  
Note that like MVC/ASP, the form data is accessible via the "Request" object. 

Giving Nancy the Boot....

Nancy is light, and unlike something heavy like IIS, it does not have as inbuilt facilities that you might expect. One of the things it needs guidance on is things like images and paths. Nancy will automatically serve up files (JS, CSS, Images..), but needs to be told where these things are stored, relative to itself. This is handled using the "Bootstrapper" class.

I am creating a new unit to store this code, "Bootstrapper.cs" - you can place it where you wish. To this file, I am adding the following use clauses:

  1. using Nancy;  
  2. using Nancy.Session;  
  3. using Nancy.Bootstrapper;  
  4. using Nancy.Conventions;  
  5. using System.Web.Routing;  
  6. using Nancy.TinyIoc;   

I also add a project reference to "system.web".

We need to derive the new class from "DefaultNancyBootstrapper" before we can start doing anything useful. We then add an override method "Configure conventions" to hook in the location of folders that will store images, etc.

  1. public class Bootstrapper : DefaultNancyBootstrapper  
  2.     {  
  3.         protected override void ConfigureConventions(NancyConventions nancyConventions)  
  4.         {  
  5.             base.ConfigureConventions(nancyConventions);  
  6.             nancyConventions.StaticContentsConventions.Clear();  
  7.             nancyConventions.StaticContentsConventions.Add  
  8.             (StaticContentConventionBuilder.AddDirectory("css""/content/css"));  
  9.             nancyConventions.StaticContentsConventions.Add  
  10.             (StaticContentConventionBuilder.AddDirectory("js""/content/js"));  
  11.             nancyConventions.StaticContentsConventions.Add  
  12.             (StaticContentConventionBuilder.AddDirectory("images""/content/img"));  
  13.             nancyConventions.StaticContentsConventions.Add  
  14.             (StaticContentConventionBuilder.AddDirectory("fonts""/content/fonts"));  
  15.         }  
  16.   
  17.     }  

On startup, Nancy is now aware that we have (for example) a local path "/content/img" that is referred to by the virtual path "images". Let's test it from our main HTML file by dropping in an image and referring to it.

  1. <form method="post" action="NiceNancy">  
  2.        <img src="images/SoWhat.jpg" />  
  3.        <br />  

Yea, works!

To tell Nancy where our images and other resources were stored, we customised things using the "bootstrapper" class. Bootstrapper is useful for all kinds of things as it allows us to hook into the NancyIoC and inject supporting objects into our application. One of the things I wanted to achieve was being able to have an object that would effectively store global variables. To do this, I created a class to load/save data using an XML file, and allow access to the data as needed.

The following is the simple "config-manager" class which I stored in a separate file "shared" (note the addition of the XML using clauses as I am using serialisation to save/load the data quickly).

  1. using System.Xml;  
  2. using System.Xml.Serialization;  
  3. using System.IO;  
  4.   
  5. namespace NancyWinForm  
  6. {  
  7.     public class ConfigInfo  
  8.     {  
  9.         public String TempFolder { getset; }  
  10.         public String Username { getset; }  
  11.         public String DateFormat { getset; }  
  12.     }  
  13.   
  14.     public class PracticeConfigManager  
  15.     {  
  16.         public ConfigInfo config;  
  17.         string _XMLFile = AppDomain.CurrentDomain.BaseDirectory + "MyConfig.xml";  
  18.   
  19.         public void LoadConfig()  
  20.         {  
  21.             if (config == null)  
  22.             {  
  23.                 config = new ConfigInfo();  
  24.             }  
  25.   
  26.             if (!File.Exists(_XMLFile))  
  27.             {  
  28.                 config.DateFormat = "dd/mmm/yyyy";  
  29.                 SaveConfig();  
  30.             }  
  31.   
  32.             XmlSerializer deserializer = new XmlSerializer(typeof(ConfigInfo));  
  33.             TextReader reader = new StreamReader(_XMLFile);  
  34.             object obj = deserializer.Deserialize(reader);  
  35.             config = (ConfigInfo)obj;  
  36.             reader.Close();  
  37.         }  
  38.   
  39.         public void SaveConfig()  
  40.         {  
  41.             if (config != null)  
  42.             {  
  43.                 XmlSerializer serializer = new XmlSerializer(typeof(ConfigInfo));  
  44.                 using (TextWriter writer = new StreamWriter(_XMLFile))  
  45.                 {  
  46.                     serializer.Serialize(writer, config);  
  47.                 }  
  48.             }  
  49.         }  
  50.     }  
  51. }  
Having setup the class to save/load the config data, we now need to inject this into Nancy. We do this using the bootstrapper. In our bootstrap class, we override the method "Application Startup", and in here, register the ConfigManager class in the IoC container, as follows. 
  1. public class Bootstrapper : DefaultNancyBootstrapper  
  2. {  
  3.   
  4.     protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)  
  5.     {  
  6.         base.ApplicationStartup(container, pipelines);  
  7.         ConfigManager mgr;  
  8.         mgr = new ConfigManager();  
  9.         mgr.LoadConfig();  
  10.         container.Register<configmanager>(mgr);  
  11.     }</configmanager>  

Having registered it, we now need to be able to access it whenever we get a GET/POST HTTP request. We do this by changing the signature of our main NancyModule.

From,

  1. public MainMod()  
To,
  1. public MainMod(ConfigManager mgr)  
As our ConfigManager is created and initialised at Nancy startup, we can therefore use it directly, now in the NancyModule. 
  1. Get["/config"] = x =>  
  2. {  
  3.    return mgr.config.DateFormat;  
  4. };  

and the result...


OK, all looking good. The bootstrapper class is an extremely useful part of NancyFX and a place I find myself dipping into often.

When developing for the web, I prefer to steer clear these days of WebForms and use MVC almost exclusively - I like the clean separation of concerns and the ability to be "close to the metal" as it were. Nancy allows us to use Razor syntax in a familiar way to MVC. Let's say, we had some values persisted that we wished to use on the web-page. We work with Razor in Nancy the same way we do in MVC...

1. Create a page "config.html" and add set properties to "add if newer"
  1. <body>  
  2.   
  3.     Model test page<br />  
  4.     <hr>  
  5.     <form method="post" action="SaveConfig">  
  6.   
  7.         <input id="dateFormat" value="@Model.DateFormat" />  
  8.         <input id="username" value="@Model.Username" />  
  9.         <input id="tempFolder" value="@Model.TempFolder" />  
  10.   
  11.         <button type="submit">Submit</button>  
  12.   
  13.     </form>  
  14. </body>  
2. Add new controller code, passing in the ConfigManager as the model:
  1. Get["/config"] = x =>  
  2. {  
  3.    //return mgr.config.DateFormat;  
  4.     return View["views/config.html",mgr.config];  
  5. };  

So we can see that the model data (the date format) has been rendered correctly into the HTML.

Binding to the IP Stack

Sometimes, when setting up a HTTP server to listen for traffic, you want to specify a particular IP address, but sometimes you want to bind to all available IPs, in other words - a wildcard binding. I found some useful code here that helps this happen. You send the method the port to bind to, it sends back an array of available bindings.

  1. private Uri[] GetUriParams(int port)  
  2. {  
  3.     var uriParams = new List<uri>();  
  4.     string hostName = Dns.GetHostName();  
  5.   
  6.     // Host name URI  
  7.     string hostNameUri = string.Format("http://{0}:{1}", Dns.GetHostName(), port);  
  8.     uriParams.Add(new Uri(hostNameUri));  
  9.   
  10.     // Host address URI(s)  
  11.     var hostEntry = Dns.GetHostEntry(hostName);  
  12.     foreach (var ipAddress in hostEntry.AddressList)  
  13.     {  
  14.         if (ipAddress.AddressFamily == AddressFamily.InterNetwork)  // IPv4 addresses only  
  15.         {  
  16.             var addrBytes = ipAddress.GetAddressBytes();  
  17.             string hostAddressUri = string.Format("http://{0}.{1}.{2}.{3}:{4}",  
  18.             addrBytes[0], addrBytes[1], addrBytes[2], addrBytes[3], port);  
  19.             uriParams.Add(new Uri(hostAddressUri));  
  20.         }  
  21.     }  
  22.   
  23.     // Localhost URI  
  24.     uriParams.Add(new Uri(string.Format("http://localhost:{0}", port)));  
  25.     return uriParams.ToArray();  
  26. }  
To implement, we need to start Nancy off slight differently... the effect of this is to this force ACL to create network rules for new ports if they do not already exist.
  1. public Main()  
  2. {  
  3.     InitializeComponent();  
  4.     int port = 8080;  
  5.     var hostConfiguration = new HostConfiguration  
  6.     {  
  7.         UrlReservations = new UrlReservations() { CreateAutomatically = true }  
  8.     };  
  9.    host = new NancyHost(hostConfiguration, GetUriParams(port));  
  10.     host.Start();  
  11. }  

There is a "gotcha" to be aware of ... Windows does not like anyone but admin running on things on anything but default ports - the solution is to open up the ports manually - you can also handle this manually outside in an installation process, like this:

netsh http add urlacl url=http://+:8888/app user=domain\user  

(+ means bind to all available IPs)

Nancy Goes into Service...

To facilitate the quick testing of the project, we put it together in a Windows form application. The objective however was to use this very cool little micro web server as a gateway to access and interact more meaningfully with a Windows service. We have already put together the main code previously in the article, so the only thing I am going to do here is show you the setup of the service - it is available for download if you wish to see it in operation or hopefully, use the code yourself!

The normal template codebase for a service program starts like this.

  1. static class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         ServiceBase[] ServicesToRun;  
  6.         ServicesToRun = new ServiceBase[]  
  7.         {  
  8.             new Service1()  
  9.         };  
  10.         ServiceBase.Run(ServicesToRun);  
  11.     }  
  12. }  
We will make two adjustments - first, we will alter the code so that if you start it from the Visual Studio development environment, it will start and allow you to debug, finally, we will add the startup Nancy code itself. 
  1. static class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         ServiceBase[] ServicesToRun;  
  6.         ServicesToRun = new ServiceBase[]  
  7.         {  
  8.             new Service1()  
  9.         };  
  10.         ServiceBase.Run(ServicesToRun);  
  11.     }  
  12. }  
Changes to, 
  1. static void Main()  
  2. {  
  3.     NancyHost host;  
  4.     string URL = "http://localhost:8080";  
  5.     host = new NancyHost(new Uri(URL));  
  6.     host.Start();  
  7.   
  8.     //Debug code  
  9.     if (!Environment.UserInteractive)  
  10.     {  
  11.         ServiceBase[] ServicesToRun;  
  12.         ServicesToRun = new ServiceBase[]  
  13.     {  
  14.         new Service1()  
  15.     };  
  16.         ServiceBase.Run(ServicesToRun);  
  17.     }  
  18.     else  
  19.     {  
  20.         Service1 service = new Service1();  
  21.         // forces debug to keep VS running while we debug the service  
  22.         System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);  
  23.     }  
  24. }  

To install the service, we need to use the command line.

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" "[Path]NancyService.exe"
(where [Path] is the location of your compiled service executable).

Le Voila, the finished product....

That's it. A useful exercise and something to consider the next time you write a Windows service...

An Aside...

Using Nancy is of particular interest to me as many moons ago in a far and distant planet, I was heavily involved in http://www.indyproject.org/index.en.aspx. Indy was/is an open source sockets library heavily used in the Borland Delphi community and as part of this, I wrote many demos, including a self hosted HTTP Server ... How the tide turns.