Tools and Packages, that’s what I want!

Seeing that it’s been a great while since my last write-up for The Pattern, I thought I would share with you today’s endeavor: getting the right stuff in place so I can start coding in TypeScript. Now, I’m not going to write about the language, nor why its existence is a good thing. I might come back to those rants some other time. Also, that’s why TypeScript is not mentioned at all in the title for this post. I want to look at the tools, and specifically, how to get a development environment up and running.

My goal this afternoon was:

  1. be able to compile TypeScript
  2. write TypeScript (.ts) files in Sublime Text, hopefully with some nice syntax highlighting

Those who know me will tell you that, “Yes, sure! Peter does his development in Visual Studio, enjoying some additional bells and whistles, mind you.” So why not go for the TypeScript plugin for VS? That would be great, and I’ll probably try that next. Truth is, I need something that works with a simple text editor, and my current choice outside of Visual Studio is Sublime. And… it is something outside the comfort zone of the cozy, friendly environment that is Visual Studio. Stepping out of your comfort zone once in a while is a good thing, right?

Getting TypeScript to compile

I have one stimpack for you here. What you need is Chocolatey. Haven’t got it yet? Three words for you:

Install. It. Now.

And don’t come back until it is installed!

Back? Right. On a command line, type cinst typescript and watch your system get imbued with both the typescript compiler and node.js, which typescript happen to depend on. Dead simple. I told you, Chocolatey is what you need. It is magic.

I’m now set up to compile .ts files. On any command line I can type “tsc myfancyscript.ts” and I will get a message saying: Error reading file “myfancyscript.ts”: File not found…

Now on to enable writing that script before I embarrass myself even more.

Rigging Sublime

Inspired by the sweet choco-package-manager for tools, I was happy to find a package manager for Sublime packages too. With that in place, hit Ctrl+Shift+P to bring up the command interface, type “install” and hit the install package command. In the following dialog, enter “typescript” and find the “TypeScript language support for SublimeText2” package. Now we’ve got nice syntax highlighting.

Conclusion

As promised, not so much a post about the TypeScript language, more about how to get stuff in place. Chocolatey has proved to be a great bootstrapper for getting tools installed, taking care of versions, dependencies and updates. Also, Sublime as a text editor turns out to be quite powerful while still being fast and lightweight. The built-in support for packages has sparked a growing community creating support for new file formats and tools. Like TypeScript.

Happy coding!

Share

Dependency Injection and Class Inheritance

Once upon a project there was a base class:

class abstract CommonLogic
{
    protected CommonLogic(IFirstLowLevelService firstService) {}
}

…that several developers wanted to subclass. They all believed in the inversion of control principle and took therefore all their dependencies as constructor parameters.  With Autofac, a dependency injection framework at hand they ventured forth implementing many great subclasses. Some of these appeared like this:

class SpecificLogic : CommonLogic
{
    public SpecificLogic(
        IHighLevelService highLevelService,
        IFirstLowLevelService firstService)
    : base(firstService) {}
}

All was well and the number of variations of special logic classes grew and prospered.

Until one day a Senior Developer wanted to extend the base class with new logic requiring more dependencies. Now all the subclasses had to include the new dependencies in their constructors too, passing them on to the base class.

class abstract CommonLogic
{
    protected CommonLogic(
        IFirstLowLevelService firstService,
        ISecondLowLevelService secondService,
        IThirdLowLevelService thirdService
        ) {}
}

class SpecificLogic : CommonLogic
{
    public SpecificLogic(
        IHighLevelService highLevelService,
        IFirstLowLevelService firstService
        ISecondLowLevelService secondService,
        IThirdLowLevelService thirdService)
    : base(firstService, secondService, thirdService) {}
}

The changes caused great disturbance throughout the Source Repository, affecting both production code and test code alike, delaying schedules and disheartening the developers.

Then a brave developer set out on a quest to free the Source from darkness. And he found the Aggregate Service, a pattern that promised to isolate the subclasses from future changes in the base class constructor:

class abstract CommonLogic
{
    public interface IAggregateService
    {
        IFirstLowLevelService FirstService {get;}
        ISecondLowLevelService SecondService {get;}
        IThirdLowLevelService ThirdService {get;}
    }

    protected CommonLogic(IAggregateService aggregateService) {}
}

class SpecificLogic : CommonLogic
{
    public SpecificLogic(
        IHighLevelService highLevelService,
        IAggregateService aggregateService)
    : base(aggregateService) {}
}

Furthermore, by tapping into the power of Castle DynamicProxy2, the developer crafted a device that could dynamically generate aggregate services, completely removing the burden of implementing classes for each aggregate service interface.

Finally, the valiant adventurer approached the Senior Developer and presented the pattern and how it could free them from distress merely by aggregating constructor-injected dependencies into one dependency. Seeing its brilliance, the aggregate service pattern was implemented throughout the Source spreading light and joy to the team. Changes could now be made to the base class dependencies by merely changing the IAggregateService interface, and no change would have to be done to the subclasses ever again.

So great was the joy and relief that the Senior Developer declared:

The Aggregate Service belongs to all developers of the land and shall thus be contributed to Autofac.

Share

Generate generic factories with Autofac

With Autofac, factory delegates can be generated based on delegate signatures. This article shows how this is done and also shows a solution to using generic delegates with Autofac.

One of the features I like the most in Autofac is the ability to register a factory in the container. A factory in this context is “some method that knows how to build and return an instance of some type”.

Factories are useful when you need fine-grained control over when dependencies should be resolved. Also, if you have dependencies that requires data input (e.g. a constructor parameter) and you need some way of passing that data into the dependency, a factory is your friend.

With Autofac it gets even better. Using C# I can declare a delegate that represents the signature of such a factory, register the delegate in my container and voila! Autofac generates the implementation based on the signature.

