Dirty Docker Hack for WikiJS PlantUML

WikiJS 2 is a great wiki server that includes support for PlantUML in markdown. If you want it to use your own PlantUML server for rendering, it’s a simple matter of changing a setting. Unfortunately, the editor is essentially hard-coded to use https://plantuml.requarks.io, and there isn’t currently a way to override it (there’s a two year old pull request that hasn’t been merged yet).

However, if you’re hosting WIkiJS in a container and super lazy, you may find this diabolical Dockerfile hack useful until WikiJS 3 is released:

FROM ghcr.io/requarks/wiki:2

RUN grep -rl plantuml.requarks.io /wiki/server | xargs sed -i 's,https://plantuml.requarks.io,https://MY_PLANTUML_URL,g' && \
    grep -rl plantuml.requarks.io /wiki/assets/js | xargs sed -i 's,https://plantuml.requarks.io,https://MY_PLANTUML_URL,g'

Basically it’s just creating a new image and replacing the https://plantuml.requarks.io URL with your own.

NuGet Package Hierarchical Versioning

This post discusses an auto-versioning strategy for interdependent NuGet packages.

The new project system

The new project system introduced with Visual Studio 2017 is a huge improvement on what’s gone before.  One of the best features is aggregation of several configuration files into a single project file.  Previously, a typical C# project might include these:

  • <project>.csproj – The project file, which typically lists every file included in the project.
  • Properties/AssemblyInfo.cs – Metadata compiled into the assembly, including version numbers.
  • packages.config – A list of referenced NuGet package versions.
  • <project>.nuspec – NuGet package configuration file (optional; used for creating NuGet packages).

With the new project system, most stuff you’ll need is in the .csproj file.  For many projects this just means less clutter, and a project file you’re happy to edit manually.  If you’re building NuGet packages, it gets even better.

Building NuGet packages

Let’s say you’re building Package A and Package B, and Package B requires Package A.  You make an API change in Package A and increment its version number.  Since you’ve not changed Package B, its latest version continues to reference the old version of Package A.

What if Package B is the primary package you want most users to use, and Package A is just one of several dependencies?  If you want users to have the latest code but not have to reference Package A directly, you need to increment Package B’s version number too.  With the old project system you also need to update Package B’s .nuspec file with Package A’s new version number.

Automated versioning

Because the new project system brings everything we need into the .csproj file, it makes automating the versioning process much easier.  Here’s something I’ve been using that works pretty well:

Given a root folder, it’ll recursively identify local changes that haven’t been committed to git yet (using the ngit package).  It then determines which projects reference projects that contain those changes.  At the end it’ll suggest new version numbers for all affected projects.  If the “writeChanges” flag is set, it’ll modify the project version numbers for you.

Because it’s comparing against the last commit, it’s safe to run multiple times or manually update version numbers if you prefer.

 

Resume Artist (iPad)

It’s time to plug a new app!   This piece of awesome lets you create resumes / CV’s pretty easily, then tweak spacing fonts, colors etc.  It’s free with a basic template, or you can unlock the other templates for $4.99.

Resume Artist (iPad)

Of course it’s not as much fun as Saguru, and perhaps not as mind-bogglingly every-day-useful as Cashflows, but it’s extremely cool if you want to make resumes.

Visual Studio 2015 Update 1

Finally, Visual Studio 2015 [Update 1] remembers my “Keep tabs” setting!!!

This has caused me considerable pain and anguish; almost as unpleasant as Go’s arrogant (and wrong) opinion on squiggly placement.  Don’t believe me?  Go paste this code into https://golang.org (or move their opening brace to its artistically correct position on the next line):

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

func main()
{
 fmt.Println("Hello, 世界")
}

This is sick.  Just putting that out there.

ImmutableInterlocked

The Immutable Collections package is awesome.  If you’re writing concurrent code, immutable collections should be your new best friends (along with immutable classes in general).  Explicit locking is bad, bad, bad, with an extra helping of bad (repeat this until it sticks).

