This is the archived version of Roland Weigelt's weblog that ran from 2003 to 2023 at weblogs.asp.net

Archives

Archives / 2013 / May
  • An Example for Self-Hosting Nancy in an Application

    In my recent blog post I wrote about the technical aspects of using the Nancy framework, in this post I’d like explain the “what did I want to achieve” a bit more. Maybe it inspires other people to think about possible self-hosting scenarios that combine desktop and web software.

    The Desktop Software

    One of my hobbies involves writing software for the local basketball club, the Telekom Baskets Bonn. Except the actual score board (which is a commercial product), virtually anything shown on the back projection screens in the arena is displayed by software I wrote. For me that’s the ultimate hobby: coding, designing, creating videos/graphics – all connected to my favorite sport, basketball.

    To get an idea, this is what things look like in the arena before the doors open on a game day:

    image

    My older software RemoteCanvas (see this old blog post from 2006) is used for showing videos, graphics and PowerPoint slides, my newer project LiveTexter uses WPF to dynamically generate views like these:

    image image

    LiveTexter runs in a two-display configuration on a laptop. The projection screens are hooked up (via some video hardware) to the VGA port, the laptop screen shows the control console:

    image image

     

    The Web Client

    Over time, the number of views, especially for live stats, grew large enough that a TV-style “halftime report” (without video, though) became feasible. The idea was to let the hosts of the internet radio show “Baskets FanRadio” analyze the first half on the court in front of a camera while picking the views they needed themselves on a mobile device.

    image 
    Marius Volkmann (left) and Marc Hartenstein (right) at the home game on Saturday; Marius is holding an iPad with the browser running the web client. Photo used with permission by Jörn Wolter, www.wolterfoto.de)

    The software was supposed to be as simple as possible for the first version, so the “remote control” is simply a bunch of preview pictures on a (long) web page. Tapping a picture makes the corresponding view appear on the screens in the arena. This is what it looks like on the iPad:

    image

    The right part of the web page is left blank for safe scrolling using the right thumb, which turned out to be very important for holding the device safely with one hand. This is the perfect example of context when using software on mobile devices – when writing and testing the software at home, I simply forgot about the fact that the people using the software had to carry a microphone in one of their hands. Next season we either need headsets or a lectern…

    The results at the Baskets home game on Saturday were encouraging, so I’m looking forward to write a second, more dynamic version over the summer.

  • Using Nancy to Remotely Control a Desktop Application

    I recently had the requirement to control a desktop application from a mobile device. The application, written using Windows Presentation Foundation (WPF) uses the secondary monitor of a system in full-screen mode, generating views that are shown on projection screens in a sports arena. More on the background story in a later blog post. [Update: the post is now online]

    When I write “control” I mean that I wanted to be able to

    • see a preview of the 10-30 possible views; the views are rather static, so a static preview with a manual refresh is sufficient.
    • tap a preview picture and make the application show the corresponding view on the projection screens

    The “mobile device” should not be limited to a specific platform, so the least complicated solution that came to my mind was to let the desktop app host “something” that would let me open a web page in a mobile browser. The web page could show the preview pictures, tapping one of the pictures would use some JavaScript to call a specific URL (without navigating away from the web page).

    So the requirements were:

    • http://hostname:port/ returns the HTML for the web page
    • http://hostname:port/images/filename.jpg returns a picture used by the web page
    • Calling http://hostname:port/commands/show/provider/view tells the desktop application to show a specific view generated by a specific provider.

    If you search the web for e.g. “wpf web server self-hosting”, you’ll sooner or later come across various recommendations, with the name Nancy popping up here and there. The Nancy framework advertises itself as follows (quote):

    Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono. The goal of the framework is to stay out of the way as much as possible and provide a super-duper-happy-path to all interactions.

    In this blog post I’ll give some tips for using Nancy in the scenario I’ve outlined above, but please don’t expect ready-to-use code.

    How to get Started

    The Nancy website is at http://nancyfx.org/. Don’t be put off by the black background, just take a look at the small code snippet for a hint on the overall experience.

    The NuGet packages you’ll need are Nancy itself (of course) and Nancy.Hosting.Self.

    The next stop is the documentation; after reading the Introduction I headed straight to Self Hosting Nancy – this was looking promising enough in terms of simplicity to keep me going.

    Do not ignore the section HttpListenerException, i.e. don’t stop reading at “may be thrown”, understand it as “will be thrown”. The netsh command line in the documentation is for a specific user, in my scenario I wanted anybody (in the heavily restricted network) to be able to access. In this case you’ll need the following command line (replace port with the actual port number):

    netsh http add urlacl url=http://+:port/ sddl=D:(A;;GX;;;WD)

    How you’ll proceed from here depends on your personal style. Combining the code snippets from the Introduction and Self Hosting pages will give you a first feeling of success with “Hello World” appearing in your browser.

    General Remarks on (Learning) Nancy

    The Nancy framework is simple to use, but that doesn’t mean you get around learning the basics. Two recommendations:

    1. If you share my feeling that the Nancy documentation has the tendency to dive into the specifics a bit too fast (which later may be great, usually framework docs are too shallow), read the article “Understanding Nancy – Sinatra for .Net”. I found it very helpful because it explains the core terms in a very concise way.
    2. Not a groundbreaking insight, but true nevertheless: If you learn a new framework, set breakpoints everywhere to learn the life cycle. It is especially important to know what gets instantiated when and how often.

    Some Remarks on Self-Hosting in an Existing Application

    • I had trouble getting the Razor view engine to work, searching the web I had the feeling that I’m not alone. I didn’t dig much deeper as the “Super Simple View Engine” does everything I needed.
    • When you self-host in a desktop application and want an incoming call of a URL to have an effect on the GUI, keep in mind that the GUI can only be updated from the UI thread. In the case of WPF, you’ll have to use on the Dispatcher.BeginInvoke pattern, e.g.
      Application.Current.Dispatcher.BeginInvoke((Action) (()=>
          {
              // Update UI
          }));
    • My application uses the Managed Extensibility Framework (MEF) and I needed a specific application service (IRemoteAccess) inside a Nancy module. The “Nancy-way” to pass something to a Nancy module (that is instantiated for each request) is to use dependency injection (DI) via a constructor parameter. Nancy uses an IoC container called TinyIoC for DI and bridging the world of MEF and TinyIoC isn’t complicated. If you use Nancy, you’ll sooner or later have a “bootstrapper” class that is used for tweaking things in Nancy – that’s where you can e.g. put stuff you’ll need later into the TinyIoC container:
      public class RemoteAccessBootstrapper : DefaultNancyBootstrapper
      {
          public static CompositionContainer MefContainer { get; set; }
      
          protected override void ApplicationStartup(TinyIoCContainer container,
                                                     Nancy.Bootstrapper.IPipelines pipelines)
          {
              // …
      container.Register(MefContainer.GetExportedValue<IRemoteAccess>()); } // ... }

    The Web Client

    The project was a spontaneous idea with a very tight deadline, so the “client” is a single static web page. Tapping on one of the preview pictures is supposed to access a specific URL without navigating away from the page. In the spirit of “the simplest thing that could possible work” I used the following bit of JavaScript code I found on StackOverflow:

    function show(provider, view) {
        var i = document.createElement("img");
        i.src = "commands/show/" + provider + "/" + view;
    }

    Over the summer the client will be rewritten completely as a single page application, inspired by the article “AngularJs, NancyFx, TypeScript, and BootStrap Oh My!”. The goal is to include more sophisticated features in the client and have learn new technology along the way.

    Final Verdict

    In the short time I had available I didn’t do thorough research what could be the best solution to my problem, but what I can say is that Nancy did its job well enough I can recommend it – at least for this specific scenario.

    Nancy kept the promise of simplicity, but at the same time I always had the feeling whenever I needed “more”, there was a way for me to customize / tweak it without jumping through hoops.

    Nice one!