1 2 3 4 5 6 7 8 9 10 11 12

Fun with Nuget

14/04/2015

I recently finished the first release of my 2nd Nuget package which provides a class to convert an ADO.Net DataTable to a list of objects. This is the result of an effort to create a library for the conversion technique outlined in this post.

I've also created a Nuget package to help out with MVC 5 Radio Buttons located here.

This post summarises some things I learned from creating these Nuget packages.

Simplest package

For simply packing a class library targeting a single version of the .Net framework you can simply invoke the Nuget.exe with the path to the .csproj:

.\.nuget\NuGet.exe pack .\Path\To\Project.csproj -Prop Configuration=Release

If your solution doesn't have a copy of the Nuget exe in the .nuget solution folder you can download the exe separately.

This command will create the nuget package in the current directory with the metadata declared in the AssemblyInfo.cs for the project.

Creating a specification

The default nuspec specification file created by calling:

...

Entity Framework 6 Enums with String column

23/03/2015

I recently watched Jimmy Bogard's excellent NDC presentation on Domain models to learn about how to implement a real world domain model.

One of the things Jimmy does in his presentation is to refactor his enum to use a base class allowing far more expressive enums with custom behaviour

There are a few versions of this custom enum base class around but I'm going to be using this one.

Annoyingly Entity Framework (EF) doesn't support mapping database fields to enums unless you use an int column in your database. This might be good enough for your implementation however it seems a bit fragile to couple your database to a mystery int defined in code somewhere which could be changed by any user who doesn't realise what they're changing.

For a marginally less fragile and more domain model friendly enum I used an adapted version of Jimmy's enumeration class:

The main change is to the DisplayName property. We add a setter because Entity Framework is only going to bring back the string display name and we need to map to the underlying value field to get the proper enum.

public string DisplayName
{
    get
    {
        return this.displayName;
    }

    // Entity Framework will only retrieve and set the display name.
    // Use this setter to find the corresponding value as defined in the static fields.
    protected set
    {
        this.displayName = value;

        // Get the static fields on the inheriting type.
        foreach (var field in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
        {
            // If the static field is an Enumeration type.
            var enumeration = field.GetValue(this) as Enumeration;
            if (enumeration == null)
            {
                continue;
            }

            // Set the value of this instance to the value of the corresponding static type.
            if (string.Compare(enumeration.DisplayName, value, true) == 0)
            {
                this.value = enumeration.Value;
                break;
            }
        }
    }
}

This simply checks the static fields on the instance of the enumeration class and finds the enumeration with the matching name.

We also change the private displayName and value fields to remove the readonly access modifier (and the underscores because I've never been able to adapt to the convention):

...

FakeItEasy Heisenbugs

17/03/2015

Update: the problem has been solved in version 2.0.0 of FakeItEasy.

I was recently facing an issue where my FakeItEasy tests were sometimes randomly failing. I'm specifying that it was the FakeItEasy tests because I managed to isolate to the failures to 2 tests which were using:

var thing = A.Fake<IInterface>();

The FakeItEasy fake would sometimes ignore the specified setup, such as:

A.CallTo(() => thing.Method()).Returns(true);

The fake would return false or null for reference types.

Analysing the stack trace on the failing test it was due to aggregate Exceptions occurring when running the tests in parallel. There is an issue describing this here.

We were using xUnit as our testing framework which runs tests in parallel by default. Unfortunately both FakeItEasy and Moq aren't threadsafe and this introduces bugs when tests are run in parallel. It seems like other testing frameworks also experience the same problem.

To get around this we disabled parallel test execution in xUnit. This means our tests take longer but are reliable.

If you've run into this issue before and found a better fix I'd be intrigued to hear it.

...

Dependency Injection Containers - Cheat Sheet

01/02/2015

There are a lot of articles out there that describe both Dependency Injection and Inversion of Control. The purpose of this one is to serve as a quick reference for the things I keep forgetting because configuring a DI container is something I do so infrequently. This is a very simple guide showing the easiest scenarios and the simplest syntax. It walks through the same 3 steps:

1. Create Container
2. Configure Container
3. Retrieve from Container

In the following DI libraries:

  • Ninject
  • Unity
  • SimpleInjector
  • StructureMap

Of course it will feature examples tenuously related to animals.

Principals

A Dependency Injection library makes dependency injection easier by doing the work of wiring up an "object graph" (collection of related objects) for your application to use. This is generally done at the entry point to an application:

  • For console apps this is in the main method of Program.cs.
  • For MVC and Web API apps this is in Startup.cs.
  • For class libraries it is difficult to include dependency injection in the library itself as these have no defined entry point. One approach is to rely on the calling application to wire up the dependencies.
  • For WebForms apps it is possible to setup the DI container in the Global.asax Application_Start method however it's a bit more complicated.

Console App Example

In this example we're going to begin building a console app which simulates an ecosystem of toads.

picture of a toad

...

EF7 Table Mapping Exception

15/01/2015

Note: This blog post relates to a library undergoing development and as such the information is likely to become outdated.

Even with Database First through the EDMX gone in Entity Framework 7 it's still possible to work with existing databases.

While trying this out with one of my databases I ran into the following Exception:

<Message>An error has occurred.</Message>

<ExceptionMessage>Invalid object name 'SomeClass'.</ExceptionMessage>

<ExceptionType>System.Data.SqlClient.SqlException</ExceptionType>

<StackTrace>
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)[...]
</StackTrace>

The Entity Framework "Invalid object name [class name]" exception means that the matching table for one of your classes hasn't been found.

In this case I'm trying to map the SomeClass to the underlying SQL table Map.Test:

[Table("Test", Schema="Map")]
public class SomeClass
{
    public int Id { get; set; }
}

The current version of EF7 (7.0.0-rc1-11953) does not have support for mapping using attributes in this way. Instead one must use Fluent configuration in the DbContext as follows:

public class MyContext : DbContext
{
    public DbSet<SomeClass> SomeClasses { get; set; }

    protected override void OnConfiguring(DbContextOptions options)
    {
        options.UseSqlServer(ConnectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<SomeClass>().ForRelational().Table(tableName: "Test", schemaName: "Map");
    }
}

The mapping is configured fluently in the OnModelCreating method. For slightly more useful information about setting EF7 up see this link.

I hope this helps!

...
1 2 3 4 5 6 7 8 9 10 11 12