A typical pattern you’ll see when modifying a collection looks like this:

myCollection = myCollection.Add( "Banana" );

However if the “myCollection” above is a field you’re sharing between threads, you still need to protect it.  This is easy with the System.Threading.Interlocked helpers:

Interlocked.Exchange(
    ref myCollection,
    myCollection.Add( "Banana" ) );

But what if you’re updating an ImmutableDictionary and need an atomic update, so it’ll only add an item if it doesn’t exist?  Here’s where the ImmutableInterlocked helpers come in:

private ImmutableDictionary<string, Fruit> myDictionary
    = ImmutableDictionary<string, Fruit>.Empty;
…
var fruit = ImmutableInterlocked.GetOrAdd(
    ref myDictionary,
    "banana",
    new Banana() );

Now things could get interesting.  You’ll notice on the line above we create a new Banana instance.  If “banana” already exists in the dictionary, the nice fresh Banana we created will just be discarded.  In many cases this isn’t a problem (maybe a slip hazard); it’s just a redundant object creation.

But what if it’s something we only want to create once, and only if it doesn’t exist?  ImmutableInterlocked has a GetOrAdd override that takes a delegate:

var fruit = ImmutableInterlocked.GetOrAdd(
    ref myDictionary,
    "banana",
    _ => new Banana() );

It sure looks promising.  Presumably it only calls the delegate if the item isn’t in the dictionary?…  Nope!  Apparently it always calls the delegate, checks if the item exists, and discards the result if it does (while the source code isn’t currently available, we can get a vague idea how it might be implemented from this Unofficial port of Immutable Collections).

So it seems we need another solution.  We really don’t want to explicitly lock anything (bad, bad, bad).  Turns out we can get this for “free” if we use Lazy<T>:

private ImmutableDictionary<string, Lazy<Fruit>> myDictionary
    = ImmutableDictionary<string, Lazy<Fruit>>.Empty;
…
var fruit = ImmutableInterlocked.GetOrAdd(
    ref myDictionary,
    "banana",
    new Lazy<Fruit>( () => new Banana(), true ) ).Value;

This ensures there’s a Lazy<Fruit> in the dictionary that knows how to create a Banana on demand.  Lazy<T> already takes care of ensuring only one thread can actually create the instance.  It does some internal locking of its own, but apparently it’s super efficient so we can happily ignore it and go on our way.

Hope this helps!

HTML View Engine

Here’s a simple view engine for ASP.NET MVC that lets you use plain HTML for your views, even if it’s badly formed!  It supports a very simple attribute syntax for embedding other partial views in the page; those views can use whichever view engine you’d like (WebForms, Razor, NHaml etc).

Let’s start with the composite view engine; its job is to find a container view based on the Master page name, but also find a primary partial view based on the current MVC controller and action:

public interface ICompositeView
{
    IView PrimaryView { set; }
}

public abstract class CompositeViewEngine : VirtualPathProviderViewEngine
{
    private ViewEngineCollection otherViewEngines;

    public CompositeViewEngine()
    {
    }

    public override ViewEngineResult FindView( ControllerContext controllerContext, string viewName, string masterName, bool useCache )
    {
        if ( !controllerContext.IsChildAction )
        {
            var result = base.FindView( controllerContext, GetMasterName( controllerContext.RouteData.Values, masterName ), null, useCache );
            var compositeView = result.View as ICompositeView;

            if ( compositeView != null )
            {
                compositeView.PrimaryView = OtherViewEngines.FindPartialView( controllerContext, viewName ).View;

                return result;
            }
        }
        else
        {
            return OtherViewEngines.FindView( controllerContext, viewName, null );
        }

        return new ViewEngineResult( Enumerable.Empty<string>() );
    }

    public override ViewEngineResult FindPartialView( ControllerContext controllerContext, string partialViewName, bool useCache )
    {
        return new ViewEngineResult( Enumerable.Empty<string>() );
    }