So I could declare a delegate like this:

public delegate ICustomerService CustomerServiceFactory();

and have it injected in, say, one of my controller classes, like this:

public class CustomerController
{
    private CustomerServiceFactory _customerServiceFactory;
    public CustomerController(CustomerServiceFactory customerServiceFactory)
    {
        _customerServiceFactory = customerServiceFactory;
    }
}

My controller now have the ability to decide when to create the service instance and still not need to know how.

To make the sample complete (thus far) I’ll show how the Autofac container setup looks like at this point:

var builder = new ContainerBuilder();
builder.Register<CustomerService>();
builder.RegisterGeneratedFactory<CustomerServiceFactory>();
builder.Register<CustomerController>();

This works great. And was fairly easy too don’t think? Now imagine that these classes and delegates was a small part of a real system, with hundreds of controllers and services. Having to declare a factory delegate for each service becomes a pain, let aside registering them in the container.

Wouldn’t it be nice if we could declare only one factory that could build all service types? Turns out you can. Think about the following generic delegate:

public delegate T ServiceFactory<T>() where T:class;

Our updated controller dependency now looks like this:

public class CustomerController
{
    private ServiceFactory<CustomerService> _customerServiceFactory;
    public CustomerController
        (ServiceFactory<CustomerService> customerServiceFactory)
    {
        _customerServiceFactory = customerServiceFactory;
    }
}

Registering such a delegate in the container becomes a bit tricky, since we don’t know T at registration time. Even more so, we cannot generate the factory delegate at registration time! The solution is to register the open generic type coupled with a method that will generate the factory when the dependency is asked for. The Autofac setup should now look like this:

var builder = new ContainerBuilder();
builder.Register<CustomerService>().As();
builder
  .RegisterGeneratedFactoryFromOpenType(typeof(ServiceFactory<>));
builder.Register<CustomerController>();

The RegisterGeneratedFactoryFromOpenType extension method does two things:

  1. Register the open generic type using builder.RegisterGeneric
  2. Attach factory generation code to the OnPreparing event.

The OnPreparing event will be fired when Autofac tries to resolve a closed version of the delegate, in our case the ServiceFactory delegate. Since the event argument contains this type we have everything necessary for generating the factory implementation. And here’s the implementation of RegisterGeneratedFactoryFromOpenType:

public static IGenericRegistrar
    RegisterGeneratedFactoryFromOpenType
    (this ContainerBuilder builder, Type openFactoryType)
{
    return builder.RegisterGeneric(openFactoryType)
        .OnPreparing(Prepare);
}

static void Prepare(object sender, PreparingEventArgs args)
{
    var factoryType = args.Component
        .Descriptor.BestKnownImplementationType;
    var serviceType = factoryType
        .GetMethod("Invoke").ReturnType; 

    var service = new TypedService(serviceType);
    var factory = new FactoryGenerator(factoryType, service); 

    args.Instance = factory
        .GenerateFactory(args.Context, args.Parameters);
}

Note: this code is based on the latest release of Autofac 1.

Share

Plugin mashup in FogBugz 7

With the advent of FogBugz 7 and the new plugin system, new possibilities arise for us FogBugz users.  Here is a tip on how to extend cases in this brilliant system with a custom field and add some functionality to it. Similar to the Related Cases feature, my scenario was that I wanted to connect cases to a wiki page with related information. My recipe is as follows:

Prerequisites

We need the Custom Field plugin by FogCreek and BugMonkey by Michael Pryor. If you’re a FogBugz on Demand user these are readily available in the Plugins admin panel.

Adding a custom field

Next, configure the Custom Field plugin and add a number field named “Wiki Page” with the description “Related wiki page”. Make a note of the description since it will come in handy later.

You will now have an extra field on each case called Wiki Page in which we expect users to enter the page id of a related wiki.

Making the field a link to the wiki page

Now go and configure the BugMonkey plugin. This plugin enables javascript to be executed on every page in your FogBugz installation. Luckily, the FogCreek team have already added JQuery into FogBugz mix so we can ride on that. Add the following script in the javascript text area:

var wikiPage = $(“.content[title=’Related wiki page’]”);
wikiPage.html(“<a href=”/?W + wikiPage.text() + “>Related wiki page</a>”);

The content of the wiki page field is rendered as a div element with class “content” and a title containing the field description. Thus, using JQuery to look up the element is a breeze.

After grabbing the element it is straightforward to add an anchor pointing to the wiki page url.

Conclusion

Ideally I would love to see the Custom Field plugin add the field name to the html element, perhaps as and id. Apart from that, with a plugin system and an eager developer community, systems like FogBugz can really reach new levels of extendability without having to put all possible features into the product up front.

Thumbs up for a great product, Fog Creek!

Share

Windows 7 and booting a virtual hard drive

Having isolated environments for doing development, testing or just trying out new stuff, is extremely valuable. I for one have several environments, one for each client I work for, and a couple for working with internal projects.

In the early stone age we had to make do with multiple computers to achieve such isolated environments. Then came the advent of emulators and virtual computers. For many years now we have had virtualization solutions that run virtualized computers, but with a performance cost in both resource consumption and processing speed. Mind you, the performance keeps improving with better hardware support.

With Windows 7 however, a hybrid solution is introduced. By virtualizing only the disk subsystem, Windows 7 is able to boot from a file system that is completely contained within a Virtual Hard Drive file, or VHD. The end result is that OS and applications execute on “the bare metal” while a thin virtualization layer redirects disk IO to the VHD file residing on the bare-metal disk.

Guest author Thomas Sandberg gives a quick rundown on how to set up booting from Virtual Hard Drives with Windows 7. Read the article here!

Share