Nov 032013

Almost three years ago I released css2xpath#, a port of Andrea Giammarchi’s project by the same name. Today, I’m excited to announce a new project, css2xpath Reloaded, which will supplant my previous project. css2xpath Reloaded does the same thing that css2xpath# did (convert CSS selectors to XPath selectors), but is instead based off of Ian Bicking’s excellent Python app (also somewhat confusingly named css2xpath).

Whereas css2xpath# (and Andrea’s original project) relied on regular expressions to perform the conversion, css2xpath Reloaded recreates Ian’s CSS selector parser.

Although more complicated, a benefit of using a parser is that your CSS selectors can be validated during conversion. It’s also a little bit easier to extend the code. And most importantly (for me at least) it was a lot of fun to write.

I’d consider the code to be beta quality at the moment; it’s lacking in documentation and rigorous testing. However, if you’re interested in testing it out, proceed to BitBucket.

css2xpath Reloaded on BitBucket

 Posted by at 11:50 pm
Dec 102012

I’ve posted BaseMemberPromotingProxy.dll to the downloads section of the BaseMemberPromotingProxy BitBucket. Now you don’t have to compile the source yourself to use it – just grab the DLL and you’re all set!

Also, to anyone that has been compiling (or modifying) the source, note that I made a few commits that correct a stupid spelling mistake. In some places, BaseMemberPromotingProxy was incorrectly spelled BaseMemberyPromotingProxy.

Enjoy, and remember:

There is no “y” in “member” – Me


 Posted by at 9:02 am
Nov 042012

If you’re trying to set up caching with Code Contracts (and SQL Server CE) but getting errors, then this is the post for you.

On a fresh install of Code Contracts, enabling caching might spawn this error:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.SqlServerCe, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

This error is telling us that we need SQL Server CE (Compact edition) version 3.5.1, but it lies! What we really need is version 3.5.2.

To fix this error, download and install this (yes, on a 64-bit machine you do need to install both the 32 and 64-bit versions). It’s going to ask you where to extract the files, not where you want to install SQL Server itself; I just chose the desktop.

If you are getting errors such as:

... Schema specified is not valid. Errors:
... error 0175: The specified store provider cannot be found in the configuration, or is not valid

this means you installed the wrong version of SQL Server CE (such as version 3.5.1). To fix this, first uninstall any 3.5.x versions of SQL Server CE, and then download and install what I linked to above.

 Posted by at 8:28 pm
Oct 092012


BaseMemberPromotingProxy is a (terribly named) class meant to be used as the target for the DebuggerTypeProxy attribute. The code is based off of Jared Parsons’ FlattenHierarchyProxy. Like the original, BaseMemberPromotingProxy (which will be referred to as BMPP throughout the rest of this post) is designed to improve the debugger displays of classes that inherit from other classes.

What the what?

The best way to demonstrate BMPP is by giving an example. Consider these classes:

public class Dessert {
    public int Calories { get; set; }
    public Dessert(int calories) {
        Calories = calories;

public class Pastry : Dessert {
    public bool Flaky { get; set; }
    public Pastry(bool flaky, int calories) : base(calories) {
        Flaky = flaky;

public class Cake : Pastry {
    private String _baker;
    public Cake(string baker, int calories) : base(false, calories) {
        _baker = baker;

Let’s create an instance of Cake and look at the debugger display that Visual Studio provides by default.

var cake = new Cake("Jerry's bakery", 250);

We set a breakpoint after the instance of Cake is created, and Visual Studio pauses execution. Hovering over cake, we see:

So where are the members of Pastry and Dessert? We need to drilldown further to find them. It takes another click to see the Flaky property of Pastry, and one more additional click to see Calories of Dessert (as pictured below).

This is very inconvenient; even more so when actual complicated class structures are involved. Enter Jared Parsons’ FlattenHierarchyProxy.


Let’s see what FlattenHierarchyProxy (off of which BMPP is based) can do for us. We apply it to Cake with a DebuggerTypeProxy attribute.

public class Cake : Pastry {

Now, when we mouse over the cake variable, we get:

Jared’s type proxy greatly improves the debugger display by displaying all members (from both parent and subclasses) “side-by-side”. I’ve decided to call this the “promotion” of the members of subclasses (hence the name of my class). So what does BMPP provide?



I was really happy with FlattenHierarchyProxy, but felt the need to make a few improvements. BMPP contains the following improvements and new features:


“Opt-in” mode for properties and fields

Sometimes you don’t want to promote every member of the subclass(es) that your class derives from. Maybe a subclass contains a property or field that isn’t relevant to your parent class, so you’d rather not see it in the debugger display. Going back to our Cake example, let’s say that we don’t care about the Flaky property. We could apply a DebuggerBrowsable attribute to hide it (see below), but then we wouldn’t see Flaky even if we were debugging a plain instance of Pastry.
The solution is to use one of BMPP’s spiffy new attributes:

  • PromoteProperty(/* name of property */): Promote the specified property
  • PromoteField(/* name of field */): Promote the specified field

To hide Flaky while debugging instances of cake, we opt-in just Calories by applying a PromoteProperty attribute:

public class Cake : Pastry {

Now we get:

The way this works is that the use of a PromoteProperty attribute switches BMPP to “opt-in” mode for properties. Normally, BMPP grabs whatever properties it can from the parent class and all subclasses. Applying a PromoteProperty attribute turns off this behavior: only properties that are opted-in with PromoteProperty attributes are promoted. This behavior is the same for PromoteField properties. However, PromoteProperty does not switch on opt-in mode for fields, or vice-versa.
Also, note that we didn’t have to explicitly opt-in the _baker field since it was declared in the parent class, not a subclass. Members of the parent class are always included. This behavior exists with properties as well.
Note: I have considered implementing an opt-out mode in addition to opt-in mode. Please comment on my blog or submit an issue on BitBucket if you are interested in this for the next version.


Alphabetical ordering of members

This is something that Visual Studio does automatically, however since we are constructing a custom debugger display, we need to perform the sort ourselves. Replacing the last line of BuildMemberList() with the following does the trick:

return list.OrderBy(m => m.Name).ToList();

Note that the collective list of fields + members is sorted as one list. If you want different behavior (for example, you might want a sorted list of fields to appear before a sorted list of properties), let me know and I can add the functionality.


Honoring of DebuggerBrowsable attributes

Let’s rewrite the declaration of the _baker field from the Cake class as:

private String _baker;

FlattenHierarchyProxy would still display the _baker field, even though we’ve chosen to hide it using the DebuggerBrowsable attribute. The fix that BMPP makes is to introduce this internal helper function:

private static bool IsMemberBrowsable(MemberInfo memberInfo) {
    return memberInfo.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true)
           .Select(p => (DebuggerBrowsableAttribute)p)
           .All(p => p.State != DebuggerBrowsableState.Never);

Now, when BMPP builds the property and field lists, it uses the IsMemberBrowsable function as a filter.


Get it

The class is hosted on BitBucket. Documentation will be up on BitBucket soon – for now, use this page as a reference.

Performance information

I have not done extensive testing on the performance of BMPP. It is noticeably slower than FlattenHierarchyProxy, however. The performance hit comes from the fact that reading attributes is a fairly expensive reflection task, relative to everything else that the proxy does. If you have any ideas on how to improve performance, please let me know.

 Posted by at 5:45 pm
Sep 162012

I’ve been working on a rather large project for the past few months (a library), and I’ve had the need to customize how the debugger displays my classes during a debug session. I found two very helpful articles from Jared Par that I wanted to share.

Article #1: FlattenHierarchyProxy

A problem I ran into very recently is how to simplify the creation of DebuggerTypeProxy proxy classes for objects that have several levels of inheritance (I describe the problem on StackOverflow). Briefly, when debugging an object that has one or more base classes, the base and parent properties do not show side-by-side. Base class properties and fields are under a separate expandable list. This means that you need to expand through two lists to view a property that came from the base class. More levels of clicking are required when further levels of inheritance are used.

Solution: In his article, Flattening class hierarchies when debugging C#, Jared creates a proxy class called FlattenHierarchyProxy that accomplishes what I want: parent and base class properties and members are corralled side-by-side in the debugger display. It’s a really useful class that I suggest you check out.

Side note: I’ve made several modifications and improvements on the class which I plan to publish as a new open source project. Details to follow.

Article #2: DebuggerDisplay attribute best practices

This article provided some helpful dos and don’ts on the usage of the DebuggeDisplay attribute. It’s a quick read, but really useful: DebuggerDisplay attribute best practices

 Posted by at 9:38 pm
Sep 042012


BitBucket repository is live:
In the final post in this five part series, I’ll develop a client side application in Python to communicate with our drumset which was modified in part 4.

The final result will be a simple command line interface (for now) that looks like this:



Before even choosing the language I wanted to use, I decided to list a few requirements for the client-side software.

  1. The software will automatically detect the drumset; the user will not have to manually choose a serial port.
  2. The software will support playing multiple drumpad sounds at once (like a real drumset). This will require audio mixing.
  3. The software must be cross-platform and easy to install.


My development process

I ended up developing this application three times: twice in C# and once in Python. There was also almost a C++ version. In this section, I’ll explain the initial prototype versions and why I decided upon Python in the end. To do this, I’ll go down the list of the requirements.

Requirement 1 is easy: if you remember, back in part 3 we added a feature to the embedded software that supports responding to “pings”:

// The client might want to know what we are, so let
// them ping us
if (Serial.available()){
  while (Serial.available()){;

  Serial.println("{ "msgType": "ping" }");

I didn’t want users to have to figure out which serial port to use. It should Just Work™. This is a very simple feature to implement, and because of this, requirement 1 didn’t actually steer me towards any one language.
Continue reading »

 Posted by at 7:00 am
May 292012

I was looking through my referrer stats the other day and found a neat use of my port of css2xpath

The author uses css2xpath to aid in inlining CSS stylesheets. Here is an excerpt of the project (I trimmed the first two paragraphs):

This week I worked on adding confirmation emails to our quiz system and was introduced to the maddeningly fickle world of HTML emails…

I had hoped that the detailed confirmation emails could simply re-use the HTML that our system already generated, but after a few test emails it became apparent that most of that HTML relied heavily on external stylesheets which no email client would render. With mounting dread I foresaw the likelihood that I would have to write another rendering engine for emails rather than re-using the one we already had…

Willing to do almost anything to avoid this code duplication I wondered if I could take the HTML rendered by the existing quiz engine and just tweak it to get it work in our emails. So how hard would it be to write some code that took these external stylesheets and applied them as inline rules (which is supported to some degree by most email clients)? Not hard at all as it turns out.

Read about the full project here:

 Posted by at 5:32 pm
Nov 252011

Recently, I needed to locate a device on my network using ARP (Address Resolution Protocol). I could have written code that directly uses the protocol to discover the device, by essentially probing a range of addresses on my network until it found the right one. But, that proved to be too much work. So, I decided to use Window’s arp command line tool.

To demonstrate the arp command, open a command prompt, type the following, and then press enter:

arp -a

This is a simple way to display a list of devices and their associated MAC addresses. The goal of my C# program would be to invoke this command and parse the output.

To begin, I wrote this simple method:

public static StreamReader ExecuteCommandLine(String file, String arguments = "") {
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.UseShellExecute = false;
    startInfo.RedirectStandardOutput = true;
    startInfo.FileName = file;
    startInfo.Arguments = arguments;

    Process process = Process.Start(startInfo);

    return process.StandardOutput;

Given the name of a program to execute, and a list of arguments to pass to that program, the above function returns the StreamReader associated with the output of the program. The next step is to parse the output and find the device you want:

var arpStream = Utility.ExecuteCommandLine(“arp”, “-a”);

// Consume first three lines
for (int i = 0; i < 3; i++) { arpStream.ReadLine(); } // Read entries while (!arpStream.EndOfStream) { var line = arpStream.ReadLine().Trim(); while (line.Contains(" ")) { line = line.Replace(" ", " "); } var parts = line.Split(' '); // Match device's MAC address if (parts[1].Replace("-", "").ToUpper().Trim() == "UPPERCASE_MAC_ADDRESS_TO_FIND_GOES_HERE") { // Your device is on the network // Access its IP address with: parts[0].Trim() } } [/csharp] The first line makes use of the function I defined above to execute the arp command and get its standard output stream. If you've tried the arp command out for yourself, you will notice that the first three lines are garbage. The next three lines of code account for this by advancing past the garbage lines. Finally, I iterate over each entry in the table and try to match the given MAC address. If the MAC address is found, you can fetch the IP address of the associated device. Please note that this code has no error checking. I'm not sure, for example, what would happen if the arp tool lists no devices, or if the user doesn't have administrative privileges.

 Posted by at 4:27 pm
Jan 272011

After browsing around a little bit, I found an interesting solution if you need to hide the tab headers on a tab control. I found it here, posted on the MSDN social forums by “nobugz” (Hans Passant). Here is his solution:

class YourTabControl : TabControl{
    protected override void WndProc(ref Message m){
        // Hide tabs by trapping the TCM_ADJUSTRECT message
        if (m.Msg == 0x1328 && !DesignMode)
            m.Result = (IntPtr)1;
            base.WndProc(ref m);

Basically, you define your own class that extends TabControl. The custom class overrides the WndProc method, which is responsible for processing Windows messages sent to windows and controls. The new version filters out the message which is responsible for drawing the tab headers. Very clever.

To use it, you can make a normal TabControl using the designer. Then, in the Designer code, change the following line (in the InitializeComponent method):

this.tabControl1 =  new System.Windows.Forms.TabControl();


this.tabControl1 =  new YourTabControl();

Finally, near the bottom of the Designer code should be a line that looks like this:

private System.Windows.Forms.TabControl tabControl1;

Change it to:

private YourTabControl tabControl1;

Another clever thing about this is that, as you will notice, tab headers are still visible while in Design mode.

 Posted by at 7:07 pm
Jan 112011

I’ve created a quick, simple tool that converts CSS file references (like url(images/someimage.png)) to inline image data (like url('data:....')). Written in C#, and available as an open source download (see below), the tool is a point-and-click alternative to manually making the data URIs.

A screenshot of the CSS Image Embedder


To use the tool, follow these three steps:

  1. Open the CSS file you want to work with.
  2. Resolve the image references that CSS Image Embedder finds to actual files. Use Manual Resolve to manually resolve a single reference, or Auto Resolve to automatically resolve multiple references.
  3. Save the CSS file. The image references are automatically inlined when you save it.

In case you didn’t know, the data URI scheme lets you inline file references anywhere a `src` attribute is normally used. Wikipedia has a good description, as well as examples.

More instructions will follow soon on the Wiki, so stay tuned. Please comment if you like the tool, or have suggestions. Enjoy!

Download/read about it at BitBucket:

 Posted by at 1:45 am