Execute SQL scripts as part of EF code first db initialization

Create a folder for sql scripts and put all *.sql files there. Set the build action of the sql files to EmbeddedResource. Call ExecuteScripts(context) method below from the Seed(context) method of your db initializer.

private void ExecuteScripts(DbContext context)
{
    foreach (var script in GetScripts())
    {
        string sql = GetFromResources(script);
        if (!string.IsNullOrWhiteSpace(sql))
        {
            context.Database.ExecuteSqlCommand(sql);
        }
    }
}

private IEnumerable GetScripts()
{
    return GetType().Assembly
        .GetManifestResourceNames()
        .Where(r => r.EndsWith(".sql"));
}

private string GetFromResources(string resourceName)
{
    using (var stream = GetType().Assembly.GetManifestResourceStream(resourceName))
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}

Converting event based async calls to Task

Working on a new WinPhone app the other day I encountered an interesting problem which made me scratch my head quite a bit. I needed to read the list of appointments from the phone’s calendar. No big deal, right? Using the MVVM pattern I created a separate view model for my page and a service where I wanted to put all my phone specific stuff. The initial signature of my method was

public IEnumerable<Appointment> GetAppointments();

When trying to implement the method I found out that the calendar API uses the old style event based async pattern (EAP). I tried couple of different methods to wrap the async call and the result from the event in a single method call and failed miserably. After that I tried changing the method to the new async/await style. I knew I had to return a Task<T> so the signature of my method became

public Task<IEnumerable<Appointment>> GetAppointments();

But I still did not know how to make it work. And then I finally came across the TaskCompletionSource class that already solves my problem:

public Task<IEnumerable<Appointment>> GetAppointments()
{
    return Task.Run(() =>
    {
        var tcs = new TaskCompletionSource<IEnumerable<Appointment>>();

        var appts = new Appointments();
        appts.SearchCompleted += (o, e) =>
        {
            tcs.TrySetResult(e.Results);
        };
        appts.SearchAsync(DateTime.Today, DateTime.Today.AddDays(1), "appointments");

        return tcs.Task;
    });
}

Beautiful, isn’t it?

INotifyPropertyChanged

The thing that bothers me the most about MVVM and similar patterns is the ugly code that you have to write just to implement INotifyPropertyChanged interface on you view models. So instead of my nice and shiny class “A” I need to write the horrible monster “B”.

// exhibit "A"
class Sale
{
    public string Name { get; set; }
    public Decimal Price { get; set; }
    public Decimal Quantity { get; set; }
    public Decimal Total { get { return Price * Quantity; } }
}

// exhibit "B"
class Sale : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            if (name != value)
            {
                name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }

    private Decimal price;
    public Decimal Price
    {
        get { return price; }
        set
        {
            if (price != value)
            {
                price = value;
                NotifyPropertyChanged("Price");
                NotifyPropertyChanged("Total");
            }
        }
    }

    private Decimal quantity;
    public Decimal Quantity
    {
        get { return quantity; }
        set
        {
            if (quantity != value)
            {
                quantity = value;
                NotifyPropertyChanged("Quantity");
                NotifyPropertyChanged("Total");
            }
        }
    }

    public Decimal Total { get { return Price * Quantity; } }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Everybody can see what the problem with “B” is. Not only the code is ten times longer but it does not mean or do anything particularly fancy. The code that I can live with looks something like this:

// exhibit "C"
class Sale : BaseClass
{
    [NotifyPropertyChanged]
    public string Name { get; set; }

    [NotifyPropertyChanged("Price", "Total")]
    public Decimal Price { get; set; }

    [NotifyPropertyChanged("Quantity", "Total")]
    public Decimal Quantity { get; set; }

    public Decimal Total { get { return Price * Quanitity; } }
}

As of this moment I do not know how to make “C” happen. My guess would be that we either need some (pre-) compiler magic or something like an aspect (as in AOP). I am willing to bet $20 that something like this will either happen in one of the MVVM frameworks very soon (and that will be my framework of choice) or Microsoft will implement it in the next version of C#.

Application Settings

The .net framework provides a powerful way to provide application settings in app.config file. There is also the ability to use command line parameters but they are accessed in completely different fashion. I created couple of classes to simplify parameters handling and provide a declarative syntax.

public class MyAppsSettings : Settings
{
    [CommandLineParam("/u")]
    public string UserName { get; set; }

    [CommandLineParam("/p")]
    public string Password { get; set; }

    [ConnectionString("MyDB")]
    public string MyDBConnStr { get; set; }

    [AppSetting("Mode")]
    public string Mode { get; set; }

    [AppSetting("DefaultMode", "Test")]
    public string DefaultMode { get; set; }
}

Here is the complete source code:

[AttributeUsage(AttributeTargets.Property)]
public class CommandLineParamAttribute : Attribute
{
    public string Name { get; set; }

    public string DefaultValue { get; set; }

    public CommandLineParamAttribute(string Name)
    {
        this.Name = Name;
        this.DefaultValue = string.Empty;
    }

    public CommandLineParamAttribute(string Name, string DefaultValue)
    {
        this.Name = Name;
        this.DefaultValue = DefaultValue;
    }
}

[AttributeUsage(AttributeTargets.Property)]
public class ConnectionStringAttribute : Attribute
{
    public string Name { get; set; }

    public ConnectionStringAttribute(string Name)
    {
        this.Name = Name;
    }
}

[AttributeUsage(AttributeTargets.Property)]
public class AppSettingAttribute : Attribute
{
    public string Key { get; set; }

    public string DefaultValue { get; set; }

    public AppSettingAttribute(string Key)
    {
        this.Key = Key;
        this.DefaultValue = string.Empty;
    }

    public AppSettingAttribute(string Key, string DefaultValue)
    {
        this.Key = Key;
        this.DefaultValue = DefaultValue;
    }
}

public class Settings
{
    public Settings()
    {
        CommandLineParams clp = new CommandLineParams();

        Type type = this.GetType();

        foreach (PropertyInfo pi in type.GetProperties())
        {
            object[] arr = pi.GetCustomAttributes(true);
            foreach (object o in arr)
            {
                if (o is CommandLineParamAttribute)
                {
                    string name = ((CommandLineParamAttribute)o).Name;
                    string value = ((CommandLineParamAttribute)o).DefaultValue;

                    if (clp.Contains(name)) value = clp[name];

                    pi.SetValue(this, value, null);
                }

                if (o is ConnectionStringAttribute)
                {
                    string name = ((ConnectionStringAttribute)o).Name;
                    string conn = ConfigurationManager.ConnectionStrings[name].ConnectionString;
                    pi.SetValue(this, conn, null);
                }

                if (o is AppSettingAttribute)
                {
                    string key = ((AppSettingAttribute)o).Key;
                    string value = ((AppSettingAttribute)o).DefaultValue;

                    if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
                        value = ConfigurationManager.AppSettings[key];

                    pi.SetValue(this, value, null);
                }
            }
        }
    }
}

Command Line Params

This is a simple class that I use for parsing command line params.

CommandLineParams clp = new CommandLineParams();
string server = clp["/s"];
bool test = clp.Contains("/test");

When the class is constructed for the first time I parse all command line parameters and save them in a dictionary. Then I can check if a parameter exists and access it using an indexer.

I chose to make the dictionary static so I don’t parse the parameters every time. I don’t feel great about it but I’ll leave it like this for now. It would be perfect if there were static indexers, then the code at least would have been prettier…

Here is the complete source code:

public class CommandLineParams
{
    private static Dictionary dict;

    public string this[string key] { get { return dict[key]; } }

    public bool Contains(string key)
    {
        return dict.ContainsKey(key);
    }

    public CommandLineParams()
    {
        if (dict == null)
        {
            dict = new Dictionary();

            string[] args = System.Environment.GetCommandLineArgs();

            foreach (string s in args)
            {
                string ParamName, ParamValue;
                if (ParsePair(s, out ParamName, out ParamValue))
                    dict.Add(ParamName, ParamValue);
                else
                    dict.Add(s, string.Empty);
            }
        }
    }

    // TODO: refactor using RegEx
    bool ParsePair(string Pair, out string Name, out string Value)
    {
        int pos = Pair.IndexOf("=");
        if (pos >= 0)
        {
            Name = Pair.Remove(pos, Pair.Length - pos);
            Value = Pair.Remove(0, pos + 1);
            return true;
        }

        // otherwise
        Name = string.Empty;
        Value = string.Empty;
        return false;
    }
}

Controlling Enum .ToString()

This is a neat trick I found yesterday. I wonder why I never thought of it myself. In the .net framework there is no way how to control .ToString() for enumerations. To work around that an extension method can be created as well as an attribute to decorate the different values of the enumeration. Then we can write something like this:

public enum TestEnum
{
    [EnumString("Value One")]
    Value1,

    [EnumString("Value Two")]
    Value2,

    [EnumString("Value Three")]
    Value3
}

EnumTest test = EnumTest.Value1;
Console.Write(test.ToStringEx());

The code to accomplish this is pretty simple:

[AttributeUsage(AttributeTargets.Field)]
public class EnumStringAttribute : Attribute
{
    private string enumString;

    public EnumStringAttribute(string EnumString)
    {
        enumString = EnumString;
    }

    public override string ToString()
    {
        return enumString;
    }
}

public static class ExtensionMethods
{
    public static string ToStringEx(this Enum enumeration)
    {
        Type type = enumeration.GetType();
        FieldInfo field = type.GetField(enumeration.ToString());
        var enumString =
            (from attribute in field.GetCustomAttributes(true)
             where attribute is EnumStringAttribute
             select attribute).FirstOrDefault();

        if (enumString != null)
            return enumString.ToString();

        // otherwise...
        return enumeration.ToString();
    }
}

[TestMethod()]
public void ToStringTest()
{
    Assert.AreEqual("Value One", TestEnum.Value1.ToStringEx());
    Assert.AreEqual("Value Two", TestEnum.Value2.ToStringEx());
    Assert.AreEqual("Value Three", TestEnum.Value3.ToStringEx());
}

The credit goes to this post.