Archive for March, 2010

Stupid C# Tricks: Ghetto Eval

Alternate Title: An Incredibly Simple Introduction to C# Metaprogramming

The eval method is a staple of scripting languages.  It takes a string and executes it as code.  This is useful when, e.g., you need to modify the value of one of several text fields on a page.  The name of the text field can be dynamically passed into the eval argument.

So C#, being a compiled language, doesn’t have an eval method. What it does have, however, is great support for programmatic compilation of code. This can be used to hack together something that’s kind of like an eval. Take, for instance, the following method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
        public static void FauxEval(string codeToEval)
        {
            //Create compiler objects
            CSharpCodeProvider Compiler = new CSharpCodeProvider();
            CompilerParameters Params = new CompilerParameters();
            CompilerResults Results;
 
            Params.GenerateExecutable = true;
            Params.OutputAssembly = "eval.exe";
 
            //We could check this Results object, but this is naught but an example
            Results = Compiler.CompileAssemblyFromSource(Params, codeToEval);
 
            //Execute the eval-ed code
            Process evalledExecutable = new Process();
            evalledExecutable.StartInfo.FileName = "eval.exe";
            evalledExecutable.Start();
            evalledExecutable.WaitForExit();
        }

This method takes the C# source of an executable as its argument. It compiles the source and executes it. Now this is kind of like an eval. It’s more structured than that found in a scripting language, since it can only eval code that compiles into a valid C# program. The heavy lifting is done by the CSharpCodeProvider class, which handles the compilation of the source. This class also contains a lot of handy methods to generate code from various CodeDOM objects, making it your one-stop shop for C# metaprogramming. (N.B. There’s a comparable class for Visual Basic called VBCodeProvider. This is exceptionally handy if, for whatever reason, you want to use C# to emit Visual Basic code.)

So the above FauxEval method can be used simply by assembling a string that will compile into an executable. The strength of eval-like methods, of course, is that this string can be constructed dynamically at run time. As a completely trivial example, here’s a program that uses the above eval to generate a Hello World-like program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
        static void Main(string[] args)
        {
            string programMessage = "Hello, world!";
            if (args.Length > 0)
            {
                programMessage = args[0];
            }
            string programCode = "";
            programCode += "using System;";
            programCode += "using System.Text;";
            programCode += "namespace GeneratedCode";
            programCode += "{";
            programCode += "class GeneratedProgram";
            programCode += "{";
            programCode += "static void Main(string[] args)";
            programCode += "{";
            programCode += "Console.WriteLine(\"" + programMessage + "\");";
            programCode += "Console.WriteLine(\"Press any key to continue...\");";
            programCode += "Console.ReadKey(true);";
            programCode += "}";
            programCode += "}";
            programCode += "}";
 
            FauxEval(programCode);
        }

The generated program will simply print the first command line argument to the console. If no argument is provided, the executable is built to be a default “Hello, World”.

The results:


(Click to embiggen)

So that’s a super-simple C# eval. This provides the ability to execute code that’s been dynamically created at run time, provided the code can be compiled into an executable. There’s a lot of room to expand on the method and make it more flexible and general, but there really is only so much you can do with this strategy of code evaluation, since the code always has to be able to be compiled into an assembly. Still, it’s a damn sight better than nothing.

Update 2010.3.30: I removed some random debugging code from the Eval method above. It was a classic case of YAGNI. I thought I might want to dump eval string contents to a file. I ended up not needing to, but then forgot to pull the debugging code.

Stupid C# Tricks – Sealed Classes

So as platform-driven languages go, C# isn’t a bad one.  We’ve had some good times together, and I’m rather fond of the bloated, lumbering behemoth.  But there are a few things about it which drive me absolutely insane.  One of these is sealed classes.

Now the conventional wisdom is that sealing classes improves performance and security.  First of all, if a sealed class increases performance (which it doesn’t in all cases), then those gains are absolutely negligible.  Relying on sealed classes to get your app to meet benchmark requirements is a little like entering a horse in the Kentucky Derby, and then relying on giving him a good shave to make him win.  Even if the minor weight loss DOES make him a bit faster, it’s not going to be enough to win.  Plus now you have an angry, naked horse on your hands.