    private ViewEngineCollection OtherViewEngines
    {
        get
        {
            lock ( this )
            {
                return ( otherViewEngines != null )
                    ? otherViewEngines
                    : otherViewEngines = new ViewEngineCollection( ViewEngines.Engines.Where( e => !( e is CompositeViewEngine ) ).ToList() );
            }
        }
    }

    protected virtual string GetMasterName( RouteValueDictionary routeValues, string defaultName )
    {
        return defaultName;
    }
}

After finding its own container view, it gives all other view engines the opportunity to find the contained partial.  Here’s the HTML view engine that derives from it:

public class HtmlViewEngine : CompositeViewEngine
{
    public IHtmlViewHelper Helper { get; set; }

    public HtmlViewEngine()
    {
        this.AreaViewLocationFormats = new string[]
        {
            "~/Areas/{2}/Views/{1}/{0}.html",
            "~/Areas/{2}/Views/{1}/{0}.htm",
            "~/Areas/{2}/Views/Shared/{0}.html",
            "~/Areas/{2}/Views/Shared/{0}.htm"
        };

        this.ViewLocationFormats = new string[]
        {
            "~/Views/{1}/{0}.html",
            "~/Views/{1}/{0}.htm",
            "~/Views/Shared/{0}.html",
            "~/Views/Shared/{0}.htm"
        };

        this.FileExtensions = new string[]
        {
            "html",
            "htm"
        };
    }

    protected override string GetMasterName( RouteValueDictionary routeValues, string defaultName )
    {
        return routeValues.ContainsKey( "path" )
            ? ( (string)routeValues[ "path" ] ).Split( '.' ).First()
            : !string.IsNullOrEmpty( defaultName ) ? defaultName : "Index";
    }

    protected override IView CreateView( ControllerContext controllerContext, string viewPath, string masterPath )
    {
        return new HtmlView( viewPath, Helper );
    }

    protected override IView CreatePartialView( ControllerContext controllerContext, string partialPath )
    {
        return new HtmlView( partialPath, Helper );
    }
}

Once the container view is found, it creates an HtmlView that knows how to render it.  Here’s how that looks (starting with a CompositeView):

public abstract class CompositeView : IView, ICompositeView
{
    protected string filename;

    public IView PrimaryView { get; set; }

    public CompositeView( string filename )
    {
        this.filename = filename;
    }

    public abstract void Render( ViewContext viewContext, TextWriter writer );
}
public interface IHtmlViewHelper
{
    void RenderContent( HtmlDocument document, ViewRenderer renderer );
}

public class HtmlView : CompositeView
{
    protected IHtmlViewHelper helper;
    protected HtmlDocument source;

    public HtmlView( string filename, IHtmlViewHelper helper )
        : base( filename )
    {
        this.helper = helper;
    }

    public override void Render( ViewContext viewContext, TextWriter writer )
    {
        var document = GetSource( viewContext );

        if ( helper != null )
        {
            var viewDataContainer = new ViewDataContainer( viewContext.ViewData.Model );
            var htmlHelper = new HtmlHelper( viewContext, viewDataContainer );

            helper.RenderContent( document, new ViewRenderer( viewContext, htmlHelper, PrimaryView ) );
        }

        document.Save( writer );
    }

    private HtmlDocument GetSource( ControllerContext controllerContext )
    {
        return source ?? ( source = GetSource( controllerContext.HttpContext, filename ) );
    }

    private HtmlDocument GetSource( HttpContextBase httpContext, string filename )
    {
        return httpContext.RequestCache().Cache( filename, () => LoadSource( httpContext, filename ) );
    }

    private HtmlDocument LoadSource( HttpContextBase httpContext, string filename )
    {
        var doc = new HtmlDocument();

        doc.Load( httpContext.Server.MapPath( filename ) );

        return doc;
    }
}

It uses HtmlAgilityPack to parse the HTML (with a little caching), injects new content into the DOM, then renders the result with some help from the ViewRenderer class (catches & pretty prints any rendering errors too):

