#3!

Posted on April 2nd, 2009 by aaron
Filed under Uncategorized | 9 Comments

No, that’s not a bash command or a regular expression. :)

#3 will be joining #2 and #1, and we are pumped.
Well, I’m pumped, my wife is just trying not to feel too sick. She’ll be pumped later, like in 5 years. ;)

Design Pattern Resources

Posted on April 2nd, 2009 by aaron
Filed under programming | 1 Comment

I’ve had a few people ask me for a recommendation of some resources to learn design patterns. There’s a lot of good stuff “out there”, of course, but my response usually says just three things:

Read pretty much anything this guy writes,
Learn SOLID, and lern it güd. I recommend starting here.
and
Let me know if you have any questions and let’s chat.

If you’re anything like me, you’ll find yourself up until 4 AM reading, reading, and reading as you link from post to post and article to article. I swear one of these days I will find the end of the internet.

Debugging UI

Posted on December 15th, 2008 by aaron
Filed under .net, debugging, windows forms | 3 Comments

I’ve talked before about System.Threading.SynchronizationContext, as well as BeginInvoke/InvokedRequired/IsHandleCreated. In a multi-threaded Windows Forms application they can easily be mis-used, introducing difficult to find bugs.

One such not-so-subtle bug (application hang) is particularly nasty, and is described fairly well here. Distilled down, the application hangs, usually when the computer comes out of sleep mode, unlocks, or another similar event occurs. The hang happens in the firing of an event handler, called from “SystemEvents.OnUserPreferenceChanged”. The cause is that OnUserPreferenceChanged is trying to be super nice, and invoke the event in the appropriate context for each event subscriber. That means that if a Control subscribes to the event, the handler will be called on the UI thread. If user code (on a background thread) subscribes, the handler will be called on an arbitrary thread, etc. The problem occurs when, at some point in the past, a Form or Control was created on a background thread. The creation of the control “installed” a WindowsFormsSynchronizationContext as the current SynchronizationContext (this is default behavior). When OnUserPreferenceChanged attempts to Send (Invoke) to the appropriate thread context, it hangs because the WindowsFormsSynchronizationContext is on the wrong thread, and thus has no message pump with which to process messages.

Blah blah blah. Right now you’re thinking “Whatever dude, I’m a web developer, man, I’m just trying to fix this bug in that other jerk’s code.” Fair enough, you can read the linked post for more gory details. What you care about is the hard part. Well, hard for web developers anyway. ;) By the time the app hangs, it’s too late to find out where the problem occurred. In a medium-to-large application, how do you find the control that was created on the wrong thread? Here’s how to do it in a matter of seconds.

1. Name your UI thread. If you’re not already doing this, it’s a good idea in general. I like to call mine “UI”, personally. In your “static void Main()” add this single line of code:

Thread.CurrentThread.Name = "UI";

2. Set a breakpoint deep in the bowels of the BCL. What we want to do is cause our application to break when a WindowsFormsSynchronizationContext gets assigned to the current thread. I cracked open Reflector to look at the constructor for WindowsFormsSynchronizationContext:

And I see that there’s a call to “Application.ThreadContext.FromCurrent()”. Close enough for government work, it’ll do for what I want. I didn’t feel like figuring out how to specify a constructor call when setting a breakpoint. (If you know how, leave a comment so we can all learn!) Add a breakpoint to that method call. In Visual Studio, go to the “Debug” > “New Breakpoint” > “Break at Function…” menu. In the “Function” area type the full path to the function: System.Windows.Forms.Application.ThreadContext.FromCurrent()

When you hit “OK” you’ll get a warning about IntelliSense not finding the specified location. Hit “Yes” to set the breakpoint anyway.

3. Run your application. Depending on what version of Visual Studio you’re running, and whether you’ve got source-level debugging for the Framework turned on, you’ll either get the breakpoint on some code, or you’ll get this message box:

It doesn’t matter, you can press “OK” or “Show Disassembly”, whatever floats your boat. Go to the “Call Stack” debugging window, right-click on the red breakpoint circle located at the top of the stack frame, and select “Breakpoint” > “Filter…”

4. Add a filter to this breakpoint so that it only breaks when the current threads’ name isn’t “UI”.

