A Simple CQRS Pattern Using C# in .NET

For years in my apps I’ve used a Data Mapper pattern or even the Repository pattern to mediate between the business domain and the database. One thing I’ve learned is that something like this interface is no help at all:

public interface IEntity
{
    int ID { get; set; }
}

public interface IRepository where T : IEntity
{
    T Get(int id);
    IEnumerable GetAll();
    int Add(T item);
    bool Update(T item);
    bool Delete(T item);
}

In all but the most trivial app it proves too inflexible to be useful. This is because no two entities are alike. In one case calling a Get() function and passing in an ID is just fine. But I might have a two-part key for another entity. Or I might need GetByLastName() instead. So I end up adding extra functions to the concrete repository class. But If I’m adding functions outside the contract then I might as well not use the contract at all. Another problem with a non-trivial app is the repository even for a single entity quickly becomes a big ball of mud (if you’re lucky) or a God class if several developers are working together and there’s no discipline. If I have to wade through 30 fetch functions to get to the one I want that’s not maintainable. There are other growing pains that emerge a few years down the road. But others — notably Ayende — have documented those problems so I won’t rehash that here. Instead I want to describe a simple CQRS pattern as an alternative that I’ve found to be flexible and maintainable over the long haul.

Continue reading “A Simple CQRS Pattern Using C# in .NET”

Oregon Star Party 2015

The Oregon Star Party (OSP) gathers every year in August in the high desert of the Ochoco Mountains in Central Oregon. This year it was brutally hot during the day and bone-chilling cold at night. In other words a typical year. Kat and I attended again this year so I wanted to capture the experience and document some of the sketches I made. First here is a gorgeous sunset taken from our remote 5,000-foot elevation base camp:

Of course the pretty colors came at a heavy price as wild fires continued to burn over 200,000 acres throughout Oregon. The fires at the Warm Springs Reservation directly to the west of us had already consumed about 55,000 acres. The dark orange sunlight had to refract through all of that smoke settling in the distant valley.

Continue reading “Oregon Star Party 2015”

Hancock Woman Pictograph Solar Calendar

A few weeks ago I volunteered to help Bernie Taylor, a fellow member of Rose City Astronomers, to investigate whether the so-called “Hancock Woman” pictograph out near Fossil, Oregon might be a solar calendar.

Bernie wrote the book Biological Time and he was kind enough to give me a copy. I have only had time to skim it heavily at this point but I highly recommend it to anyone interested in biological rhythms and the way animal behavior changes during lunar and solar cycles in nature.

Continue reading “Hancock Woman Pictograph Solar Calendar”

Polymorphic Associations in Entity Framework

In this post I’m going to show how to use EF 6.1 Code First to model polymorphic associations between a base class and two derived classes. In EF this is called “table-per-type” (TPT) inheritance. Microsoft has a walkthrough on using EF to map TPT inheritance in a domain model. Unfortunately it was written before EF Code First and is now dated. A search turned up some information here and there but it too was dated. It took me the better part of an afternoon to get it working in EF Code First so I thought I should post the solution. More after the jump…

Continue reading “Polymorphic Associations in Entity Framework”

AuthorizationAttribute with Windows Authentication in MVC 4

With MVC 4 the Visual Studio team released the SimpleMembershipProvider. I’ve used it and I’m not so sure “simple” is the word I’d use for it. 🙂 In any case it works great for a forms authentication scenario. And if you really want to deep dive into it I highly recommend Long Le’s blog. My solution is after the jump…

Continue reading “AuthorizationAttribute with Windows Authentication in MVC 4”

Cursorless Iteration in SQL

Knowing when to use cursors and when to avoid them is key to being a successful developer. Here’s a very useful snippet to use when you want to use a cursorless iteration over a resultset. In the example I create a temp table of widgets and then enumerate each row to print them out:

set nocount on;
  
declare @i int
declare @curr_widget nvarchar(20)
   
declare @widget_table TABLE (
    id smallint primary key identity(1,1)
    , widget_color nvarchar(10)
    , widget_type nvarchar(10)
 )
   
 -- populate the widget table with records
 insert @widget_table (widget_color, widget_type) values ('Red','Widget')
 insert @widget_table (widget_color, widget_type) values ('Orange','Gear')
 insert @widget_table (widget_color, widget_type) values ('Yellow','Rotor')
 insert @widget_table (widget_color, widget_type) values ('Green','Crank')
 insert @widget_table (widget_color, widget_type) values ('Blue','Cog')
 insert @widget_table (widget_color, widget_type) values ('Indigo','Flywheel')
 insert @widget_table (widget_color, widget_type) values ('Violet','Propeller')
  
 -- cursorless enumeration of the widget table 
 SET @i = 1
 WHILE (@i <= (SELECT MAX(id) FROM @widget_table))
    BEGIN
    -- get the widget color and type
    SELECT 
        @curr_widget = widget_color + ' ' + widget_type
    FROM 
        @widget_table WHERE id = @i
  
    PRINT @curr_widget
          
    -- increment counter for next row
    SET @i = @i + 1
 END

The key to making this work of course is to have an identity column to order the rows and the MAX function to know when you’re done. It’s a great little trick to try in your next project.

 

Generics and Nullable Types

It is often useful in OR mapping to analyze a value type that might be null prior to setting it in a business entity. For instance, SqlDateTime type (in System.Data.SqlTypes namespace) is a value type that is nullable. You can call IsNull to check and Value to retrieve the underlying DateTime type:

SqlDateTime d = new SqlDateTime();
if (d.IsNull)
{
    Trace.WriteLine("SqlDateTime is null");
}

d = DateTime.Now;
Trace.WriteLine(string.Format("SqlDateTime is {0}", d.Value.ToString()));

This is useful when fetching data from SQLServer. DataSets allow nullable values but strongly-typed classes do not. So if I’m instantiating a business entity, I often call TryParse first to protect against null:

//instantiate SqlCommand cm here
SomeBusinessEntity obj = new SomeBusinessEntity();
DateTime dt = new DateTime();
SqlDataReader dr = cm.ExecuteReader();
if (dr != null) 
{
    while (dr.Read()) 
    {
        obj.ID = (DBNull.Value != dr["ID"]) ? Convert.ToInt32(dr["ID"]) : 0;
        if (DateTime.TryParse(dr["ApprovalDate"].ToString(), out dt))
        obj.ApprovalDate = dt;
    }
}

Wouldn’t it be great to have a DateTime struct in C# that allows for null? A bunch of folks have gnashed their teeth over this issue since the release of .NET. And now .NET Framework 3.0 supports nullable value types. But I’m still in 2.0 land and will likely remain there for some time so here’s my solution. The goal is to support both the above OR mapping logic via generics and to emulate the nullable feature of the SqlDateTime type. In the end we want to do something like this:

Nullable ndt = new Nullable();
if (Nullable.TryParse(DateTime.Now.ToString(), out ndt))
{
    obj.ApprovalDate = ndt;
}

We start with a basic generics-enabled struct with exposed properties Value and IsNull:

public struct Nullable 
{
    private static bool _isnull;
    private T _value;

    static Nullable() 
    {
        _isnull = true;
    }

    public bool IsNull 
    {
        get { return _isnull; }
    }

    public T Value 
    {
        get { return _value; }
        set 
        {
            _value = value;
            _isnull = false;
        }
    }
}

The struct has a private _isnull member which is set to true in the static constructor. Only when the value is set does that flag flip to false. So by default it will be null even if the type is not really null; for instance if the underlying DateTime is initialized at 1/1/0001 or the underlying Int32 is initialized at 0. Now we support the TryParse functionality by adding a delegate function that mimics the signature. Note that I’m not supporting the overloaded method for IFormatProvider but rather keeping it simple:

private delegate bool TryParseDelegate(string s, out T result);

Then add a private static function to do the work:

private static bool ParseNullable(string s, out Nullable result, TryParseDelegate Parse) where T : struct 
{
    if (string.IsNullOrEmpty(s)) 
    {
        result = default(Nullable);
        return false;
    }
    else 
    {
        T t;
        bool success = Parse(s, out t);
        Nullable n = new Nullable();
        n.Value = t;
        result = n;
        return success;
    }
}

At this point it’s just a matter of adding public methods for each type that you need to support. I’ve added two methods, one for DateTime and one for Int32. Here is the complete Nullable struct:

public struct Nullable 
{
    private static bool _isnull; 
    private T _value;
    private delegate bool TryParseDelegate(string s, out T result);

    static Nullable() 
    {
        _isnull = true;
    }

    public bool IsNull 
    { 
        get 
        { 
            return _isnull; 
        }   
    }

    public T Value 
    {
        get 
        {           
           return _value;       
        }
        set 
        {
            _value = value;
            _isnull = false;
        }
    }

    public static bool TryParse(string s, out Nullable result) 
    {
        return ParseNullable(s, out result, Int32.TryParse);
    }

    public static bool TryParse(string s, out Nullable result) 
    {
        return ParseNullable(s, out result, DateTime.TryParse);
    }

    private static bool ParseNullable(string s, out Nullable result, TryParseDelegate Parse) where T : struct 
    {
        if (string.IsNullOrEmpty(s)) 
        {
            result = default(Nullable);
            return false;
        }
        else 
        {
            T t;
            bool success = Parse(s, out t);            
            Nullable n = new Nullable();            
            n.Value = t;
            result = n;
            return success;
        }
    }
}

To exercise the struct:

class Program 
{
    static void Main(string[] args) 
    {
        // exercise Nullable with type DateTime
        Nullable ndt = new Nullable();
        Console.WriteLine(string.Format("Is null? {0}", ndt.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", ndt.Value.ToString()));
        
        ndt.Value = DateTime.Now;

        Console.WriteLine(string.Format("Is null? {0}", ndt.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", ndt.Value.ToString()));
        Console.WriteLine();

        // exercise Nullable with type Int32
        Nullable nint = new Nullable();
        Console.WriteLine(string.Format("Is null? {0}", nint.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", nint.Value.ToString()));
        nint.Value = 42;

        Console.WriteLine(string.Format("Is null? {0}", nint.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", nint.Value.ToString()));

        // exercise TryParse functionality
        if (Nullable.TryParse(DateTime.Now.ToString(), out ndt)) 
        {
            Console.WriteLine(string.Format("Successful TryParse with result {0}", ndt.Value.ToString()));
        }

        if (Nullable.TryParse("99", out nint)) 
        {
            Console.WriteLine(string.Format("Successful TryParse with result {0}", nint.Value.ToString()));
        }

        Console.ReadKey();
    }
}