May 30, 2013

Migrating from Castle ActiveRecord

Unfortunately Castle ActiveRecord project is abandoned and not developed anymore. Latest release uses NHibernate 3.0 and is not compatible with last NHibernate due  to the changes in API of dynamic proxy.

So we have decided to remove dead assembly and move on. In order to do that there some major steps that needed to be done:

  1. Rewrite all dependent code that used ActiveRecordMediator class
  2. Implement ISession, ISessionFactory lifetime management
  3. Reconfigure NHibernate without using AR wrappers over configuration
  4. Export existing AR mappings based on attributes to XML
  5. Migrate XML mappings to mapping by code

First two steps are tightly related. Methods in ActiveRecordMediator class are easily translated into appropriate analogs in ISession object. We already had a Repositories layer that was used to encapsulate all NHibernate related code, so it was not a really big problem to inject session to them.

For lifetime management we implemented same solution that was described in my blog earlier – let the IoC container resolve it.

Now about third step. NHibernate has not a lot of configuration in fact. All the new API descriptions can be found here. AR doesn’t add a lot, so nothing fancy here.

Export ActiveRecord mappings to XML

With exporting mappings things are starting to get interesting. I couldn’t find an out of the box way in AR to do that. So in fact I had to copy paste methods and to make something from AR public to support this. So here is a mapper class that allows exporting (btw AR sources that we have used before removing it). Line 21 is a place where you have map as a string and do anything you want with it.

Migration from hbm.xml to code

Sure you can stop migration here and just keep XML mappings. But that is just not good enough. Now there is a task of converting XML mappings to code. What is the best tool to covert XML to anything else?.. Well its XSLT. Sorry for that, but it is as it is. So I’ve created a transformation that is capable to do what is needed. Source is too long to put here, so I’m putting a link to appropriate gist. There are some preparations need for mappings – remove all nhibernate namespaces and wrappers like

<hibernate-mapping  auto-import="true" default-lazy="false" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:nhibernate-mapping-2.2">
    <!-- mapping here should be kept --> 
</hibernate-mapping>

It uses XSLT 2.0 that is not supported by default .net tools. To run it you can use saxonica tool. In order to run it you can use following command line:

c:\Program Files\Saxonica\SaxonPE9.4N\bin\Transform.exe -s:mappings.xml -xsl:nbmToCs.xslt -o:mappings.cs

So after doing that you will have new nice mappings. Not everything that is supported by NHibernate is supported by XSLT, I’ve added only things that we needed. If you need to add something, feel free to contact me.

Apr 5, 2013

Downloading multiple files on Windows Phone 8

What I think is missing from the internet is a posts with examples of solving simple tasks that usually takes longer then they should. So I decided to share some.

What I wanted to do is to download a number of images from the internet, combine them and use it as a background for my app. The simple way to do that is with the help of build in BitmapImage class:

BitmapImage image = new BitmapImage(new Uri("http://test.jpg"));
image.ImageOpened += (sender, args) => {
    Process(); // here we have image downloaded
};

Each time I need to create new Uri I ask myself why there is no constructor that accepts string…

So what went wrong with the code above? The problem is that I needed all images content at the same time to combine them and put results to cache or something. First solution I came up with was using Interlocked.Increment() method. It solved problem in some way. But code became complicated and I didn’t like that. So here a better way to do that. In order to have determined point in time where all images are downloaded I created my file downloader helper:

public class ImageDownloader
{
    public static async Task<MemoryStream> Download(string url)
    {
        var request = (HttpWebRequest)HttpWebRequest.Create(url);

        var response = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
        var result = new MemoryStream();
        using (var responseStream = response.GetResponseStream())
        {
            responseStream.CopyTo(result);
        }
        result.Position = 0;

        return result;
    }
}

Maybe returning Stream is not the best way to do it, but I think its ok for this example post. So code is simple and self-explanatory. It just downloads any file by provided URL.

Having that helper, we can compose list of tasks and execute processing just after receiving all images:

var imageUrls = new[] {
    string.Format("http://placekitten.com/{0}/{1}", imageWidth, imageHeight), 
    string.Format("http://placekitten.com/g/{0}/{1}", imageWidth, imageHeight)
};

var downloadTasks = new List<Task<MemoryStream>>();
foreach (var image in imageUrls)
{
    downloadTasks.Add(ImageDownloader.Download(image));
}

Task.Factory.ContinueWhenAll(downloadTasks.ToArray(), tasks => {
    WriteableBitmap image1 = new WriteableBitmap(imageWidth, imageHeight);
    image1.LoadJpeg(tasks[0].Result);
    WriteableBitmap image2 = new WriteableBitmap(imageWidth, imageHeight);
    image2.LoadJpeg(tasks[1].Result);

    Image1.Source = image1;
    Image2.Source = image2;
}, 
    CancellationToken.None, 
    TaskContinuationOptions.None, 
    TaskScheduler.FromCurrentSynchronizationContext() // this will make sure we are changing UI in the thread that is allowed to do that.
);

This code uses Task Parallel Library’s method ContinueWhenAll. It allows you to execute task after all other tasks are finished.

So that all what is needed. It is really simple, but took me a while to find the right classes and syntax to solve the problem.

You can download a working example here.

Jul 31, 2012

Setup kdiff3 with TortoiseGIT for 3 way merge

Its always an issue because you need to know what values to pass for merge tool so just as a reminder:

C:\Program Files (x86)\KDiff3\kdiff3.exe %base %mine %theirs -o %merged

kdiff3 as merge tool

The only problem with it is that when you exit kdiff3, it remains to be conflicted and you need manually mark as resolved.

Mar 28, 2012

ASP.NET MVC extension points in action

Recently I made a tech talk about my alt.net web stack of love. It has lots of things there. Validation, NHibernate, Routing etc. So here are slides:

Source code for it is on bitbucket. Its purpose is just see it all in action. If you want, you should move code your new/old projects. Don’t try to make some type of project template out of it.

To try things out

Once again link to sources.

I was asked to give some kind of practice task to try all stack together. So here it is:

Implement blog details page to show posts inside it. So when I open localhost/blogs/3 I should see something like:

untitled_page

When I navigate to post details page I should be able to see post content and leave comments. Just like on this blog Smile.

Mar 5, 2012

Using ASP.NET MVC 4 WebAPI with NHibernate and Autofac

Wanted to try how they play together. So it will yet another tutorial with sample application built from scratch. First of all I don’t want to manage ISession and ISessionFactory lifetime manually, so I’ll use Autofac to do the job. So after creating new Web API project execute following commands in nuget console:

Uninstall-Package EntityFramework
Install-Package NHibernate
Install-Package Autofac.Mvc3

First remove EntityFramework, then install NHibernate and Autofac.Mvc3 package. The last package has some really useful extensions like implementation of dependency resolver for MVC and instance per web request life style. Now setup autofac:

var builder = new ContainerBuilder();
// Register ISessionFactory as Singleton 
builder.Register(x => NHibernateConfigurator.BuildSessionFactory())
    .SingleInstance();
// Register ISession as instance per web request
builder.Register(x => x.Resolve<ISessionFactory>().OpenSession())
    .InstancePerHttpRequest();

// Register all controllers
builder.RegisterAssemblyTypes(typeof(ProductsController).Assembly)
    .InNamespaceOf<ProductsController>()
    .AsSelf();

// override default dependency resolver to use Autofac
DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

// this override is needed because WebAPI is not using DependencyResolver to build controllers 
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
    DependencyResolver.Current.GetService, 
    DependencyResolver.Current.GetServices);

This code is executed one time on Application start. I won’t put code for domain (its simple one entity) and NHibernateConfigurator class you can find them on github.

Now we are ready to add our first controller that is going to expose web api:

public class ProductsController : ApiController
{
    private readonly ISession nhSession;

    public ProductsController(ISession nhSession)
    {
        if (nhSession == null) throw new ArgumentNullException("nhSession");
        this.nhSession = nhSession;
    }

    public IQueryable<Product> Get()
    {
        return nhSession.Query<Product>();
    }
}

Notice that I don’t need to do anything to get the ISession instance. Autofac will find that in order to get it it needs ISessionFactory and will configure factory first to give ISession for controller. Now we can visit url http://localhost:54270/api/products and see our list of products in XML format. Notice that because returned type is IQueryable request to http://localhost:54270/api/products?$top=1&$skip=0 will return only first product from the list.

PUT, POST and DELETE methods are pretty straight forward and won’t be different from the same in entity framework. So I won’t cover it. The last thing I want to try is transaction management. In mvc projects I used to do it with action filter. Here is slight catch involved. There are two ActionFilterAttribute classes. One in System.Web.Http.Filters and other is in System.Web.Mvc. In order to get working in webapi we need to implement the one in System.Web.Http.Filters namespace. So the implementation is the following:

using System.Data;
using System.Web.Mvc;
using NHibernate;
using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute;

namespace webapi.Infrastructure
{
    public class TransactionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
            DependencyResolver.Current.GetService<ISession>().BeginTransaction(IsolationLevel.ReadCommitted);
        }

        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            ITransaction currentTransaction = DependencyResolver.Current.GetService<ISession>().Transaction;

            try
            {
                if (currentTransaction.IsActive)
                    if (actionExecutedContext.Exception != null)
                        currentTransaction.Rollback();
                    else
                        currentTransaction.Commit();
            }
            finally
            {
                currentTransaction.Dispose();
            }
        }
    }
}