After you hit “OK”, continue running your application in the debugger. The first time a WindowsFormsSynchronizationContext is created and it’s not on the UI thread, BAM. There’s your problem, and there’s your stack trace allowing you to find the bad code.

This worked like a champ for me today, hopefully you have as much success with it too.

Case insensitive string comparisons with LINQ Dynamic Query

Posted on December 15th, 2008 by aaron
Filed under .net, tips and tricks | 1 Comment

LINQ rocks. It really does.

One down-side to LINQ is that, out of the box, it’s geared towards knowing your query structure at compile-time. The values can be dynamic, of course, but it’s assumed that the structure of your query is static. For example, if you want to select a set of "Person" objects from the "People" collection where Person.FirstName starts with "Aar", you could write it as such:

var results = from person in People
              where person.FirstName.StartsWith("Aar")
              select person;

That’s all fine and good, but what about scenarios where you want to dynamically build up your query structure? In our client application we have address books (directories) that include the ability to filter them on any, or nearly any, column:

How would I accomplish this with LINQ? Not easily. Just ask Ayende or Rob Conery, both of whom have blogged about some of their adventures in advanced usage scenarios. Enter the LINQ Dynamic Query sample from Microsoft. As usual, ScottGu’s got a good write-up. In a nutshell, it’s a custom expression tree generator based on a limited (but useful) string-based query grammar. With Dynamic Query I could write the query above like this:

var results = from person in People
              select person;
results = results.Where("FirstName.StartsWith(\"Aar\")");

It solved my problem nicely. Almost. As with my example above about matching FirstName’s, let me ask: how often does a user enter an exact case-sensitive match for what they’re looking for? I can save you the trouble and tell you: it doesn’t matter. It’s an unacceptable requirement for a user to have to match something exactly. It’s already questionable that we don’t automatically use fuzzy matching algorithms.

So what I really want is to specify a StringComparison enum value on the call to "StartsWith":

var results = from person in People
              select person;
results = results.Where("FirstName.StartsWith(\"Aar\", System.StringComparison.OrdinalIgnoreCase)");

Alas, this breaks. LINQ Dynamic Query doesn’t support enum values as parameters to methods. So I added it. I won’t redistribute the sample (I’m pretty sure I can’t, but I don’t care to anyway) so here’s what you need to do to add support for enum parsing. Note that I’ve only tested it with calls to string’s StartsWith(string, StringComparison) method. I don’t know what will happen if you sprinkle enum values in random places throughout your dynamic query. Work on My Machine, your mileage may vary, etc. etc. etc.

1. Download the sample.