public class ViewRenderer
{
    private ViewContext viewContext;
    private HtmlHelper htmlHelper;
    private IView primaryView;
    private ViewEngineCollection otherViewEngines;

    public ViewRenderer( ViewContext viewContext, HtmlHelper htmlHelper, IView primaryView )
    {
        this.viewContext = viewContext;
        this.htmlHelper = htmlHelper;
        this.primaryView = primaryView;
        this.otherViewEngines = new ViewEngineCollection( ViewEngines.Engines.Where( e => !( e is CompositeViewEngine ) ).ToList() );
    }

    public MvcHtmlString RenderContent( bool usePrimaryView, string actionName = null, string controllerName = null, string viewName = null )
    {
        var rendered = ( viewName != null )
            ? RenderView( viewName )
            : null;

        if ( rendered == null && usePrimaryView && ( controllerName == null || controllerName == (string)viewContext.RouteData.Values[ "controller" ] ) )
        {
            rendered = RenderView( primaryView );
        }

        if ( rendered == null ) rendered = RenderAction( actionName ?? "Index", controllerName );

        return rendered ?? MvcHtmlString.Empty;
    }

    public MvcHtmlString RenderView( string viewName )
    {
        return RenderView( FindView( viewName ) );
    }

    public MvcHtmlString RenderAction( string actionName, string controllerName = null )
    {
        MvcHtmlString result = null;

        try
        {
            result = htmlHelper.Action( actionName, controllerName );
        }
        catch ( HttpException ex )
        {
            result = MvcHtmlString.Create( ex.GetHtmlErrorMessage() ?? new HttpUnhandledException( ex.Message, ex.InnerException ).GetHtmlErrorMessage() );
        }
        catch ( Exception ex )
        {
            result = MvcHtmlString.Create( new HttpUnhandledException( ex.Message ).GetHtmlErrorMessage() );
        }

        return result;
    }

    private IView FindView( string viewName )
    {
        var result = otherViewEngines.FindPartialView( viewContext, viewName );

        return ( result.View != null ) ? result.View : null;
    }

    private MvcHtmlString RenderView( IView view )
    {
        if ( view == null ) return null;

        using ( var writer = new StringWriter() )
        {
            var renderViewContext = new ViewContext( viewContext, view, viewContext.ViewData, viewContext.TempData, writer );

            try
            {
                view.Render( renderViewContext, writer );
            }
            catch ( HttpException ex )
            {
                writer.Write( ex.GetHtmlErrorMessage() ?? new HttpUnhandledException( ex.Message, ex.InnerException ).GetHtmlErrorMessage() );
            }
            catch ( Exception ex )
            {
                writer.Write( new HttpUnhandledException( ex.Message ).GetHtmlErrorMessage() );
            }

            return MvcHtmlString.Create( writer.ToString() );
        }
    }
}

Finally we need to tell MVC about the view engine. Similar to the RouteConfig class you’ll see in a new MVC 4 project, here’s ViewEngineConfig:

public class ViewEngineConfig
{
    public static void RegisterEngines( ViewEngineCollection viewEngines )
    {
        viewEngines.Insert( 0, new HtmlViewEngine()
        {
            Helper = new HtmlViewHelper()
        } );
    }

    private class HtmlViewHelper : IHtmlViewHelper
    {
        public void RenderContent( HtmlDocument document, ViewRenderer renderer )
        {
            foreach ( var node in SelectNodes( document.DocumentNode, "//*[@html-primary or @html-controller or @html-action]" ) )
            {
                var isPrimary = node.GetAttributeValue( "html-primary", false );
                var controllerName = node.GetAttributeValue( "html-controller", null );
                var actionName = node.GetAttributeValue( "html-action", null );

                node.InnerHtml = renderer.RenderContent( isPrimary, actionName, controllerName ).ToHtmlString();
            }

            foreach ( var node in SelectNodes( document.DocumentNode, "//*[@html-partial]" ) )
            {
                node.InnerHtml = ( renderer.RenderView( node.Attributes[ "html-partial" ].Value ) ?? MvcHtmlString.Empty ).ToHtmlString();
            }
        }

