Use Compile Time Info In C# 5.0 Code

I just stumbled upon a great new feature of C# 5.0 reading  Charles Petzold’s 6th edition of “Programming Windows” (a lot of water gone under the bridge since the 2nd edition, Borland C and I were inseperable!).

One might say “at long last”, but with C# 5.0 you’re now able to include compiler info in your program: Line number, Source file and last – but not least – the method/property name. Apart from logging, the property name being very useful when using the MVVM pattern with XAML.

The so called “Caller Info Attributes” take the shape of annotations, and here is a very small sample program that illustrates these three new annotations:

using System;
using System.Runtime.CompilerServices;

namespace CallerInfoAttributes
{
    class Program
    {
        public static int _myproperty;
        public static int MyProperty
        {
            get
            {
                Log("Get " + _myproperty.ToString());
                return _myproperty;
            }
            set
            {
                Log("Set " + value.ToString());
                _myproperty = value;
            }
        }

        static void Main(string[] args)
        {
            Log("Hello");
            MyProperty = 8;
            MyProperty = MyProperty * 3;

            Console.ReadLine();
        }

        static void Log(string message,
                       [CallerMemberName] string member = "",
                       [CallerFilePath] string file = "",
                       [CallerLineNumber] int line = 0)
        {
            var s = String.Format("{1} ({2}:{3}) - {0}", message, member, file, line);
            Console.WriteLine(s);
        }
    }
}

The output, completely as expected:

image

Checking the generated code in dotNetSpy shows that the compiler actually inserts the compile time strings into the call, making for very good performance especially compared to the previous Expression Tree hacks sometimes used with MVVM:

// Type: CallerInfoAttributes.Program
// Assembly: CallerInfoAttributes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// Assembly location: E:\Projects\CallerInfoAttributes\CallerInfoAttributes\bin\Debug\CallerInfoAttributes.exe

using System;
using System.Runtime.CompilerServices;

namespace CallerInfoAttributes
{
  internal class Program
  {
    public static int _myproperty;

    public static int MyProperty
    {
      get
      {
        Program.Log("Get " + Program._myproperty.ToString(), "MyProperty", "e:\\Projects\\CallerInfoAttributes\\CallerInfoAttributes\\Program.cs", 13);
        return Program._myproperty;
      }
      set
      {
        Program.Log("Set " + value.ToString(), "MyProperty", "e:\\Projects\\CallerInfoAttributes\\CallerInfoAttributes\\Program.cs", 18);
        Program._myproperty = value;
      }
    }

    private static void Main(string[] args)
    {
      Program.Log("Hello", "Main", "e:\\Projects\\CallerInfoAttributes\\CallerInfoAttributes\\Program.cs", 25);
      Program.MyProperty = 8;
      Program.MyProperty *= 3;
      Console.ReadLine();
    }

    private static void Log(string message, [CallerMemberName] string member = "", [CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
    {
      Console.WriteLine(string.Format("{1} ({2}:{3}) - {0}", (object) message, (object) member, (object) file, (object) line));
    }
  }
}

Read more about this small, but important improvement at http://msdn.microsoft.com/en-us/library/hh534540(v=vs.110).aspx

Advertisements

Timing parts of your C# code with a using statement.

Timing (and tracing) specific parts of your code can often be necessary in order to trace what is going on in both a testing and production environment. For the sake of my own memory, and perhaps to the enjoyment of others,  I’ve decided to commit to the memory of the web a method for doing this that I find useful.

At one point I came upon a class in a colleague’s code called the LogicalOperationTimer. It is actually a lot more complicated and feature laden than what is shown here, and other variations exist on the web, but for the sake of principle this will suffice.

The idea is to create an IDisposable class that can wrap the code to be measured in the scope of a “using” statement. When the class is instantiated it starts a timer, and when the “using” scope ends, it automatically calls the Dispose() method of the class where you can the do the magic of saving the timer result to whatever media you prefer. In this case it’s just writing out the result to the console, but more practically it would be persisting it to disk in some form.

Here is the sample timer:

class LogicalOperationTimer : IDisposable
{
    private readonly Stopwatch _stopwatch = new Stopwatch();
    private readonly string _operationname;