Okay, so that analogy went kind of a weird place.  But I hope my point is clear: sealed classes don’t provide good enough performance boosts to really make a difference.  If the kind of operation-shaving that sealed classes sometimes result in is really your last resort for optimization, then you may have a bigger problem on your hands than you think.

As for the security argument, well, I just don’t buy it.  It seems that people think that a lack of inheritance is somehow a security feature, but I just don’t see how.  If not allowing your C# code to be overridden or reused by other people is really key to your “security” methodology, then you better hope that none of your customers are smart enough to use Reflector.  I mean, this security argument is really so stupid that I can’t help but think that I must be constructing a straw man.  Alas, a quick Google search seems to indicate that sealing classes is widely understood to be “good security.”

Of course, none of this would be that bad if it was just a smattering of C# developers who went around sealing their classes.  The problem is that a lot of very useful classes in the platform itself are sealed.  I recently found another such class when I tried to override the Console class.  Apparently the C# team at Microsoft has decided that no one will ever need, want, or get to override Console.  Which would be fine, except that I both needed and wanted to override Console.

Why, you ask?  Well, to be fair, it was for a gonzo code joke that probably would have amused only me.  But the fact of the matter is, I won’t get a chance to find out if it’s as funny as I thought it would be, because .NET won’t let me override the Console class.

So that’s the rant.  Sealing classes is both useless and annoying, doubly so when it’s done to basic platform classes.  What’s more, I’ve not seen a single good argument in defense of the practice.

Though just watch, a few weeks from now, we’ll see someone flogging sealed classes on the grounds that it protects the world from dubiously funny jokes by bored twenty-somethings.

Truth

Click for bigger. Source unknown; if anyone knows, please leave a comment.

Dear SOA Coders

Please version your services. Seriously, I cannot express the irrational irritation I feel whenever I encounter an unversioned web service. And while I would like say that it makes me go all Bruce Banner and go on campaigns of violence against service authors, really I just say mean things about them and question their intelligence, heritage, grooming habits. Truly, you wouldn’t like me when I’m angry; I can be pretty damned annoying.

Where was I? Right, web service versioning. Probably the best way to handle it is to add another web method to all your services that returns version of the executing assembly. In C# and other .NET languages, this is pretty simple:

1
2
3
4
5
6
7
8
9
10
11
12
[WebMethod]
public string GetVersion()
{
    Version versionObj = 
        System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
 
    string versionString = 
        versionObj.Major + "." + versionObj.Minor + "." + 
        versionObj.Build + "." + versionObj.Revision;
 
    return versionString;
}

Another option for web service versioning is simply to include the version as an output parameter on every method. In most cases this is overkill, but in instances where the web service changes often and/or without notice, it might not be such a bad idea.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        public static string Message { get; set; }
        [WebMethod]
        public string GetMessage(out string currentServiceVersion)
        {
            currentServiceVersion = GetVersion();
            return Message;
        }
 
        [WebMethod]
        public void SetMessage(string newMessage, out string currentServiceVersion)
        {
            currentServiceVersion = GetVersion();
            Message = newMessage;
            return;
        }

Of course this method has the disadvantage that, even though you probably only need to check the version rarely (e.g. when issues arise or when deploying new versions of consumer apps), the web service does the work of retrieving the version every time. It also incurs a slight network traffic cost, since you’re passing the version back with every response message.

I would have thought that attaching some kind of client-accessible version to your web services would be common sense or, at the very least, common best practice. But we’ve been fighting this battle in the context of my day job, trying to get a client to version the services we rely on for integration. This after several cases in which QA saw issues in testing which, after investigation, turned out to be due to web services that hadn’t been updated as promised or, worse yet, had been “updated” without our knowledge.

So yes: version your services. It’s not that hard, and can save everyone a lot of angst. Especially those who would otherwise have to listen to me bitch.

Throw-Away Apps FTW!

