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.

Oct 21, 2011

Setup SQL Server Compact 4 to unit test NHibernate related code

Most of the time to fake data base SQL lite data base is used. But it has certain differences from SQL server. With release of SQL Compact 4 it becomes really good choice to mock data base calls. So in this post I will describe a way of setting up NHibernate to work with SQL CE local data base. So here are our goals:

  1. Each test fixture has its own fresh DB instance
  2. NHibernate SessionFactory is same for all the tests (performance is still important in tests)
  3. Caching of NHibernate doesn’t stands on isolation way (each test will have clean factory, without any cached entities)
  4. Works just after getting from source control with no additional configuration

First of all we need to install sql ce tools for visual studio. After done that we can add an empty data base file to our tests project:

Sql server compact 4.0 local data base

lets call it db. This file is going to be the one that is going to be copied for each test and where NHibernate will create its tables.

Now lets create a base class for tests that are going to use NHibernate:

public class DbTests
{
    protected static ISessionFactory factory;
    static Configuration nhConfig;

    static DbTests()
    {
        File.Copy("db.sdf", "Temp.sdf", true);
        nhConfig = NhConfigure();
        factory = nhConfig.BuildSessionFactory();
    }

    [TestFixtureSetUp]
    public void Setup()
    {
        File.Copy("db.sdf", "Temp.sdf", true);
        new SchemaExport(nhConfig).Execute(true, true, false);
    }

    [TestFixtureTearDown]
    public void TearDown()
    {
        File.Delete("Temp.sdf");
    }

    static Configuration NhConfigure()
    {
        DomainMapper mapper = new DomainMapper();
        HbmMapping mappings = mapper.CompileMappingFor(new[] { typeof(TestEntity) });

        var configuration = new Configuration();
        configuration.SessionFactory()
            .Integrate.Using<MsSqlCe40Dialect>()
            .Connected.By<SqlServerCeDriver>()
            .Using("Data Source=Temp.sdf");

        configuration.AddDeserializedMapping(mappings, "domain");
        
        return configuration;
    }
}

What is done here is pretty straight forward. Each test fixture will get its own empty data base with new schema installed.

Also you will need to install SqlServerCompact package from nuget in order to get SqlServerCeDriver support.

There is an interesting bug when using identity columns with SQL CE. You can get NHibernate.AssertionFailure : null identifier exception. Here is how you can solve it.

The last thing we want to take care about is NHibernate cache. Each test probably will have its own ISession instance, so only second level caching should be handled. Here is how we can clean up it:

static void ClearCache()
{
    factory.EvictQueries();
    foreach (var collectionMetadata in factory.GetAllCollectionMetadata()) 
        factory.EvictCollection(collectionMetadata.Key);
    foreach (var classMetadata in factory.GetAllClassMetadata()) 
        factory.EvictEntity(classMetadata.Key);
}

Just add this method call to Setup and that it. As always working sample attached:

Source code sample doesn’t contain nuget packages and uses this way of working. So don’t be scared of everything red in ReSharper after open solution. Just build it.

Oct 7, 2011

Getting started with knockout.js

Recently I’ve had some time to learn knockout.js. It’s a javascript library for building rich internet applications. In spite of wonderful tutorials section on main site learning wasn’t as smooth as I would like it to be. Mainly because of some changes in 1.3 version and version 1.2 (that is currently used for tutorials).

Before reading further I would suggest you to watch a great video about knockout.js. After seeing it I’m not sure that you need to read further Smile.

Now we are going to build an editing form for Northwind data base products. The desired result is the following form:

Products editing form

So when page is loaded only categories list is visible at the left. When user selects category, list of products is shown where user is able to select concrete product to edit and save.

So lets create a new ASP.NET MVC 3 internet web application. As data access layer we’ll use Entity Framework. So add new ADO.NET Entity Data Model, name it Northwind and point to your DB instance.

To get started we need a list of categories, so navigate to HomeController and add the following code to Index action:

public ActionResult Index()
{
    using (Northwind context = new Northwind())
    {
        var categories = context.Categories.Select(c => new {c.CategoryID , c.CategoryName}).ToList();
        ViewBag.Categories = categories;

        return View();
    }
}

That’s it for now on server side. Now navigate to Index.cshtml view where everything interesting is going to happen. In order to get knockout working execute next nuget command: Install-Package Knockoutjs. It will download latest version of knockout library and place it under Scripts folder. Include it in your view.

First of all we need to render a list of categories. Knockout 1.3 has build in ability to generate html based on template. So to render list of categories add the following html with javascript on view:

<ul data-bind="foreach: categories">
    <li>
        <a data-bind="text: $data.CategoryName"
            href="javascript:void(0);">
        </a>
    </li>
