10 March, 2013

TypeLITE - TypeScript interfaces from .NET classes

In the last few weeks I was doing some client-side development in TypeScript. It is amazing tool, that increased my productivity in client-side development dramatically.

To streamline the integration between TypeScript and C# code on the server I wrote a simple utility that generates TypeScript interfaces from our POCO classes. It help us a lot in keeping our client-side code in sync with the server side-code - when a server-side class changes, TypeScript interface is automatically updated and if the TypeScript code isn't compatible with the updated interface, TypeScript compilation fails with nice, descriptive message - a huge difference form previous experience with pure JavaScript.

I think this utility might be useful for other developers, so I made it available under MIT license. It's called TypeLITE.


POCO classes
public class Person {
    public string Name { get; set; }
    public int YearOfBirth { get; set; }

    public Address PrimaryAddress { get; set; }
    public List<address> Addresses { get; set; }

public class Employee : Person {
    public decimal Salary { get; set; }

public class Address {
    public string Street { get; set; }
    public string Town { get; set; }

Generated TypeScript interfaces
interface Person {
  Name: string;
  YearOfBirth: number;
  PrimaryAddress: Address;
  Addresses: Address[];

interface Employee extends Person {
  Salary: number;

interface Address {
  Street: string;
  Town: string;

Usage instructions are available on Bitbucket on the project page. Any comments or suggestions are welcome.

28 January, 2013

Linking BitBucket with JIRA

Last week we started using the issue tracking system JIRA. To take full advantage of all features we wanted to integrate our repositories on BitBucket with JIRA - it should be easy, there is an official  DVCS Connector plugin for this task.

Installation of the plugin was really smooth, after couple minutes spend on configuration, we were able to push changesets to our repository and they immediately appeared in the activity stream of the project. At the first glance it seemed that everything is working just fine, but as we tried more advanced features a problem appeared - smart tags weren't working. (Smart tags is a nice feature, that allows you to edit issues in JIRA with the commit message - e.g. LS-15 #time 15m #close)

We checked and rechecked configuration of JIRA / Bitbucket and everything seemed exactly as in the installation guide. After some tests we tracked down the problem to user accounts - the user accounts on BitBucket weren't linked to the user accounts in JIRA, since issue changes in our JIRA can be made only by authorized users, smart tags couldn't work. Both JIRA and Bitbucket accounts have the same usernames and the same emails, but it isn't enough. 

After couple tries we finally found the solution - to successfully link the author of the commit with the JIRA user (and thus enable smart tags), the commit has to been made with the correct username. Is seems that BitBucket credentials are irrelevant for this case - they are necessary to push changes to BitBucket, but they aren't used by JIRA.

The username can be set in the mercurial.ini file or in UI, if you are using TortoiseHg

The correct format of the username is

Username <UserEmailInJIRA>

e.g. Lukas Kabrt <lukas@kabrt.cz>

I hope this might save somebody few minutes, because this detail isn't mentioned in the documentation (or it is well hidden :-) )

26 November, 2012

Message bus for ASP.NET MVC application

I am working on a modular ASP.NET MVC application, one of the problems is communication among modules. At the beginning, with just 3 - 4 modules, it might seem possible to call methods among modules directly. As the system grows, number of modules increases and dependencies among modules become more complex, such solution become impractical.

I didn't need anything fancy, just a simple publisher/subscriber pattern implementation for the single application, so I decided to write my own 'library'.

Publisher - subscriber pattern


The core of the implementation is the MessageBus class. A publisher obtains an instance of the MessageBus (from IoC container), sends a message and the MessageBus distributes the message to appropriate subscribers.

Subscribers need to implement the IMessageSubscriber<TMessage>  interface, so they can process messages of the desired type.

public interface IMessageSubscriber<TMessage> where TMessage : IMessage {
    void Handle(TMessage msg);

The actual implementation of MessageBus is pretty simple, the difficult part - managing references to subscribers is done by an IoC container (encapsulated in IDependencyResolver). An IoC container is usually already in place in MVC applications, so why reinvent a wheel ...  

public class MessageBus : IMessageBus {
    IDependencyResolver _resolver;

    public MessageBus(IDependencyResolver resolver) {
        _resolver = resolver;

    public void Send<TMessage>(TMessage message) where TMessage : IMessage {
        var subscribers = _resolver.Resolve<IMessageSubscriber<TMessage>>();
        foreach (var subscriber in subscribers) {

The final piece of the implementation is registering all necessary classes in the IoC container - in this case I used Autofac.

ContainerBuilder builder = new ContainerBuilder();

To send a message publisher needs to obtain an instance of the MessageBus from the IoC container and than send the message.

bus = container.Resolve<IMessageBus&gt();
SampleMessage msg = new SampleMessage() { Content = message };

And that's it - a simple message bus, that fulfill my requirements in about 20 lines of code. You can download the source code of the MessageBus with a MVC demo project from GitHub

21 July, 2012

Modular MVC application - building DBContext on the fly

I am building a modular ASP.NET MVC application and this task brings a lot of interesting challanges. One of them is to design a data access layer.


We are using Entity Framework in our solutions and for this project we'd like to take advantage of new features of the Entity Framework, especially Code First development and data migrations.

Any module in our application might want to save some data to the database - in order to simplify communication with database, the application core provides bunch of classes responsible for wiring up all the stuff like connection strings, entity configurations, etc. With that infrastructure in place, we can use the same, simple code to access data anywhere in our application ... and keep in mind that our domain model is spread across multiple modules and possibly across multiple assemblies. How have archived that?


If you are using Entity framework Code First, the most of the actions involve DbContext class. It provides methods for adding new entities, retrieving existing ones from database, saving changes and much more. Typically you create derived class with properties of DbSet<TEntity> type to expose collections of entities and EF will do all the work.

public class GuestbookContext : DbContext {
    DbSet<Comment> Comments { get; set; }

Entity framework internally uses a conceptual model to map entities and tables. In order to create it EF needs types of entities to include in the model. It the previous example it's done by exposing DbSet<Comment>, but this solution isn't applicable in our case because we don't know types of the entities types at compile time. Fortunately there are other ways - the one we have chosen uses DbModelBuilder class and creating DbContext from the model produces by the builder. The whole process is encapsulated in the DbContextBuilder.Build method.

public DbContext Build(DbContextConfig config) {
    var factory = DbProviderFactories.GetFactory(config.ConnectionString.ProviderName);
    var connection = factory.CreateConnection();
    connection.ConnectionString = config.ConnectionString.ConnectionString;

    if (config.Model == null) {
        DbModelBuilder builder = new DbModelBuilder();
        foreach (var entity in config.EntityCatalog) {

        config.Model = builder.Build(connection).Compile();

    return new DbContext(connection, config.Model, true);

The DbContext class contains data neccessary to build and configure DbContext.

public class DbContextConfig {
    public ConnectionStringSettings ConnectionString { get; set; }
    public IEnumerable<IEntityConfig> EntityCatalog { get; set; }
    internal DbCompiledModel Model { get; set; }

EntityCatalog property contains a collection of IEntityConfig objects, that instructs DbModelBuilder which entities should be included in the model and how these entities should be mapped to the database. To avoid any manual use of reflection or manual registration of the modules, EnityCatalog property is populated by MEF.

Along with model classes every module includes a configuration class that implements IEntityConfig interface and is used to setup DbModelBuilder, if denoted with Export attribute, this class is automatically discovered by MEF.

public class Comment {
    public int ID { get; set; }
    public string Author { get; set; }
    public string Text { get; set; }

public class CommentConfig : IEntityConfig {
    public void Configure(DbModelBuilder builder) {

Using MEF to find all IEntityConfig classes:

public static IEnumerable<IEntityConfig> DiscoverEntities(Assembly assembly) {
    var configuration = new ContainerConfiguration().WithAssembly(assembly);

    using (var container = configuration.CreateContainer()) {
        return container.GetExports<IEntityConfig>();

It is almost finished the only task left is to initialize the DbContextBuilder application at application start-up.

var contextConfig = new DbContextConfig();
    contextConfig.ConnectionString = ConfigurationManager.ConnectionStrings["DomainModelDb"];
    contextConfig.EntityCatalog = DiscoverEntities(Assembly.GetExecutingAssembly());


For the sake of simplicity this example loads model class only from the current assembly. but trust me it's working with multiple assemblies as well.


DbContextBuilder class implements singleton pattern (I know I could have done better, but it's prototype ...)  so its instance is available across application. In my controllers I can instantiate a new instance of the DbContext by calling DbContextBuilder.Instance.Build().

public ActionResult Index() {
    using (var ctx = DbContextBuilder.Instance.Build()) {
        var comments = ctx.Set<Comment>().ToList();
        return View(comments);

The sample project with complete source code can be download from my Bitbucket repository.

19 July, 2012

Entity Framework going opensource

Just three months after Microsoft released the whole ASP.NET stack under an opensource license, there is another surprise. As announced today on Scott Hanselman's blog and Scott Gu's blog Microsoft is releasing the Entity Framework under Apache 2.0 license.

The new home of the Entity Framework is entityframework.codeplex.com site. Nice introduction to the structure of source code and the whole process of development inside the EF team was published on the Arthur Vickers blog.

So let's start hacking :-)

31 May, 2012

Debugging javascript application on mobile devices

I have been stuck with javascript application development in last few weeks. Even though Javascript isn't my the most favorite language, it's interesting experience that brings new challenges.

We are developing a web application that should work on personal computers and mobile devices (iPhone, iPad, Android phones and tablets, ...). The core of our application is the same for both platforms, but UI is little different. We'd like to give users the best possible experience and in the case of our application it means working with touch events a lot. 

Using touch events isn't difficult, but debugging application with these events can be really painful.

Opera Dragonfly is your friend

Without proper tooling it would be almost impossible do debug this kind of user input intensive application on mobile devices. Thanks to guys from Opera you can have such tools for free.

Every desktop Opera browser contains Opera Dragonfly - an extension that allows developers to inspect DOM of the page, monitor network traffic, monitor resources used by the page and debug Javascript. It isn't anything special - almost all browsers have some kind of developer console, but Opera has another ace in it's sleeves - remote debugging and Opera mobile emulator. Yes, Google Chrome and Firefox mobile offers some kind of remote debugging support, but Opera wins with it's ease of use. Configuration of the remote debugger is really easy and you got all the functions of the Opera Dragonfly - even breakpoints in javascript code.

 Step by step instructions

  • Run Opera mobile emulator, choose a device and launch it

  • Configure Dragonfly to accept remote connection by clicking icon in the toolbar

  • Configure Opera Mobile to connect to Dragonfly by visiting page "opera:debug", entering correct connection settings (if you are running Dragonfly and Emulator on the same computer, IP address is  or localhost) and clicking connect.
  • Navigate to the page you want to debug
That's it. Now you have Opera Mobile Emulator talking to the Dragonfly and vice-versa. You can set breakpoints in javascript files, inspect DOM elements by selecting them directly in the DOM emulator, monitor network traffic and lot of other things :-)

Of course you can use real physical device with Opera Mobile instead Opera Mobile emulator, but I found the emulator more convenient during development. From my experience emulator is better for application development and physical device is better for testing overall user experience.

28 March, 2012

ASP.NET MVC 4, ASP.NET Web API and Razor going opensource

A bombshell landed in my RSS reader this morning - ASP.NET MVC 4, ASP.NET Web API and Razor are going open source!

As announced on the ScottGu's blog as well as on the Scott Hanselman's blog - Microsoft is releasing  ASP.NET MVC 4, ASP.NET Web API and Razor under the Apache 2.0 license. The new home for the projects is Codeplex.

All products will continue to be fully suported and developed by Microsoft, but will be accepting contributions from the community as well. Also being released under Apache 2.0 opens a lot of new possibilities - e.g. building your custom version of the projects.