        public string GetControllerName( HtmlDocument document )
        {
            var controllerNode = document.DocumentNode.SelectSingleNode( "//*[@html-controller]" );

            return ( controllerNode != null ) ? controllerNode.GetAttributeValue( "html-controller", null ) : null;
        }

        private static IEnumerable<HtmlNode> SelectNodes( HtmlNode node, string xpath )
        {
            return node.SelectNodes( xpath ) ?? Enumerable.Empty<HtmlNode>();
        }
    }
}

This is doing most of the content substitution.  It’s looking for a few pre-defined attributes in the HTML (html-primary, html-partial, html-controller and html-action) and replacing the content as needed.

Call RegisterEngines in Application_Start (in Global.asax.cs) and you’re done:

ViewEngineConfig.RegisterEngines( ViewEngines.Engines );

This works great when you’re just using regular MVC controller / action routes, but what if you want to handle direct requests for the HTML views? (for example if you’re hosting an entire static site within your MVC project… not as odd as it might sound).  We can do this by adding some Route definitions:

// Controller prefixed resources
routes.Add( "ControllerStaticResource", new Route( @"{controller}/{*path}", new StaticFileRouteHandler() )
{
    Constraints = new RouteValueDictionary( new { path = @".*\.(css|js|png|jpg|gif)" } ),
    Defaults = new RouteValueDictionary( new { rootFolder = "~/Views", folder = "Shared" } ),
} );

// Resources
routes.Add( "StaticResource", new Route( @"{*path}", new StaticFileRouteHandler() )
{
    Constraints = new RouteValueDictionary( new { path = @".*\.(css|js|png|jpg|gif)" } ),
    Defaults = new RouteValueDictionary( new { rootFolder = "~/Views", folder = "Shared" } )
} );

// Static HTML path with controller and action prefix
routes.Add( "ControllerActionStaticHtml", new PlaceholderRoute( @"{controller}/{action}/{*path}", handler )
{
    Constraints = new RouteValueDictionary( new { path = @".*\.(html|htm)" } ),
    Excludes = new[] { "path" }
} );

// Static HTML path with controller prefix
routes.Add( "ControllerStaticHtml", new PlaceholderRoute( @"{controller}/{*path}", handler )
{
    Constraints = new RouteValueDictionary( new { path = @".*\.(html|htm)" } ),
    Defaults = new RouteValueDictionary( new { controller = "Home", action = "Index", path = UrlParameter.Optional } ),
    Excludes = new[] { "path" }
} );

// Static HTML path with controller prefix
routes.Add( "StaticHtml", new PlaceholderRoute( @"{*path}", handler )
{
    Constraints = new RouteValueDictionary( new { path = @".*\.(html|htm)" } ),
    Defaults = new RouteValueDictionary( new { controller = "Home", action = "Index", path = UrlParameter.Optional } ),
    Excludes = new[] { "path" }
} );

// Static HTML path with controller and action prefix
routes.Add( "ControllerActionStaticHtmlGenerate", new PlaceholderRoute( @"{controller}/{action}/{path}", handler )
{
    Defaults = new RouteValueDictionary( new { controller = "Home", action = UrlParameter.Optional, path = UrlParameter.Optional } ),
    Placeholders = new RouteValueDictionary( new { action = "Index" } ),
    Excludes = new[] { "path" }
} );

This could be more complex than you need, so don’t freak out just yet Smile  The first couple are intercepting css, js, png etc files, and pointing them to a new StaticFileRouteHandler class.  Next we’re looking for .html and .html files, but letting the regular MvcRouteHandler take care of those.

Browsers expect non-absolute resource paths to be relative to the current request URL.  In this example we have CSS files, images etc in subfolders of the Views/Shared folder, along with the composite HTML files.  However the URL the browser sees might be just an MVC path.  The StaticFileRouteHandler lets us intercept those resource requests and grab the files from the appropriate place.