I’ve put all the code there just be sure that you can figure out all required namespaces. The last thing I want to notice here is that if you implement System.Web.Mvc version of action filter, you won’t see any error messages or exceptions. Your filter just won’t work.

All code you can find here.

Mar 1, 2012

Convert tfs repository to mercurial

The easiest way I’ve found to do it is the following:

  1. With the help of git-tfs tool convert tfs repository to git one with the following command:
    git tfs clone %FullUrlToYourTfsServer% $/%PathToProject%

    I suggest you to verify that your network connection to TFS is stable because this operation will take a lot of time and if it fail you will need to start from the beginning.
  2. Have hg installed (I’m using tortoisehg) and configure its ConvertExtension.
    In order to do that navigate to C:\Users\%UserName% and open mercurial.ini file, and add this at the end:
    [extensions] hgext.convert=
  3. Execute convert command on git repository with following command:
    hg convert -s git -d hg %PathToGitRepository%
  4. Have fun with hg

Nov 22, 2011

Implementing Repository with NHibernate

In spite of common now approach of using in memory data base for unit testing NHibernate related code I still do like to have repository. The reason for that is simplicity. In most applications transactions are managed separately, either via action filters or HTTP modules. So in unit test you need to repeat logic not for just creating of object graph, but for saving it also.

What I always wanted is ability to write code like this in tests:

var product = new Product {
    Price = 100,
    Name = "Test"
};

product.Category = new Category {
    Name = "Food"
};

IRepository<Product> products = new List<Product>();

And all the logic for testing queries can be done with LINQ to objects (you will need integration tests to verify real query generated by the ORM). No need for huge test setup and so on.

With release of on NH 3 LINQ provider was greatly improved (but still has a lot of troubles). In this post I’m going to show implementation of Repository described in Fabio’s post. The main idea described there is that IRepository interface should just look like this:

/// <summary>
/// Repository for basic entities persistence actions
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IRepository<T> : ICollection<T>, IQueryable<T>
    where T : Entity
{
    T Get(long id);
}

The only additional method is Get. Its just useful in a lot of cases. Everything else is provided with mentioned interfaces. Implementation from NHibernate point of view is pretty straight forward and I won’t describe it, you can see in the project sample. The interesting part is mocking one. Here is code for one of the methods:

public class FakeRepository<T> : List<T>, IRepository<T>
    where T : Entity
{
    public FakeRepository(IEnumerable<T> products) : base(products)
    {
    }

    public Expression Expression
    {
        get
        {
            return ((IEnumerable<T>)this).Select(x => x).AsQueryable().Expression;
        }
    }
}

So now we can implement test like this:

[Test]
public void Repository_can_be_created_from_simple_list()
{
    Product product = new Product();
    
    List<Product> products = new List<Product>();
    products.Add(product);

    IRepository<Product> repository = new FakeRepository<Product>(products);

    Assert.That(repository, Is.Not.Empty);
}

And it will pass. Also all production code can do any sort of LINQ queries and they will succeed.

The last and probably the most scary thing - fetching. LINQ to NHibernate has Fetch and FetchMany extension methods. But when you use them on regular list exception is thrown:

System.InvalidOperationException : There is no method 'Fetch' on type 'NHibernate.Linq.EagerFetchingExtensionMethods' that matches the specified arguments

So we need to abstract fetching away. In order to do that, we will need our own Fetch and FetchMany methods and IFetchRequest interface with the following signature:

public interface IFetchRequest<TQueried, TFetch> : IOrderedQueryable<TQueried> 
{
}

Instance of this interface will be returned as a result of calls to our new extension methods, that look like this:

public static class EagerFetch
{
    public static IFetchRequest<TOriginating, TRelated> Fetch<TOriginating, TRelated>(this IQueryable<TOriginating> query, Expression<Func<TOriginating, TRelated>> relatedObjectSelector)
    {
        return FetchingProvider().Fetch(query, relatedObjectSelector);
    }

    // ... other methods

    public static Func<IFetchingProvider> FetchingProvider = () => new NhFetchingProvider();
}

I’m showing only method here, others are implemented in the same way (and yes, it is ugly). But the good news is that you write it once, and forget. Interesting part is FetchingProvider that performs fetching itself. The instance of provider is provided by Func, that means that in tests you can easily change provider instance. With such code somewhere in test fixture setup:

EagerFetch.FetchingProvider = () => new FakeFetchingProvider();

Implementation of NHibernate provider is on the github (together with fake provider). FakeProvider in its turn just doing nothing. But in theory we can mock it and set some verifications, but I don’t think it’s a good idea.

Full source code with working solution you can find on the github.