    public LogicalOperationTimer(string operationname)
    {
        _operationname = operationname;
        _stopwatch.Start();
    }

    public void Dispose()
    {
        _stopwatch.Stop();
        Console.WriteLine("{0} : {1}ms", _operationname, _stopwatch.ElapsedMilliseconds);

        GC.SuppressFinalize(this);
    }
}

More on the workings of the GC.SuppressFinalize can be found here. Now follows a very simple test of the above class:

    static void Main()
    {
        using (new LogicalOperationTimer("Operation1"))
        {
            // Measure this
            Thread.Sleep(1000);
        }

        // Don't measure this
        Thread.Sleep(200);

        Console.ReadLine();
    }
}

It’s the kind of code I like: short, clear and useful!

RazorEngine, Templating Anywhere.

For the last couple of months I have been deep into building mobile WebApps with jQuery Mobile and MVC 4. I must say that working with MVC, as an old ASP hack, has been a very pleasant experience and change from WebForms. MVC really joins the flexibility and transparency of a scripted language, be it ASP or PHP, with a modern structured approach (maintainability, testability, readability etc).

Working with the View-engine you quickly get the feeling that this could be used for other things, such as generating stuff like SQL, MDX, HTML output for PDF conversion or other report generators.

Enter the CodePlex RazorEngine project, available right inside VS2010 via NuGet, which builds on MVC to deliver the same features for other .Net environments. Other people, like Rick Strahl, have made similar efforts to harness the power of Razor. This guy on CodeProject uses RazorEngine for CSS generation.

Having played with it for a couple of hours I discovered that the documentation and samples aren’t completely up to date, so here is my very simple code sample. I’m sure there’s a lot more to it, but this at least got me started:

using System;
using RazorEngine;
using System.Dynamic;

namespace BatchRazor
{
    public class Test {
        public string Name { get; set; }
    }