This isn’t a requirement (resources could be in the typical ~/Content folder if you prefer) but it can be pretty convenient. By keeping the embedded site files together they can be modified with any HTML editor. If a third party is responsible for those, you can just drop in the entire site when they make changes.

Here’s StaticFileRouteHandler:

public class StaticFileRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler( RequestContext requestContext )
    {
        return new StaticFileHttpHandler( requestContext );
    }

    public class StaticFileHttpHandler : IHttpAsyncHandler, IHttpHandler //, IRequiresSessionState
    {
        private delegate void AsyncProcessorDelegate( HttpContext httpContext );

        protected RequestContext requestContext;
        private AsyncProcessorDelegate asyncDelegate;

        public StaticFileHttpHandler( RequestContext requestContext )
        {
            this.requestContext = requestContext;
        }

        public void ProcessRequest( HttpContext context )
        {
            var routeValues = requestContext.RouteData.Values;

            var controllerName = (string)routeValues[ "controller" ];
            var folderName = (string)routeValues[ "folder" ];
            var path = GetFilePath( context );

            var filePath = ( controllerName != null )
                ? FindFilePath( controllerName, path ) ?? FindFilePath( folderName, path )
                : FindFilePath( folderName, path );

            if ( filePath != null )
            {
                var response = context.Response;

                response.ContentType = GetContentType( filePath );
                response.AddFileDependency( filePath );
                response.Cache.SetETagFromFileDependencies();
                response.Cache.SetLastModifiedFromFileDependencies();
                response.Cache.SetCacheability( HttpCacheability.Public );

                context.Response.TransmitFile( filePath );
            }
            else
            {
                System.Diagnostics.Trace.WriteLine( string.Format( "ERROR: StaticRouteHandler couldn't find {0}", context.Request.Url ) );
                context.Response.StatusCode = 404;
            }
        }

        private string GetFilePath( HttpContext context )
        {
            var routeValues = requestContext.RouteData.Values;

            if ( context.Request.UrlReferrer == null ) return (string)routeValues[ "path" ];

            var urlBase = "http://" + context.Request.Url.GetComponents( UriComponents.Host | UriComponents.Path, UriFormat.Unescaped );
            var referrerBase = "http://" + context.Request.UrlReferrer.GetComponents( UriComponents.Host | UriComponents.Path, UriFormat.Unescaped );

            var url = new Uri( urlBase, UriKind.Absolute );
            var referrer = new Uri( referrerBase, UriKind.Absolute );

            return referrer.MakeRelativeUri( url ).OriginalString;
        }

        private string FindFilePath( string folderName, string path )
        {
            var httpContext = requestContext.HttpContext;
            var routeValues = requestContext.RouteData.Values;

            var filePath = string.Format( "{0}/{1}/{2}",
                routeValues[ "rootFolder" ],
                folderName,
                path );

            var absolutePath = httpContext.Server.MapPath( filePath );

            System.Diagnostics.Trace.WriteLine( string.Format( "Looking for file in {0}", absolutePath ) );

            return File.Exists( absolutePath ) ? absolutePath : null;
        }

        private string GetContentType( string filePath )
        {
            var extension = System.IO.Path.GetExtension( filePath );

            switch ( extension )
            {
                case ".htm":
                case ".html": return "text/html";
                case ".css": return "text/css";
                case ".js": return "application/javascript";
                case ".png": return "image/png";
                case ".jpg": return "image/jpeg";
                case ".gif": return "image/gif";
            }

            return "text/plain";
        }

        public IAsyncResult BeginProcessRequest( HttpContext context, AsyncCallback cb, object extraData )
        {
            asyncDelegate = ProcessRequest;

            return asyncDelegate.BeginInvoke( context, cb, extraData );
        }

        public void EndProcessRequest( IAsyncResult result )
        {
            asyncDelegate.EndInvoke( result );
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}

Full source and sample project coming soon! Smile