2. Crack open the Dynamic.cs source file. It’s scary, but you can do it. Modify it like so (I added the "if (ParseEnumType…"

Expression ParseIdentifier() {
    ValidateToken(TokenId.Identifier);
    object value;
    if (keywords.TryGetValue(token.text, out value)) {
        if (value is Type) return ParseTypeAccess((Type)value);
        if (value == (object)keywordIt) return ParseIt();
        if (value == (object)keywordIif) return ParseIif();
        if (value == (object)keywordNew) return ParseNew();
        NextToken();
        return (Expression)value;
    }
    if (symbols.TryGetValue(token.text, out value) ||
        externals != null && externals.TryGetValue(token.text, out value)) {
        Expression expr = value as Expression;
        if (expr == null) {
            expr = Expression.Constant(value);
        }
        else {
            LambdaExpression lambda = expr as LambdaExpression;
            if (lambda != null) return ParseLambdaInvocation(lambda);
        }
        NextToken();
        return expr;
    }
    // ADD THIS IF STATEMENT
    if (ParseEnumType(out value))
    {
        Expression expr = Expression.Constant(value);
        NextToken();
        return expr;
    }
    if (it != null) return ParseMemberAccess(null, it);
    throw ParseError(Res.UnknownIdentifier, token.text);
}

3. Add the definition for ParseEnumType. This little bit of nastiness is essentially doing a look-ahead to resolve a type name, since most of the parser’s rules are built to process more contextual information (such as a property name of a type, etc.) In our case, we need to attempt to match "Foo.Foo.Foo" to a type name, and if it doesn’t end up resolving, we need to reset the parser back to the beginning of "Foo" to continue parsing.

bool ParseEnumType(out object value)
{
    value = null;

    ValidateToken(TokenId.Identifier);
    Type enumType = null;
    int position = token.pos;
    string typeName = token.text;
    while (enumType == null)
    {
        // Loop until we stop processing identifiers and/or dots
        enumType = Type.GetType(typeName, false, true);
        if (enumType == null)
        {
            NextToken();
            if (token.id == TokenId.Dot)
            {
                typeName += token.text;
                NextToken();
                if (token.id == TokenId.Identifier)
                {
                    typeName += token.text;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
    }

    if ((enumType != null) && IsEnumType(enumType))
    {
        NextToken();
        ValidateToken(TokenId.Dot, Res.DotExpected);
        NextToken();
        ValidateToken(TokenId.Identifier, Res.IdentifierExpected);
        value = Enum.Parse(enumType, token.text, true);
        return true;
    }
    else
    {
        SetTextPos(position);
        NextToken();
    }

    return false;
}

4. Add an error "resource" string (but not really a true resource string) to the "Res" static class. We added a new condition, so we need an error message to match.

public const string DotExpected = "'.' expected";

Voila! Make sure your enum values are fully-qualified type names and you’ll be good to go.

Hopefully this works for you as well as it did for me, and I have to say I can’t believe I couldn’t find this on the ‘net, as I imagine this is a very common use-case.

Run ASP.NET MVC on Windows Azure

Posted on November 1st, 2008 by aaron
Filed under asp.net mvc, azure | 13 Comments

If you’ve purposefully been ignoring the announcements out of PDC, I don’t blame you one bit. Everybody knew it would be the unveiling of Microsoft’s “cloud computing” initiative, and just about the only thing we didn’t know was the official name of it: Windows Azure. And of course I pronounce it wrong every time (I say “ah-jour”, as in “soup-de-jour”). It’s hard to call it “initiative” when they’re the 3rd one to bring a product to the table. ;)

One thing I was looking forward to was hearing about the ASP.NET MVC story on Azure. So color me surprised when I found out there wasn’t one. Since ASP.NET MVC is bin-deployable it shouldn’t be impossible, and doing some quick searches didn’t retrieve any results showing anybody else having tried this. Of course later I discovered that Phil and Eilon had whipped up a sample app that ran ASP.NET MVC on Azure, but was pleased to find out that the downloadable sample app didn’t work. In fact, it seemed to just be MVC stuff slapped into a WebRole project. (I’m guessing something got “lost in translation” since it wasn’t Phil or Eilon that posted the code.)

Anyway, here’s how you can get ASP.NET MVC up and running on Azure. I’ve created a Visual Studio template for this to make it easy to set up – download it here. To avoid distributing code that isn’t my own (i.e. Windows Azure SDK Samples) there are a few steps you’ll have to take. I’m presuming that you’ve already installed the Windows Azure SDK and the Azure Visual Studio tools.

One thing that running a web application “in the cloud” means is that you can instantly scale higher by adding more “instances”. This means the leaky-as-a-sieve abstraction of “session state” isn’t immediately available (finally!) since any given HTTP request could be going to a different server. The default session state provider for ASP.NET is an in-memory provider. This assumes that every request comes to the same physical machine. Session state providers have varied in their reliability and handling of scalability, but the other built-in providers include an out-of-proc provider (still same machine, but more resilient to IIS going up and down) and a SQL Server provider. None of these are enabled on the Azure platform, for good reason.

The limitation of zero session state wouldn’t matter except that ASP.NET MVC includes the concept of “Temp Data”, which is data persisted in one request and made available to the next request only. By default, MVC uses the session to store this data.

Aside: like it does everywhere else, ASP.NET MVC allows you to swap out default implementations for TempData persistence. A better solution than what I have below is to specifically implement a TempDataProvider that uses the Azure data storage capabilities. Look for that soon. ;)

Fortunately for us the Windows Azure SDK includes some “samples”, including full implementations of membership, profile, and session providers built on the Azure data storage platform. So let’s hack those in to fulfill the default requirements of ASP.NET MVC. The only thing that I’ll say about this is that much of this stuff had better be baked into the SDK/platform by the time it goes GA. This is just a CTP, and Microsoft has been doing better at earlier community releases, so I’ll cut them some slack. ;) But this is way to much work to be a reasonable shipped solution.

Unzip the “samples.zip” file in the Azure SDK and build the “AspProviders” application.

They’ve conveniently included “buildme.cmd” batch files, but I built the application using Visual Studio since I like to see more of “what’s going on” (even though I really don’t see more, per se).

Create the required tables in the Azure Development Storage.

Open the Azure SDK command prompt under your start menu, and navigate to the directory containing the AspProviders output. Run the command “devtablegen” passing in the assembly name “AspProviders.dll”. This command creates the appropriate database structures to persist objects that meet certain criteria. Run devtablegen with no parameters for a short description, or check out the documentation for more info as well.

You’ll get a confirmation window that displays progress and shows that the table was created successfully.

Start the Development Storage service.

By now, the storage service should be running, but you’ll need to explicitly enable its endpoints. Open the UI from the system tray icon (), and click “Start”. If you’ve never started it before, it will ask you for the name of the database – select “AspProviders”.

Create a new Cloud Service and add an “ASP.NET MVC Web Role” project.

Download the Visual Studio template I created here. Import the template by copying the downloaded .zip file to “My Documents\Visual Studio 2008\Templates\Project Templates” (or whatever you have specified in Tools – Options – Projects and Solutions – General). Create a new “Blank Cloud Service” project.

 

Add a new “ASP.NET MVC Web Role” project using the installed template.

Your VS solution should now approximate this:

Under the “Cloud Service” project, right-click on the “Roles” folder and select “Add > Web Role Project in solution…” and select the web role project we just added.

Cleanup

Because I can’t distribute the compiled version of the sample app, and because the location of it on your drive depends entirely on your personal preferences, you’ll have to re-add the references manually. From the ASP.NET MVC Web Role project we added, delete the references to AspProviders and StorageClient

and re-add the references pointing to the assemblies we built above.

Press F5, and you’re up and running the default ASP.NET MVC sample app on the Windows Azure platform! From there the sky’s the limit. Or maybe “the cloud’s the limit”?

kick it on DotNetKicks.com

The Aaron and Mike Show

Posted on October 24th, 2008 by aaron
Filed under aaron and mike show | 3 Comments

I wasn’t going to say anything until we had another show or two under our belt (for your sake, poor innocent reader!) but Mike let the cat out of the bag. He’s much crueler than I am. ;)

