Wednesday, 18 February 2009

Spark View Engine in ASP.Net MVC

I ran across something today, the Spark view engine.  I’ve never used another view engine before so running through a few tutorials was very interesting.  It appears to be far more appropriate (at a first glance) for ASP.NET MVC than the Web Forms view engine.  Here is a fantastic video on how to integrate it with ASP.NET MVC.

I guess before I ever considered using the Spark view engine I’d have to answer the following questions:

1. How well supported is it,

2. How many developers are fluent enough with it to develop code with it.

3. Can intellisense work with it correctly in visual studio

4. Can it work with ASP.NET MVC Areas

If it scores well in all these areas it is definitely something I’m going to consider for future projects.  If I find out the answers to the above, I’ll post them here.

Wednesday, 4 February 2009

LINQ Best Practice 2 – One Data Source Per Repository, Inner and Outer Joins in LINQ

I’ve been using LINQ a lot with my new project, in particular with the Entity Framework.  I have learned a lot about good practices with LINQ and I figured it would be a good idea to post them up here.  Contained in these posts are all those things I’ve learned and suggest could be useful to you.  They are best practices that work for me, if they work for you then great, but everyone’s solution is different.

My first post was about how you can use the repository pattern to increase testability and separate concerns within your code.  This second post extends on that into the data sources.

The Data Source

This is the main table that your repository is concerned with.  If at all possible you should have only one of these per repository.  The main reason for this is the testability and maintainability of your code, setting up a single data source is far more simple than setting up several.  You will also find that the code produced will be more standardised and far more simple to read.

Example Code:

public class TypeRepository : ITypeRepository
{
    private LynxEntities _Entities;
    private IQueryable<Type> _DataSource;
    
    // Implementation here.
}

One to One Inner Join

This is the single data source for my TypeRepository.  This is easy to implement with when you’re only selecting data relating to that type, but when you’re selecting data that crosses multiple tables this becomes a little more difficult.  For example if my Type table has a foreign key to the Usage table and I want to get all types that are within a particular usage I would immediately think of doing a join.  This isn’t really the LINQ way, instead you should use the generated object dependencies to your advantage:

rfType ITypeRepository.GetByUsage(string usage, string type)
{
    rfType result = (from t in _DataSource
                     where t.rfUsage.Name.Equals(usage)
                         && t.Name.Equals(type)
                     select t).FirstOrDefault();
    return result;
}

 

One to Many Inner Join

This becomes a lot more tricky when you’re dealing with a one to many reference, or even worse a many to many reference.    Say for example my Type table has many usages, the above code is not going to work because there are lots of usage records.  But you can do a simple join to ensure that data exists.  You don’t need a second data source to do a join, though most of the examples out there will tell you to do it that way, you can do it like this.

rfType ITypeRepository.GetByUsage(string usage, string type)
{
    rfType result = (from t in _DataSource
                     from u in t.rfUsage
                     where u.Name.Equals(usage)
                         && t.Name.Equals(type)
                     select t).FirstOrDefault();
    return result;
}

One to Many Left Outer Join

The above is fine if you know the dependency exists, but when if you want to get the item even if it’s usage doesn’t exist, but you also want to retrieve the usage?  The Entity Framework is not great at lazy loading through LINQ, if you need something, you really have to ask for it.  So if I were to write:

public Type Get(string type)
{
    return (from t in _DataSource
            where t.Name.Equals(type)
            select t).FirstOrDefault();
}
 
// Other Code
Type returnedType = _TypeRepository.Get("myType");
ProcessUsage(returnType.rfUsage);

The ProcessUsage method would get NULL every time I called the method, even if there were several usages available in the database.  This is because the lazy loading of L2E (LINQ to Entities) is not all that great.  So you need to outer join all the tables you want to use data from.

return (from t in _DataSource
        where t.Name.Equals(type)
 
        let u = (from uLO in t.rfUsage
                 where uLO.Name.Equals(usage)
                 select uLO)
 
        select new 
        {
            t, u
        }).FirstOrDefault().t;

The middle part is the left outer join.   We tell LINQ to get t and u from the database but then return only t.  The entity framework will get all the data and return it in the t object representing the type.  You can also use this to limit your data selection of course.

Test Cases

Now when writing your tests all you need to do to setup a source of data is:

[TestInitialize()]
public void InitialiseTest()
{
    _Items = GetTestData();
    _Target = new TypeRepository(_Items.AsQueryable());
}
 
private List<Type> GetTestData()
{
    List<Type> items = new List<Type>
    {
        new Type
        {
            TypeID = 1,
            Name = Constant.Type.Thickness,
            rfUsage = new rfUsage
            {
                UsageID = 1,
                Name = Constant.Usage.ItemSize
            }
        },
        new Type
        {
            TypeID = 1,
            Name = Constant.Type.Weight,
            rfUsage = new rfUsage
            {
                UsageID = 1,
                Name = Constant.Usage.ItemSize
            }
        }
    };
 
    return items;
}

If you had multiple data sources (like one for type and one for rfusage) you would have to set each of them up individually and the links between them would not be setup in the same way as the links setup in the Entity Framework.

Tuesday, 3 February 2009

ASP.NET MVC RC1 and Areas

I just found out something today that is very important if you have implemented areas in ASP.NET MVC as per this post by Phil Haack.  With RC1, strongly typed views that do not have code behind files (as per the RC1 setup) will throw an error:

UPDATE: Parser Error Message: Could not load type 'System.Web.Mvc.ViewPage<ModelObject>'

The problem is that your view folders within each of the areas does not have a Web.config file like your root view folder.  With RC1, the Web.config file in the root folder needs to have this:

<pages validateRequest="false"
   pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
   pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
   userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <controls>
        <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
    </controls>
</pages>

The simple solution is to make a Web.config file for each of the Views folders in your areas that is exactly the same as the one in your root view path.  Things will start working after that.

Tuesday, 20 January 2009

LINQ to Entities and the “Collection was modified” exception – A solution!

I’ve found that something that is a common mistake when dealing with collections.  Say I want to go through a list of objects and delete every one that matches a certain criteria.  The simplest code would be something like this:

foreach (Item item in _Entities.Item)
{
    if (/* criteria */)
    {
        _Entities.Item.Remove(item);
    }
}

But that’s not going to work.  When the Remove method is run you will get an exception:

{"Collection was modified; enumeration operation may not execute."}    System.Exception {System.InvalidOperationException}

Ok, so if you think about it it makes sense really, you’re trying to remove an item from the enumeration that you’re currently enumerating through.  But what’s the solution?

Turns out there are many ways you can tackle this problem.  One way is to write each of your delete segments so that you build a list of items to delete first and then delete them from the master list.  It works but it’s a lot of extra code.  Another option is to turn the Colleciton into an array before looping through it and deleting the items.

I like this solution better:

public void RemoveIf<T>(ICollection<T> collection, Predicate<T> match)
{
    List<T> removed = new List<T>();
    foreach (T item in collection)
    {
        if (match(item))
        {
            removed.Add(item); 
        }
    }
 
    foreach (T item in removed)
    {
        collection.Remove(item);
    }
 
    removed.Clear();
}

I’ve written my own helper method to remove an item if it meets a certain criteria.  The helper method will take a Predicate (the same as the Collection.Exists method) and if an items in the collection match the Predicate it will add them to a list, then cycle through the list and remove them.

To implement it use code similar to the following:

RemoveIf(_Entities.Item, delegate(Item i) { return /* criteria */; });

Which is the same style of code you would use if you were trying to implement the Collection.Exists method.  If you wanted to delete all the items from one list if they exist in another, you can of course chain the Exists method into the RemoveIf helper also like so:

RemoveIf(_Entities.Item, delegate(Item itemRemove) 
{
    return !otherList.Exists(delegate(Item itemSearch) 
    { 
        return itemSearch.CustomerID == itemRemove.CustomerID; 
    });
});

But the downside is that the code will get a little confusing for people who haven’t used delegates much, or at all.

Wednesday, 14 January 2009

LINQ Best Practice 1 – The Repository Pattern

I’ve been using LINQ a lot with my new project, in particular with the Entity Framework.  I have learned a lot about good practices with LINQ and I figured it would be a good idea to post them up here.  Contained in these posts are all those things I’ve learned and suggest could be useful to you.  They are best practices that work for me, if they work for you then great, but everyone’s solution is different.

Use the Repository Pattern