    class Program {
        public static void Main(string[] args)
        {
            string template =
                "@{var _v = \"Mr \" + Model.Name; }" +
                "Hello @_v, Welcome to Razor at @DateTime.Now.ToString()!";

            // Anonymous Console.WriteLine(Razor.Parse(template, new { Name = "World" }));

            // Dynamic dynamic d = new ExpandoObject();
            d.Name = "Expando1";

            Console.WriteLine(Razor.Parse(template, d));

            Razor.Compile(template, typeof(ExpandoObject), "complex");
            Console.WriteLine(Razor.Run("complex", d));

            dynamic e = new ExpandoObject();
            e.Name = "Expando2";
            Console.WriteLine(Razor.Run("complex", e));

            // Strongly typed var t = new Test() { Name = "Test" };
            Console.WriteLine(Razor.Parse(template, t));

            Razor.Compile(template, typeof(Test), "complex1");
            t.Name = "Test2";
            Console.WriteLine(Razor.Run("complex1", t));

            Console.ReadLine();
        }
    }
}

Using ExpandoObject (Dynamic) with XML data

Having played with the ExpandoObject as a container for SQL data in a previous post, I’ve been playing a bit with using it for XML data which can be even more dynamic in nature.

Without further ado, here is a method that will do exactly that:

public static IEnumerable<dynamic> GetExpandoFromXml(string file, string descendantid) { var expandoFromXml = new List<dynamic>(); var doc = XDocument.Load(file); var nodes = doc.Root.Descendants(descendantid); foreach (var element in doc.Root.Descendants(descendantid)) { dynamic expandoObject = new ExpandoObject(); var dictionary = expandoObject as IDictionary<string, object>; foreach (var child in element.Descendants()) { if (child.Name.Namespace == "") dictionary[child.Name.ToString()] = child.Value.Trim(); } yield return expandoObject; } }

 

Note that I use a descendantid parameter to specify what part of my XML I want to fetch as dynamic objects.

In my example I was working with an RSS feed, and this is the reason why I ignore the elements that have an empty namespace, and BTW the file parameter can be an URL as well as you can see in the sample.

As I sample, I can get the “item” elements from the RSS feed of this blog like so:

var expandolist = GetExpandoFromXml("https://phejndorf.wordpress.com/feed/", "item");

expandolist.ToList().ForEach(element => Console.WriteLine(element.title));

 

Or perhaps, a bit more exotically, to list all the properties of each dynamic element:

expandolist.ToList().ForEach(element => 
{
    var dictionary = element as IDictionary<string, object>;
    dictionary.ToList().ForEach(d => Console.WriteLine("{0}: {1}",d.Key,d.Value));
});

And that’s all there is to it!

Using C# “dynamic” with SqlDataReader

Type safety is, in my opinion, a lot better than sliced bread. But though the dynamic keyword has to be used very carefully, I still think there are places where it can be an advantage to bring it into play.

For instance when accessing data via SqlDataReader in a dynamic fashion. To that end I suggest wrapping the data reader in a construct that will allow you to return a dynamic class where the columns are accessible by name and not a string reference. This can be done via an ExpandoObject that makes it possible to work with the dynamic class as if it was a dictionary:

private dynamic SqlDataReaderToExpando(SqlDataReader reader)
{
    var expandoObject = new ExpandoObject() as IDictionary<string, object>;

    for (var i = 0; i < reader.FieldCount; i++)
        expandoObject.Add(reader.GetName(i), reader[i]);

    return expandoObject;
}

To create a method for returning the elements of a Sql query in a dynamic fashion can then be implemented like so:

private IEnumerable<dynamic> GetDynamicSqlData(string connectionstring, string sql)
{
    using (var conn = new SqlConnection(connectionstring))
    {
        using (var comm = new SqlCommand(sql, conn))
        {
            conn.Open();
            using (var reader = comm.ExecuteReader())
            {
                while (reader.Read())
                {
                    yield return SqlDataReaderToExpando(reader);
                }
            }
            conn.Close();
        }
    }
}

 

There are of course all the usual problems with late binding that misspelling and erroneous datatypes won’t be caught until you run the code, but still I find it more elegant than accessing the SqlDataReader’s columns with column-name strings as indexers. And in case you later on decide to make the IEnumerable use an actual class, it will not break the code. This can be done as shown here, where you have a class of T that maps to your database-request:

private static IEnumerable<T> GetSqlData<T>(string connectionstring, string sql) 
{
    var properties = typeof (T).GetProperties();

    using (var conn = new SqlConnection(connectionstring))
    {
        using (var comm = new SqlCommand(sql, conn))
        {
            conn.Open();
            using (var reader = comm.ExecuteReader())
            {
                while (reader.Read())
                {
                    // http://blog.benhall.me.uk/2006/08/creating-objects-dynamically-with-c-20.html
                    var element = Activator.CreateInstance<T>();

                    foreach (var f in properties)
                    {
                        var o = reader[f.Name];
                        if (o.GetType() != typeof(DBNull)) f.SetValue(element, o, null);
                    }
                    yield return element;
                }
            }
            conn.Close();
        }
    }
}

 

Actually the little Activator.CreateInstance<T> trick can nowadays also be coded with a new T() if you add a type-constraint on the method (where T : new()), but internally it’s still Activator.CreateInstance<T> so this version is basically just sugar-coating:

private static IEnumerable<T> GetSqlData<T>(string connectionstring, string sql) where T : new()
{
    var properties = typeof (T).GetProperties();

    using (var conn = new SqlConnection(connectionstring))
    {
        using (var comm = new SqlCommand(sql, conn))
        {
            conn.Open();
            using (var reader = comm.ExecuteReader())
            {
                while (reader.Read())
                {
                    var element = new T();

                    foreach (var f in properties)
                    {
                        var o = reader[f.Name];
                        if (o.GetType() != typeof(DBNull)) f.SetValue(element, o, null);
                    }
                    yield return element;
                }
            }
            conn.Close();
        }
    }
}

A RemoveAll Extension for the Collection Class

For some reason the Collection<T> class doesn’t contain a number of methods found on the List<T> class. The fabulous extensibility in .Net makes it easy to overcome however. Here’s my suggestion for an extension method that will do the trick:

public static void RemoveAll<T>(this Collection<T> collection, Func<T,bool> condition)
{
    collection.Where<T>(condition).ToList().ForEach(e => collection.Remove(e));
}

The point here – as opposed to some other solutions I’ve seen – is to only create a temporary list of the objects to remove, assuming that there will be fewer of these than of the number of elements remaining, thus minimizing the overhead.

And a sample invocation:

var collection = new Collection<string>();

collection.Add("ABC");
collection.Add("XYZ");
collection.Add("DEF");

collection.RemoveAll(s => s.StartsWith("X"));

Time to wave goodbye to the C# “for” statement?

Lately I’ve got a bit tired of the kinda old fashioned syntax of the for-statement, especially the triple declaration of the variable to count on. As the Enumerable.Range is nice and Linq’y I’ve taken to using that, and as far as I’ve (unscientifically) measured, there’s only a small perf-hit if you approach more than about 100000 iterations.

First the old fashioned way:

for (var i = 0; i < 10; i++) Console.WriteLine(i);

Then the Enumerable way:

foreach (var i in Enumerable.Range(0, 10)) Console.WriteLine(i);

And finally, with an extension method thrown in:

public static IEnumerable<int> Range(this int i, int count)
{
    return Enumerable.Range(i, count);
}

foreach (var i in 0.Range(10)) Console.WriteLine(i);

Not big science, but in my opinion nice and clean and – most importantly – a succinct expression of programmer intent

Formatting A String With Named Parameters

I usually try to blog about things that I haven’t really been able to find anywhere else. I realize that this may not quite be the case here – Phil Haack has an inspiring article here that sums up various methods of extending the usual positional formatting of String.Format.

However I wanted to be able to:

  • have the same formatting capabilities as String.Format, like{0:00}
  • have extensive validation between the string “template” and the parameters passed
  • not use Databinder.Eval, which seems a bit (too) exotic for my taste
  •  

    The use-cases – insert values from Dictionary<string,object> or from class looks like this:

    const string s = "Hello {name}, the value is {value:00} at {date:yyyy-MM-dd} {date:HHmmss}";
    
    var d = new Dictionary<string, object>();
    d.Add("date", DateTime.Now);
    d.Add("value", 5);
    d.Add("name", "MySelf");
    
    Console.WriteLine(s.FormatByName(d));
    
    Console.WriteLine(s.FormatByName(new {date=DateTime.Now, value=5, name="MySelf"}));

    My implementation of this follows here, and if you’d like to play with it you can download the full sample code here

    Please return any modifications or additions you come up with :).

    I’ll just skip the extension methods here and go straight into the meat of the formatting which is handled by a method with this signature:

    private static string KeyValueReplacer(string template, Dictionary<string, object> parametercollection)

    First the parameters need to be extracted, which is done by the black art of a RegEx (the origins of which I’m afraid I’ve forgotten)

    Regex m_regexmatch = new Regex(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+",
        RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
    
    var matches = m_regexmatch.Matches(template).OfType<Match>();
    
    // Get the parameters { to } and index of any suffixed : formatting code
    var paramlist1 = matches.Select(s => new { Parameter = s.Value, FormatIndex = s.Value.IndexOf(':') });
    
    // Extract the key (parameter name) and formatting code from template
    var paramlist2 =
        paramlist1.Select(s =>
                          new
                          {
                              Key = s.Parameter.Substring(1, s.FormatIndex < 1 ? s.Parameter.Length - 2 : s.FormatIndex - 1),
                              Format = s.FormatIndex < 1 ? "" : s.Parameter.Substring(s.FormatIndex, s.Parameter.Length - s.FormatIndex - 1),
                              s.Parameter,
                          });

    As mentioned above I wanted extensive checking that the parameters correlate:

    // Perform existence checks from both sides
    var paramlist2unique = paramlist2.Select(s => s.Key).Distinct();
    foreach (var key in parametercollection.Keys)
        if (!paramlist2unique.Contains(key))
            throw new ArgumentException("Parameter [" + key + "] not found in template");
    
    foreach (var key in paramlist2unique)
        if (!parametercollection.ContainsKey(key))
            throw new ArgumentException("Template variable {" + key + "} not found in parameter collection");

    Now it’s time to join the template together with the values, and finally perform the actual replacing in the template string:

    // Join the template parameters and the values from parametercollection
    var paramlist3 =
        from p in paramlist2
        from v in parametercollection
        where p.Key == v.Key
        select new
        {
            p.Parameter,
            ValueString = String.Format("{0" + p.Format + "}", v.Value)
        };
    
    // Replace the values into the template
    var sb = new StringBuilder(template);
    foreach (var p in paramlist3)
        sb.Replace(p.Parameter, p.ValueString);
    
    return sb.ToString();

    Well, that’s about it – except that I also wanted the ability to substitute with the properties of a (possibly anonymous) class.

    This is done by first creating a dictionary of key/values from the class before calling the method above:

    private static Dictionary<string, object> PropertiesToDictionary(object o)
    {
        var t = o.GetType();
    
        if (!t.IsClass)
            throw new ArgumentException("Can only resolve properties in classes.");
    
        var p = t.GetProperties();
        var propcollection = p.ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => propertyInfo.GetValue(o, null));
        return propcollection;
    }

    Enjoy!

    Assert that a particular exception has occured (Assert.Throws in MSTest).

    Built into the MS Unit Test framework is the option of putting an attribute on your testmethod:

    [TestMethod]
    [ExpectedException(typeof(FormatException), "Description.")]

    If, however, you would like to test for more than one exeption type you have to create a test method for each. It is, of course, quite a different matter of principle whether you should ever do that 🙂

    But a solution to this problem could be a method like this, which I’ve synthesized from a number of StackOverflow posts (like this):

    // Assert (by true/false) that an exception of the spcified type has been thrown
    public bool AssertThrows(Action action) where T : Exception
    {
        try{ action(); }
        catch(Exception exception)
        {
            if (exception.GetType() == typeof(T)) return true;
        }
        return false;
    }

    Which can then be called simply like:

    Assert.IsTrue(AssertThrows<FormatException>(delegate{ new MyMethod(MyParameter); }));

    Other approaches than using the genric of T could be implemented (as a parameter of Type or even array), but I really think that the generic offers the most elegant solution. In this case I prefer using the delegate keyword instead of the ()=> lambda syntax – not least because I get a nice highlighted documentation (blue being my favorite color) of what is going on.

    UPDATE I’ve just become aware that this functionality is actually available in nUnit as Assert.Throws, so I’ve updated my article to reflect this.

    Start process with impersonation – roll your own RunAs in C#

    Quite a few of our servers are now in a different domain than the one I’m in – and especially for using SQL Server Management Studio that means that I have to use the RunAs command quite often (or use the shift + right-click RunAs option). Being a bare-bones command-line tool RunAs is not as user-friendly as one might wish, so I decided to try and make my own today, and here is the heart of the matter:

    using System.Diagnostics;
    using System.IO;
    using System.Security;

    var file = @”C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe”;

    // http://stackoverflow.com/questions/4624113/how-to-process-start-with-impersonated-domain-user

    var sspw = new SecureString();

    foreach (var c in “Mypassword”) sspw.AppendChar(c);

    var proc = new Process();

    proc.StartInfo.UseShellExecute = false;

    proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(file);

    proc.StartInfo.FileName = Path.GetFileName(file);          
    proc.StartInfo.Arguments = “”;

    proc.StartInfo.Domain = “MyDomainName”;

    proc.StartInfo.UserName = “MyUserName”;

    proc.StartInfo.Password = sspw;

    // http://stackoverflow.com/questions/4422084/impersonating-in-net-c-opening-a-file-via-process-start

    proc.StartInfo.LoadUserProfile = true;

    proc.Start();

    What was especially tricky was that StartInfo must absolutely have a valid path, and that – in order for Ssms.exe to find its modules – StartInfo must also be told to use the UserProfile of the impersonated user.

    I find it a little odd that SecureString doesn’t have a constructor or method for taking a string, but maybe I’m overlooking some finer security detail here.

    The whole thing will have to go inside a GUI with some sort of secure persistance of user info, but that should be the easy part 🙂