I recently heard a reading of an essay where the author said that the reason children create so much art is that they don’t know that they’re bad at it. That’s so true. And yet I love walking through my 4-year old daughter’s pre-school looking at the dozens and dozens of masterpieces posted on the walls.

There is something about society, peer pressure, fear of failure, etc. that keeps us from trying things because we’re not good at it. “I wish I was good at that,” we tell ourselves. But we get into a race condition where we demand excellence from ourselves before we can start, yet we need to start to achieve that excellence.

Enough psychobabble – what am I getting at, anyway? It’s the Aaron and Mike Show. My friend and coworker Mike and I decided we’d take no more than 15 minutes on a Thursday afternoon (4PM EST) and broadcast a “show” LIVE right from my office. We’ll talk about software and the craft of building software. Imagine it like an even shorter Hanselminutes. Not the Hanselminutes of late, which are just interviews, nay, it’s more like the old-school Hanselminutes from way back yonder when Scott was building products for Corillian and talked about the real development challenges he faced every day. (Both styles of Hanselminutes are good, but each serves/served a different purpose.)

Mike and I will be talking about the development challenges we run across every day, as well as the kinds of things we are continually doing to improve our skill at the craft of software. It’ll be hard to fit it into 15 minutes but we will do our best. Each show will be recorded, so if you can’t make it to the live show, you can still see the recorded version later, and I’ll put up a blog post for each show with notes, follow-ups, etc.

Our first show (view it here) was SPECTACULAR! Just look at the kind of feedback we received:

I expect this to be spectacularly lame :) (getting popcorn)
- subdigital

thanks for your first show! Looks nice, a bit flaky though. But the effort is much appreciated. We all should start doing this!
The deep insights you guys raised OTOH completely made up for the flakiness
- azuidhof (2nd tweet)