I can’t stress this enough, if you’re going to use LINQ to Entities then you will benefit enormously from the repository pattern, in particular if Unit Testing and / or TDD is important to you.  The repository pattern defines that you create an interface to your data source within a context and only use this interface for retrieving the data.  Your unit tests for controllers or business logic can then mock the interface into the data to provide logical feedback for the tests.

Here is an example repository for the Item table within my database.  I have a table called Item and I define standard methods for my repositories to implement, Get, Save, Search etc.

This is the interface:

public interface IItemRepository
{
    Item Get(int itemCodeID);
    List<ValidationErrorResult> Save(Item item);
    void Delete(Item item);
    List<ValidationErrorResult> Add(Item item);
    List<Item> Search(string name, string description, int pageNumber, int itemsPerPage);
}

I like to return lists, some people may wish to return IQueryable.  If you return an IQueryable then you’re accepting that the data may not be physically fetched from the database when within the repository source.  In our project I believe it is better to be in control of when we get the data, but this is not for everyone.  There is a great article about returning List over IQueryable or not here.

And my implementation:

public class ItemRepository : IItemRepository
{
    private IQueryable<Item> _DataSource;
    private LynxEntities _Entities;
 
    public ItemRepository(LynxEntities entities)
    {
        _Entities = entities;
        _DataSource = _Entities.Item;
    }
 
    public ItemRepository(IQueryable<Item> dataSource)
    {
        _DataSource = dataSource;
    }
 
    Item IItemRepository.Get(int itemCodeID)
    {
        // implementation
    }
 
    List<ValidationErrorResult> IItemRepository.Save(Item item)
    {
        // implementation
    }
 
    void IItemRepository.Delete(Item item)
    {
        // implementation
    }
 
    List<ValidationErrorResult> IItemRepository.Add(Item item)
    {
        // implementation
    }
 
    List<Item> IItemRepository.Search(string name, string description, int itemsPerPage, int pageNumber)
    {
        // implementation
    }
}

I’ve removed all the implementation because it’s not relevant.  The important part is the constructors.  The first constructor is the default constructor.  It is very important with LINQ to Entities that you pass the entity object into the constructor instead of creating it.  This is because if you don’t and you get items from another repository with a different entity object then your relationships are not going to work.

The second constructor allows me to construct a list of objects with which to test in my unit testing environment.  We use MSTest and Rhino Mocks to support our testing framework.  Each of my repository classes will have a test class associated with it, and each test class will have a method to setup the data to test with.

List<Item> data = new List<Item>
{
    new Item
    {
        // Item details
    },
    new Item
    {
        // Item details
    }
};
 
ItemRepository target = new ItemRepository(data);

Allowing me to easily test my database functions without having to connect to any form of real data source.  You will run into problems when you try to run the SaveChanges methods of the entity model as when unit testing your entities object will be null.  You can just ensure that you test for null before saving changes to the data model like this:

if (_Entities != null)
{
    _Entities.SaveChanges();
}

Implementing the Repository Pattern

Once we have the repository we need to implement it.  Code examples are the best way to show this so I’ll do that.  We’re using ASP.NET MVC so our controllers define the instance of the repository.  As the controller is the master of the unit of work, we create the entity model in the controller and give it to the repositories that we create instances of.

// Constructor
public ItemController()
{
    LynxEntities entities = new LynxEntities();
    _ItemRepository = new ItemRepository(entities);
    _AnotherRepository = new AnotherRepository(entities);
 
}

Because we are using the same entity model in all the repositories in our unit of work I can load an object from my “AnotherRepository” and set it against an item pulled from my “ItemRepository” if I need to.  If they did not share the same entity model you would get an error when you tried to save changes.

In my test classes for my controllers we use Rhino Mocks to mock the interface to the repository.  Each of my test classes defines a SetupMocks method that will setup the mocks for each interface I am mocking.

private void SetupMocks(MockRepository mocks, IItemRepository items)
{
    using (mocks.Record())
    {
        // Setup the item repository
        SetupResult
            .For(items.Get(""))
            .Return(null).Repeat.AtLeastOnce();
        SetupResult
            .For(items.Get("itemA"))
            .Return(new Item
            {
                // Item Details
            }).Repeat.AtLeastOnce();
    }
}

Now I can unit test my controller just as if it were connected to the database.

The Repository Pattern is a very straight forward solution that gives you the advantages of testable code, reusable code modules and separation of concerns between the database business rules and the application business rules.  Hopefully you find it useful.