So one of the greatest things about being a hacker is that one has a ready answer to idle thoughts of “I wish my computer did X…” You simply code up a way for it to do what you want. It’s especially nice when what you want it to do is actually rather simple, but just something that no one’s thought to implement yet. (This is all, of course, assuming that Google failed to turn up a good existing solution. Reinventing the wheel makes baby Edsger Dijkstra cry.)

Case in point: on a couple of recent occasions, I’ve thought it’d be nice if I had a way to quickly dump a timestamp to my windows clipboard so that I could drop it into documents. Well, after ten minutes of hacking and a little bit of thrashing at OS integration, I have exactly that.

Basically I wrote a lightweight C# console app that optionally takes a DateTime format string as an argument and does nothing but push a current timestamp to the clipboard. (It applies the format string if provided, otherwise it just uses default formatting.) I put the executable in an easy-to-remember path (C:\TimeToClipboard\). I then added keys to some of the shell registry entries to add the application (called with my preferred timestamp format) to filesystem context menus.

The application code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Windows.Forms;
 
namespace TimeToClipboard
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Clipboard.SetText(DateTime.Now.ToString(args[0]));
            }
            else
            {
                Clipboard.SetText(DateTime.Now.ToString());
            }
        }
    }
}

The registry entries:

Keys: HKey_Classes_Root/*/shell/Get Timestamp/command
HKey_Classes_Root/Drive/shell/Get Timestamp/command
HKey_Classes_Root/Folder/shell/Get Timestamp/command

Value: c:\TimeToClipboard\TimeToClipboard.exe “yyyy.M.d H:mm:ss”

This worked pretty well, but I couldn’t figure out a way to add the Get Timestamp context menu item to the desktop context menu. I was hoping that * really meant “add to all context menus”, but it in Microsoft world, it apparently means “add it to an unspecified subset of context menus.” Not very helpful.

So my next idea for easy access was a keyboard shortcut. I added a shortcut to the TimeToClipboard application to my desktop and bound it to the Ctrl+Alt+T keyboard combination. This works well, and works no matter what application has keyboard focus. So no matter what I’m doing, I’m never more than three keystrokes away from having a timestamp.

World changing? Hardly. But convenient. Plus the whole thing took me less than an hour to bash together and get setup, and most of that time was googling around for the names of registry keys.

CSS Hackery

Getting some CSS help from my friend Chris. This is just a test. Please ignore.

1
2
3
4
5
6
7
8
if(thisWorks)
{
    return "I'm impressed";
}
else
{
    return "OH SHIT GUYS, DIDN'T WORK!";
}

(Also, sorry for the weirdness of the code samples the past few days. I think we have the problems ironed out now. Just beating a new WP plugin into submission. Nothing to see here.)

Stupid C# Tricks – Closures

So in my current quest to poke around in some of the more esoteric corners of C#, I’ve gotten interested in C#’s implementation of closures. Like most .NET languages, C# is trying really hard to be everything to everyone, and so as of language version 3.0 it has native support for closures. Now, many of you functional folks in the audience are probably either saying “woo-hoo closures! Yeah! ROCK!” or possibly “wait, people use C#? I thought everyone was on Ruby these days.”

The .NET folks are probably searching in vain for the MSDN article on this mythical “closure” thing.

So a closure (for those unfamiliar) is a chunk of code that can be passed around like a first-class object and which can reference variables in the namespace in which it was created. It’s essentially a method that’s treated like and object and can reference variables it could see at the time of its creation. These things are all the rage in Lisp- and Smalltalk-like languages. They’re one of the things that makes Lisp so powerful and they cause most Rubyists to get all wet in the trousers.

So what can closures do for you? Go go gadget example!

In this example, we’ll be creating a light-weight console app which determines the length of the Collatz Chain resulting from a given starting point. The Collatz Conjecture (unproven) states that the following function, if iterated, will eventually converge to 1, regardless of starting point:

f(x) = x/2 (X is even)
f(x) = 3x+1 (X is odd)

A Collatz Chain, then, is the sequence of results created by iteratively applying the above function starting from a particular number.

Now a recursive solution to this is pretty easy to bash out. There’s not much to the problem as stated here. But it serves as a pretty handy way to demonstrate closures. (The real mindfuck comes when you start examining the problem’s properties and the various interesting attempts at proving the conjecture. Also, the function makes for a really kickass graph and fractal.)

So, in the code below, I’m going to encapsulate the Collatz function in code block and pass it in to a wrapper class which will do that actual execution of the code.  First, the wrapper:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CollatzByClosures
{
    public static class CollatzWrapper
    {
        public static Func method;
        public static int Execute()
        {
            return method();
        }
    }
}

As you can see, there’s not a whole lot to this. The static CollatzWrapper class has a Function object that returns an integer, and it’s got a public Execute method that just returns the result of that method’s execution. Note that the method takes no arguments and that the wrapper is both static and contains no other member variables besides the function. “There’s nothing up my sleeve and nothing under my hat”, said the magician.

Next, the program that uses this wrapper:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CollatzByClosures
{
    class Program
    {
        private static int CollatzArgument = 0;
        private static int CollatzLength = 0;
 
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                CollatzArgument = int.Parse(args[0]);
            }
            else
            {
                CollatzArgument = 42;
            }
 
            CollatzWrapper.method = (
                () => {
                    if(CollatzArgument%2 == 0)
                    {
                        CollatzLength++;
                        return CollatzArgument/2;
                    }
                    else
                    {
                        CollatzLength++;
                        return (CollatzArgument*3+1);
                    }
                });
 
            while (CollatzArgument > 1)
                CollatzArgument = CollatzWrapper.Execute();
 
            if (args.Length > 0)
            {
                Console.WriteLine(args[0] + " results in a Collatz chain of " + CollatzLength.ToString());
            }
            else
            {
                Console.WriteLine("No argument detected. Using 42 which results in a Collatz chain of length " + CollatzLength.ToString());
            }
        }
    }
}

So the above code’s fairly simple. The Program class has a pair of private static variables used to track the length of the chain and the current number that we’re evaluating using the Collatz Function. If the user passes in an argument, we’ll calculate the chain from that. Otherwise, we’ll calculate the chain from 42. Next, we assign a block encapsulating the Collatz Function to the CollatzWrapper’s “method” variable. Notice that the block that I’m constructing here references private members of the Program class, and I’m assigning this block to a variable in the CollatzWrapper class. The intuition of most OOP folks will tell them that these private members shouldn’t be accessible from another class.

Thanks to the magic of closures, however, the block that I assigned to the CollatzWrapper’s “method” variable can still reference anything to which it had access when that block was created. This means that it can still access those private members, even from another class.

The results of running the above app with no arguments:

No argument detected. Using 42 which results in a Collatz chain of length 8    
Press any key to continue . . .

Results when I pass in argument 17298 (randomly generated using the “ask a friend to pick a large number” method):

17298 results in a Collatz chain of 53

So the closure passed into the wrapper uses private variables from the class in which it was created (rather than the one in which it was executed) to track the length of the Collatz chain and to store the result of its computations.

One other nice thing about closures (not really demonstrated in this code), is that since closures are first-class objects, they can be passed around in exactly the same way as any other object. Moreover, they can be changed, assigned, and moved all through a system, all while maintaining access to the variables that were available to them on creation. These are all properties which make closures full of awesome.

Now, is there anything you can do with closures that you can’t do some other way in C#? Well, no. But I imagine there are a lot of things that closures make easier, more intuitive, and quicker to implement. Besides, even if one never uses closures, it’s nice to be able to say that we know what our tools can do.

Return top

Magic Blue Smoke

House Rules:

1.) Carry out your own dead.
2.) No opium smoking in the elevators.
3.) In Competitions, during gunfire or while bombs are falling, players may take cover without penalty for ceasing play.
4.) A player whose stroke is affected by the simultaneous explosion of a bomb may play another ball from the same place.
4a.) Penalty one stroke.
5.) Pilsner should be in Roman type, and begin with a capital.
6.) Keep Calm and Kill It with Fire.
7.) Spammers will be fed to the Crabipede.