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.

Fun with extension methods or don’t envy Visual Basic

We all like the ToString() method conveniently located in every class. But unfortunately there is no ToInt() method where you need it most. We are not completely out of luck however thanks to a new feature in c# called extension methods. The extension methods are simply static methods that behave like if they were from another class. “Why not just extend the actual class?” someone might ask. Well, sometimes we just can’t do that and other times it is just plain inconvenient, imagine changing every string in out program to be from a type MyString…

So let’s create our ToInt() method that will extend the string class:

public static class Extensions
{
    public static int ToInt(this string s)
    {
        return Int32.Parse(s);
    }
}

[TestMethod()]
public void ToIntTest()
{
    Assert.AreEqual(123, "123".ToInt());
}

A little bit weird syntax but nothing that we can’t live with. Now each time we have a string that is composed of digits we can easily convert it to a number.

Another two methods that I love from Visual Basic are Left(i) and Right(i):

public static string Left(this string s, int length)
{
    return s.Substring(0, length);
}

public static string Right(this string s, int length)
{
    return s.Substring(s.Length - length);
}

[TestMethod()]
public void LeftRightTest()
{
    Assert.AreEqual("AB", "ABCD".Left(2));
    Assert.AreEqual("CD", "ABCD".Right(2));
}

Notice that the first parameter with the keyword this is the class that we are extending and the next parameter(s) are the parameters of the method. I really can’t imagine what they (Anders?) were thinking when they came up with this syntax but one can get used to it I guess…

One last thing… Visual Basic has this nice inline xml syntax that c# does not have:

Dim xml = <tag></tag>

So I was thinking…

public static XElement ToXml(this string s)
{
    return XElement.Parse(s);
}

[TestMethod()]
public void ToXmlTest()
{
    var xml = @"<tag></tag>".ToXml();
    Assert.AreEqual("tag", xml.Root.Name);
}

Here is a link to the MSDN article describing the extension methods in greater detail.

Creating an ORM in C#

A great article in 7 parts:

http://www.gutgames.com/post/Creating-an-ORM-in-C-Part-1.aspx

http://www.gutgames.com/post/Creating-an-ORM-in-C-Part-2.aspx

http://www.gutgames.com/post/Creating-an-ORM-in-C-Part-3.aspx

http://www.gutgames.com/post/Creating-an-ORM-in-C-Part-4.aspx

http://www.gutgames.com/post/Creating-an-ORM-in-C-Part-5.aspx

http://www.gutgames.com/post/Creating-an-ORM-in-C-Part-6.aspx

http://www.gutgames.com/post/Creating-an-ORM-in-C-Part-7.aspx