Okay, so it was a little rough. :) But we’re new at this, we had fun doing it, and I’m looking forward to getting better as we go along.

View the video here 

Please leave us feedback with ideas of what you’d like us to talk about. You can leave a comment on this post if you like. We’ll be having the occasional guest on the show (our co-workers) to share something going on in their world of software.

My main question for you is, will you still respect me in the morning? ;)

Indy Tech Fest Slides

Posted on October 6th, 2008 by aaron
Filed under asp.net mvc, community | 3 Comments

I really enjoyed giving my talk on ASP.NET MVC at Indy Tech Fest this year. Thanks to all who came! I think there were 75-100 people there.

A poll at the beginning showed that most people in attendance had done some sort of web development, about a third had done ASP.NET development, and 2 people had worked with ASP.NET MVC. The most challenging thing was that almost everybody was unfamiliar with the MVC pattern. And yet again I learned the difference between a master and a wanna-be. A master can take complex principles and concepts and express them in a simple form that people can immediately understand. I, on the other hand, cannot. I seemed to struggle with getting the “core concepts” of ASP.NET MVC across in a way that was clear and unambiguous.

I’ve created a slideshare presentation with the slides. It’s an overview, and I only had time to cover a few aspects of it, but I’m still sure I was off on a few concepts – if you notice something, leave a comment so I can learn!

Here links to various MVC resources to get you started with ASP.NET MVC:

- Download ASP.NET MVC from Codeplex
- MVCContrib – community contributions/extensions to ASP.NET MVC
- CodeCampServer – a slightly-out-of-date-but-still-good reference implementation
- Official ASP.NET MVC site (lots of links to resources)
- ASP.NET MVC Forums – a lot of questions asked and answers given
- ScottGu’s MVC posts
- Phil Haack is the ASP.NET MVC Program Manager
- Stephen Walther has done many posts on ASP.NET MVC
- Blog posts tagged “aspnetmvc” on Technorati

Why the iPhone Rocks

Posted on September 15th, 2008 by aaron
Filed under iphone | 5 Comments

It has “save me 30 minutes” functionality baked into the platform.

Bam.

Speaking at IndyTechFest 2008

Posted on September 14th, 2008 by aaron
Filed under community | No Comments

I’m giving a talk at IndyTechFest 2008 on ASP.NET MVC. Due to the nature of the event, it’ll be more of an introduction to ASP.NET MVC than a deep dive. But we will still have fun looking at things like doing some AJAX with jQuery, etc.

Hope to see you there! The event sold out quickly, but in my experience you can still get in if you show up the morning of the event. If you’re there, come over and say hi!

Staying Sane as a Technical Manager

Posted on September 2nd, 2008 by aaron
Filed under misc | 2 Comments

A while ago I wrote about some characteristics of a good Technical Manager. After having some time to reflect on the transition from Developer to Technical Manager, there are three little words that I think every Technical Manager needs to take to heart.

I love you.

Oh wait, no, that was supposed to go in the email to my wife.

Know your limits.Drawing for ε-δ definition of limit

Consider this phrase as just one aspect of the golden rule as it relates to leadership. For example, I am a person who loves to dig into details and who tends to struggle with intentionally staying at a high-level view of a project. As the team grew, we had 8 people each working on a different project. With my natural hands-on style, I found myself inadvertently ignoring half of the team, barely keeping up with the current state of their projects, while digging into the other half of the projects.

I realized that my current limitations were preventing me from giving attention to my co-workers and their projects that they needed, and at the same time I was growing increasingly stressed out and frustrated from trying to keep up with everybody. In the spirit of “doing to others what I would want done to me” I knew that my co-workers deserved proper attention and focus from their manager. I also knew that the more stressed I was, the less effective I was.

The solution in my situation? Find and/or develop another Technical Manager and split the team up, allowing each manager to provide an increased level of focus to their teams.

We split the teams about a month ago and the day the split went into effect I swear I felt a literal load taken off of my shoulders, and the result for both teams has been wonderful.

Team mitosis and optimal team size is an interesting topic that perhaps I’ll muse about more in-depth in a future post.