</ul>
<script type="text/javascript">
   var viewModel = {
        categories: @Html.Raw(Json.Encode(ViewBag.Categories))
    };
   ko.applyBindings(viewModel);
</script>

It will render li with anchor for each category that came from server. Notice that in order to get JSON representation of categories list Json.Encode method is used.

On this small example we already can see the MVVM pattern in action. View is bounded to model that is stored in js objects. So how we have strong separation of data from its representation even on client side. We can apply unit testing of javascript without messing with UI and have all the procs of concerns separation (e.g. build other UI for mobile devices).

Now lets work with some events. We want to show products when some category is selected. Lets create a server side logic for retrieving products in category. Add a new controller like this:

public class ProductsController : Controller
{
    public ActionResult InCategory(int id)
    {
        using (Northwind context = new Northwind())
        {
            var result = context.Products.Where(x => x.CategoryID == id)
                                         .Select(p => new {p.ProductID, p.ProductName})
                                         .ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}

So when category is clicked we should somehow call this method and show returned results. Lets add a method for our view model that should be called when category is selected and bind click event to it. Here what we should get:

<a data-bind="text: $data.CategoryName,
              click: function(){ viewModel.selectCategory($data.CategoryID); }"
    href="javascript:void(0);">
</a>
<script type="text/javascript">
   var viewModel = {
        categories: @Html.Raw(Json.Encode(ViewBag.Categories)),
        selectCategory: function(categoryId) {
               console.log(categoryId);
        }
   };
   ko.applyBindings(viewModel);
</script>

Now if you open FireBug and refresh a page when you click on category you will see its id being printed in console.  Now lets store selected category id (we will need it further in tutorial). In order to do it, lets add a new property for viewModel and set in selectCategory method:

selectedCategory: ko.observable(),
selectCategory: function(categoryId) {
    this.selectedCategory(categoryId);
}

Couple of things needs to be noticed here: initial value of the selectedCategory is ko.observable – it will create an empty value, but when this value is changed all interested in it parts of application will be notified. Second thing is that assigning value is done not via =, but with calling that property and passing value. Now we are ready to display list of products. In order to do it lets add a table template:

<table>
    <thead>
        <th>
            ProductName
        </th>
    </thead>
    <tbody data-bind="foreach: products">
        <tr>
            <td>
                <a data-bind="text: $data.ProductName"
                   href="javascript:void(0);">                    
                </a>
            </td>
        </tr>
    </tbody>
</table>

So we have a table that is bound to the products field of view model. Now we need fill this collection:

viewModel.products = ko.observableArray([]);

ko.dependentObservable(function() {
    if(this.selectedCategory()) {
       $.get('@Url.Action("InCategory", "Products")/' + this.selectedCategory(), this.products);
    }
}, viewModel);

With the help of dependentObservable method we can create a property that is going to change when another property changes. Knockout will figure out by himself that this method should be called when selectedCategory method is called. So now you should have working list of categories with ability to view products in it.

Next step is displaying and edit form. Steps should be already familiar. Lets add a server side method for retrieving order by its id:

public ActionResult Get(int id)
{
    using (Northwind context = new Northwind())
    {
        var result = from p in context.Products
                     where p.ProductID == id
                     select new { p.ProductID, p.UnitPrice, p.ProductName, p.UnitsInStock, p.UnitsOnOrder };
        return Json(result.FirstOrDefault(), JsonRequestBehavior.AllowGet);
    }
}

And on the client side:

viewModel.selectedProductId = ko.observable();
viewModel.selectedProduct = ko.observable(‘’);

viewModel.selectProduct = function(productId) {
  viewModel.selectedProductId(productId);
};

ko.dependentObservable(function() {
     if(this.selectedProductId()) {
         $.get('@Url.Action("Get", "Products")/' + this.selectedProductId(), this.selectedProduct);
     }
}, viewModel);

After binding a click event of product anchor to selectProduct method we need last thing to do – implement template for editing:

<fieldset>
    <legend data-bind="text: selectedProduct().ProductName">       
    </legend>
    <dl>
        <dt>
            Product name
        </dt>
        <dt>
            <input type="text" name="ProductName" data-bind="value: selectedProduct().ProductName" />
        </dt>
    </dl>
</fieldset>

So now user is able to select category and product. I won’t cover saving data to db in this tutorial. Lets add some nice features. For example we want to highlight selected category and selected product in order to show user where he is now. Lets add a new style called current:

.selected
{
    background-color: Aqua;
}

And we want apply it to current category and product. Now we can do it with just only bindings:

css: {selected: $data.CategoryID === viewModel.selectedCategory()}
css: {selected: $data.ProductID === viewModel.selectedProductId()}

First one goes for category anchor template, second one is for product item template in list.

Full source code for this example: