PowerShell unit testing: mocking constructors

I started using PowerShell about a year ago (my new team uses it for both build and deployment scripts), and I keep meaning to start blogging about it.

Today’s tip: mocking constructors.

In most languages, you can’t write a unit test that intercepts constructor calls. If you have a method like this:

public void OpenBrowser() {
    var driver = new FirefoxDriver();
    // ...
}

then your method is tightly coupled to the FirefoxDriver class, and (without refactoring) there’s no way for your tests to call that method without creating a new instance of FirefoxDriver, and now everything is fraught with peril. This kind of tight coupling has been a problem since forever, and it’s the reason why we have the Factory pattern.

(Yes, you can use something like Microsoft Shims or TypeMock Isolator to intercept constructor calls, but those work by going outside the language and sinking their hooks deep into the .NET runtime. And you still have to return a FirefoxDriver instance; you can’t substitute something else.)

But in PowerShell, as I recently discovered, you don’t need the Factory pattern. The way to create .NET objects is to call the New-Object function. And Pester, the PowerShell unit-testing framework, can mock any function. Including New-Object.

Now, in C# code, I’m all about refactoring the code to use a factory (or a Func<T>, or dependency injection). But PowerShell is a different beast with different idioms, and I’ve found cases where mocking New-Object makes really good sense.

Here’s the basic template I work off of:

Mock New-Object {
    [PSCustomObject] @{
        Property1 = "value1"
        Property2 = 42
    }
}

This tells Pester to replace the New-Object function with my own script block, which uses the [PSCustomObject] syntactic sugar to return a new object with two properties, Property1 and Property2.

The script block that you pass to Mock can also access the $TypeName and $ArgumentList parameters that were passed to New-Object, so you can do things like returning fakes for some classes but falling back to the original New-Object cmdlet for all other classes:

Mock New-Object {
    $Type = Invoke-Expression "[$TypeName]"
    if ([OpenQA.Selenium.Remote.RemoteWebDriver].IsAssignableFrom($Type)) {
        [PSCustomObject] @{}
    } else {
        & (Get-Command New-Object -CommandType Cmdlet) @Args
    }
}

But I’d been using this technique for a while before I had to get that fancy. Mostly in PowerShell you don’t use New-Object a lot; arrays and hash tables and [PSCustomObject]s have their own dedicated syntax and don’t need to go through New-Object (which is fine since they don’t have any side effects you’d need to worry about mocking).

Microsoft.TeamFoundationServer.Client: getting started, and getting sprint dates

There’s a new REST API in TFS 2015. It’s completely undocumented at the moment, although Visual Studio Online’s REST API is well-documented and they probably overlap a lot.

There’s a NuGet package called Microsoft.TeamFoundationServer.Client that provides a .NET client library for the TFS REST API. Unfortunately, it’s also completely undocumented, and in this case there is no other documentation to refer to — which makes it hard to figure out where to start.

But you’re in luck: I’ve been tinkering with it a bit, and I’m going to start blogging what I’ve learned about how to use the darned thing.

Connecting to work item tracking

Unlike the old-school TFS API, there isn’t some central class you have to create and authenticate to and then query for services.

Instead, you instantiate the client for the particular service you want, and hand it an object with authentication information. Then you start calling methods. I’m guessing that each method corresponds to a single HTTP request, but I haven’t verified that.

Let’s say we want to do something with work item tracking — basically anything relating to work items, including things like saved queries, area paths and iterations, work-item edit history… all that stuff. For that, we need to instantiate WorkItemTrackingHttpClient.

using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
using Microsoft.VisualStudio.Services.Common;

var client = new WorkItemTrackingHttpClient(
    new Uri("http://myserver:8080/tfs"),
    new VssCredentials(true));

VssCredentials

VssCredentials tells the library how you’re going to authenticate. There are a bunch of constructor overloads, and I’m not clear on when you would use some of them. But here are the most obvious ways I see to authenticate:

Authenticate using my current Windows credentials

new VssCredentials(true)

This is probably simplest in most cases. Just pass true for the useDefaultCredentials constructor parameter.

Authenticate using a specific username and password

Maybe you’ve got a username and password in your web.config (stored in encrypted form, of course), and you want to use those to authenticate against TFS.

new VssCredentials(new WindowsCredential(new NetworkCredential(userName, password)))

It’s possible there’s a way to do that without chaining quite so many objects together. Or maybe not; you get used to things being unnecessarily complicated when you’re working with TFS.

Getting a list of sprints

Sometimes you need to query the work items for the current sprint. So let’s start by getting the list of sprints.

Sprints are just iterations (with some extra metadata that describes their start and finish dates), so we’ll query the iteration tree.

using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;

var rootIterationNode = await client.GetClassificationNodeAsync(
    teamProjectName,
    TreeStructureGroup.Iterations,
    depth: int.MaxValue);

Each team project has its own areas and iterations, so you have to pass in the name of your team project. I assume you already know your teamProjectName and have it ready to pass in. (You can also pass in the project’s Guid if you happen to have it.)

GetClassificationNodeAsync returns a WorkItemClassificationNode:

public class WorkItemClassificationNode : WorkItemTrackingResource
{
    public WorkItemClassificationNode();

    public IDictionary<string, object> Attributes { get; set; }
    public IEnumerable<WorkItemClassificationNode> Children { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public TreeNodeStructureType StructureType { get; set; }
}

The method returns the root node for the iteration tree; as far as I know, the root’s Name always matches the name of the team project. Then you’ve got its children, and you can recursively walk your way through the tree.

Be careful — if a node has no children, Children is null rather than an empty list. (Makes sense for the JSON, but the API really should have smoothed out that wrinkle.)

You’ll notice that this class doesn’t have properties for StartDate and FinishDate for sprints. (I think that’s because you can also ask this method for area paths, where start- and finish-date properties would make no sense at all.) The object hides the dates inside the Attributes dictionary, under the keys startDate and finishDate; the values are DateTimes. Once again, beware: if a node has no attributes (e.g., if it represents an iteration that isn’t a sprint), the Attributes dictionary is null.

Here’s some sample code to get the start and finish dates (if present) from an iteration. If they’re present, it’s a sprint.

if (iterationNode.Attributes != null) {
    object startDateValue;
    object finishDateValue;
    iterationNode.Attributes.TryGetValue("startDate", out startDateValue);
    iterationNode.Attributes.TryGetValue("finishDate", out finishDateValue);
    var startDate = startDateValue as DateTime?;
    var finishDate = finishDateValue as DateTime?;
    if (startDate.HasValue && finishDate.HasValue) {
        // do something with startDate.Value and finishDate.Value
    }
}

Or you could do like I do, and write a GetValueOrDefault extension method for Dictionary<TKey, TValue>, at which point it becomes:

if (iterationNode.Attributes != null) {
    var startDate = iterationNode.Attributes.GetValueOrDefault("startDate") as DateTime?;
    var finishDate = iterationNode.Attributes.GetValueOrDefault("finishDate") as DateTime?;
    if (startDate.HasValue && finishDate.HasValue) {
        // do something with startDate.Value and finishDate.Value
    }
}

Other notes

If you want to load both iterations and area paths, you can save yourself a round-trip by calling client.GetRootNodesAsync, which returns them both in a single call (it returns a list of WorkItemClassificationNode instead of a single node). Remember to specify the depth parameter, or it’ll only return the root iteration and the root area path, without their children.

Further reading

The Visual Studio Online API Overview has a good conceptual overview of some of the terms you’ll see; for example, it explains the difference between “revisions” and “updates” when you’re looking at work item history. Worth checking out.

If I blog more about Microsoft.TeamFoundationServer.Client, you’ll be able to find it under my microsoft.teamfoundationserver.client tag.

Making DataContractSerializer play nice with UpdateControls

I’m really psyched about UpdateControls. I haven’t used it in too many projects yet, but it’s already changing the way I think about INotifyPropertyChanged, and opening new horizons yet unexplored.

(If you’re not familiar with UpdateControls, here’s my intro. tl;dr: If you do MVVM, you want to learn about UpdateControls. And it’s free.)

But UpdateControls just takes care of what happens between your model and your viewmodel and your view. There are other concerns your app has to figure out too, like moving data between your model and some kind of persistent storage. I’m writing a game, so I don’t have a database back-end or a service tier; I just want to save state to a local file. Sounds like a job for DataContractSerializer.

Simple enough, right? I just slap a [DataContract] attribute on my model, [DataMember] on all the public properties, and write it out, no problem. Then I try to load it back in, and… my app promptly crashes with a NullReferenceException. What went wrong?

War of the Constructors

The crux of the problem is that an UpdateControls-based model has to do some initialization in its constructor before you can start using its properties, whereas DataContractSerializer doesn’t acknowledge that the constructor even exists.

Recall that, when you define a model object using UpdateControls, you wrap each of your data fields in an Independent<T> that handles the bottom half of the notification magic. Our model object looks something like this:

[DataContract]
public class FooModel {
    private readonly Independent<bool> _active = new Independent<bool>();
    [DataMember]
    public bool Active {
        get { return _active; }
        set { _active.Value = value; }
    }

Notice that the _active field is initialized to a new instance of Independent<bool>. When this code is compiled, that assignment actually gets inserted at the beginning of the IL for FooModel’s constructor(s).

DataContractSerializer, when it deserializes a stream back into an object, doesn’t call any constructors; it just grabs an empty hunk of memory and calls it an object. I don’t know why it skips the constructors; it makes things awfully weird — as well as making it hard to delegate the property’s storage to another object, like you do with UpdateControls. Since FooModel’s constructor never ran, _active is null; so when the deserializer tries to set the Active property, the _active.Value assignment causes a NullReferenceException.

You can get different behavior by removing the [DataContract] attribute and serializing the object as a Plain Old CLR Object (POCO). If you’re deserializing a POCO, DataContractSerializer actually will call the constructor. But, it won’t serialize sub-objects — for POCOs, it looks like it only operates on properties with primitive types. No good for me — I don’t want to cram my entire application’s state into a single object.

Classic solution: Persistence objects

If I was using Entity Framework, I wouldn’t even be thinking about saving my model objects directly; I’d already have a separate set of entity classes that represent tables in the database. These classes wouldn’t depend on UpdateControls, and I’d have to manually copy the data between my model and my entity objects. Similarly, if I was saving to a service tier in a multi-tier application, I’d have the same situation with data transfer objects: I’d have to copy my model object’s contents to a DTO and back.

I could do the same thing with DataContractSerializer. I could define some persistence classes — dumb data contracts that are only used to save and load — and then copy data between those and my models.

The thing is, that “copy data back and forth” step is (a) hard, (b) boring, and (c) easy to screw up. I strive to be constructively lazy, and hard/boring/easy-to-screw-up is high on my list of things to avoid.

At work, we automate the hard/boring parts (and unit-test the easy-to-screw-up parts) with AutoMapper, which works really well. I think it would play pretty nicely with UpdateControls. But there isn’t (yet?) a WinRT version of AutoMapper, so that won’t help me with my WinRT app.

And even if I could use AutoMapper, it feels redundant to make a whole separate set of classes, with all the same properties as my model objects, unless it’s absolutely required by some persistence framework. Even if AutoMapper was there to remove the grunt work (and warn me when I forget to add a property to my persistence object), creating all those extra classes still feels unnecessary. DataContractSerializer should be able to serialize objects; that’s its job. The only problem is that it doesn’t run any of our initialization code. If that was solvable, we’d be golden.

OnDeserializing

If you poke around the System.Runtime.Serialization namespace, you’ll find the OnDeserializingAttribute.

The documentation for this attribute is pretty vague: it just says that it lets you designate a method to be “called during deserialization of an object”. When during deserialization? Before any fields are deserialized? After all the fields?

But since there’s also an OnDeserializedAttribute, I think I’m fairly safe in guessing that these follow the usual pattern: first the -ing method is called, then some other work (deserializing the object’s properties) is done, then finally the -ed method is called. Assuming that’s true (and I think it is, since my tests are passing), then you can use it to make a constructor stand-in for deserialization.

So you can make these changes:

  1. Add a new method called InitFields.
  2. Remove all the initialization expressions from the field declarations, and move those assignments into InitFields.
  3. Remove the readonly from the fields, since they’re now being assigned in a method, not in the constructor.
  4. Add an OnDeserializing method and tag it with [OnDeserializing], and give it a parameter of type StreamingContext. (I don’t know what the parameter is for, but you get a runtime error if it’s not there.)
  5. Call InitFields from both your constructor and your OnDeserializing method.

If you’re using ReSharper, then you’ll also want to add the JetBrains.Annotations NuGet package, and mark the OnDeserializing method as [UsedImplicitly] so ReSharper doesn’t warn you about the unused parameter.

Et voilà — you now have an UpdateControls-based model that you can serialize and deserialize successfully with DataContractSerializer! Here’s what it looks like:

[DataContract]
public class FooModel {
    private Independent<bool> _active;
    private void InitFields() {
        _active = new Independent<bool>();
    }
    public FooModel() {
        InitFields();
    }
    [OnDeserializing, UsedImplicitly]
    private void OnDeserializing(StreamingContext context) {
        InitFields();
    }
    [DataMember]
    public bool Active { ... }

This works, but it feels a bit clumsy, what with the extra two methods, and the assignments being separated from the field declarations. Just for fun, I decided to see if I could go one better.

Automating the process

Why not make a base class that uses Reflection to find all of our Independent<T> fields, and instantiate them automatically as needed?

My first thought was to plug this logic into both the constructor and OnDeserializing. Here’s what a model would look like in that case:

// Note: this example isn't compatible with the final version of SerializableModel
[DataContract]
public class FooModel : SerializableModel {
    [UsedImplicitly] private readonly Independent<bool> _active;
    [DataMember]
    public bool Active { ... }

If the base constructor instantiates the Independent<T>s for us, then _active doesn’t need an initializer anymore. But then ReSharper’s static analysis warns us that the field is never assigned, and we need to suppress the warning by adding an attribute to tell it that the field is used implicitly (i.e., via Reflection).

I thought I was being clever by removing all the “duplicate code” of Independent<T> instantiation, but ReSharper’s warning was my first hint that no, this really wasn’t technical elegance — it was a code smell. And after playing around with it for a couple of days, I had to agree.

It comes down to cognitive load. Our brains are only so big. When the code does what it says, you don’t have to waste as much of your brain capacity on technical minutiae; you have more brainpower available to actually solve the problems at hand. It’s not worth “removing duplication” if it means the code no longer does what it says. Any time you have to stop and think about where that field is being instantiated, it derails your train of thought.

As an added bonus, doing things this way also means that you can make an existing UpdateControls-based model into a serializable model just by changing its base class, and nothing else:

[DataContract]
public class FooModel : SerializableModel {
    private readonly Independent<bool> _active = new Independent<bool>();
    [DataMember]
    public bool Active { ... }

I like the way this code reads. All the UpdateControls-based stuff looks exactly like you’d expect. The only unusual thing is that you’re descending from SerializableModel, and that’s almost as declarative as the [DataContract] attribute.

One big caution: if you pass a default value to the Independent<T> constructor, that default won’t be used for deserialization. This isn’t a problem in the usual case, where you’re about to load that property’s value from storage. But if you’re reading an older stream that doesn’t contain that property, you might have to figure something out.

Without further ado, here’s the SerializableModel class. This was written for WinRT, but should also work in .NET 4.5. (If you’re using an older version of .NET, the Reflection APIs are totally different.)

[DataContract]
public class SerializableModel
{
    private IEnumerable<TypeInfo> Ancestry
    {
        get
        {
            for (var type = GetType(); type != null; type = type.GetTypeInfo().BaseType)
                yield return type.GetTypeInfo();
        }
    }

    private void CreateIndependentFields()
    {
        var independentFields =
            from type in Ancestry
            from field in type.DeclaredFields
            let fieldType = field.FieldType.GetTypeInfo()
            where fieldType.IsGenericType &&
                  fieldType.GetGenericTypeDefinition() == typeof(Independent<>)
            select field;

        foreach (var field in independentFields)
        {
            var instance = Activator.CreateInstance(field.FieldType);
            field.SetValue(this, instance);
        }
    }
    [OnDeserializing, UsedImplicitly]
    private void OnDeserializing(StreamingContext context)
    {
        CreateIndependentFields();
    }
}

I consider this code to be more of a useful technique than actual copyrighted intellectual property, so feel free to use the above code in any context you wish (no credit necessary). But I’d appreciate hearing about it if you find this useful.

WinRT’s default “save on suspend” isn’t good enough

If you create a new WinRT app, using the templates that ship with Visual Studio (e.g. the Grid App template), the default code will save your app’s state when the app gets suspended.

“Save on suspend” seems like a reasonable model. The trouble is, your app can get killed without ever getting its suspend notification.

If you close a WinRT app (either by pressing Alt+F4, or dragging from the top of the screen to the bottom), Windows switches away from the app immediately, but it actually waits about ten seconds before firing the app’s OnSuspending method. (That “about ten seconds” comes from my own observations of how long it takes until the timestamp changes on the autosave file. That’s on a physical machine, not a VM, so it should be about best-case.)

If, during that ~10-second window after the app gets closed, the user decides to start the app again, then Windows kills the previous instance, flat-out, and starts a new instance. In this case, the previous instance never gets a chance to save.

I suspect (though it’d be tricky to try to confirm) that your app could even get terminated while it’s in the middle of an async save operation — at which point your save file is only partially written, and therefore corrupt, and the user loses all their data.

So if the only time you save your state is in your app’s OnSuspending method, you’re asking for trouble. If a user closes your app, and then re-launches it again less than ten seconds later, they will lose all the data they entered during their previous session, and maybe everything.

Now, why would somebody do that — close the app and then re-launch it right away? Beats me. Maybe they close it and then think of something else they wanted to do. Maybe your app doesn’t have a Home button and they’re frustrated with trying to find their way back. Maybe the app doesn’t correctly refresh the date when you resume it the next day (Microsoft’s XBox games, with their date-sensitive daily challenges, are really bad at this).

But you know what? It doesn’t matter why they do it. Closing and reopening is a totally innocuous action. It should not screw the user out of their data.

Right now, I don’t have a great alternative to recommend; I just ran into the problem, I haven’t solved it yet. I’ll probably keep the “save on suspend”, so I have a chance to save the latest and greatest state; but I’ll probably also add some background saves as well. But of course all those saves will be async operations, so I have to come up with a way to make sure they don’t step on each other. Good times.

Stop writing INotifyPropertyChanged, start using UpdateControls

If you use MVVM, you know all about INotifyPropertyChanged, and mostly you know that it’s a pain. Simple properties are a lot of code, but otherwise not too bad; but once you start having derived properties, it’s hard to make sure you fire all the right change events at the right time (and even harder to keep it right as you refactor).

Can’t we do things the way Knockout.JS does, with a framework that automatically discovers the dependencies for you?

Why yes, yes we can. Last weekend I discovered UpdateControls.

Introduction to UpdateControls

UpdateControls is free and open-source (MIT license), is available via NuGet, and works pretty much everywhere: WinRT, WPF, Silverlight, Windows Phone 7 — even WinForms! Update: WP8 is supported too.

The idea is:

  • Don’t implement INotifyPropertyChanged on your viewmodel.
  • Wrap each of your independent variables inside an Independent<T> instance. Expose the underlying value through properties.
  • For computed properties, just write the code to compute the values.
  • Before you assign your top-level viewmodel to a DataContext, wrap it with a call to ForView.Wrap.

And that’s it. You don’t need to fire notifications manually; UpdateControls does it for you.

An example:

public class MyViewModel {
    private Independent<string> _firstName = new Independent<string>("");
    private Independent<string> _lastName = new Independent<string>("");
    private Independent<bool> _lastNameFirst = new Independent<bool>();

    // Expose independent values through simple wrapper properties:
    public string FirstName {
        get { return _firstName; }
        set { _firstName.Value = value; }
    }
    public string LastName {
        get { return _lastName; }
        set { _lastName.Value = value; }
    }
    public bool LastNameFirst {
        get { return _lastNameFirst; }
        set { _lastNameFirst.Value = value; }
    }

    // Dependent (computed) properties are just code:
    public string Name {
        get {
            if (LastNameFirst)
                return string.Format("{0}, {1}", LastName, FirstName);
            else
                return string.Format("{0} {1}", FirstName, LastName);
        }
    }
}

// And in the view:
DataContext = ForView.Wrap(new MyViewModel());

And like magic, all your properties, all your logic, will start notifying the UI of changes. Between the ForView.Wrap wrapper at the top and the Independent<T> at the bottom, UpdateControls is able to automatically track all the dependencies, and triggers change events for computed properties whenever their ingredients change. This even works if a property changes which ingredients it uses.

ForView.Wrap wraps your top-level viewmodel in an internal class called DependentObject<T>. The first time a databinding asks for a property, the DependentObject<T> switches into recording mode, and then invokes your viewmodel property. Until that property returns, the DependentObject<T> takes note of every time you read the value from any Independent<T> anywhere; and whenever you do, it hooks that Independent<T>‘s change event.

Then the DependentObject<T> caches the property value and returns. Next time XAML asks for the value, it just returns it. (Its ingredients haven’t changed, so why not?) But as soon as any of the ingredients change, it clears its cache and fires PropertyChanged. There’s a lot of magic under the covers, but using it is dead simple. In principle.

As with any magic, there are some subtleties and gotchas, which I go into below. But first, some important notes about the documentation.

API drift, or, an UpdateControls documentation survival guide

UpdateControls has a fair bit of documentation, including several good videos. Unfortunately, the API has changed in a couple of significant ways over time, but a lot of documentation still refers to the old APIs. So some places you see it one way, and some places you see it the other way, which is hella confusing.

The old APIs do still work (though not on every platform and not with every edition of Visual Studio), but there are easier — and more universal — ways to do things now.

Here are the two things you really need to know before you start reading the UpdateControls documentation:

Codegen vs. Independent<T>

Independent properties used to take more code than what I showed above. It was so tedious that the author even wrote a Visual Studio add-in to do the code generation for you. But now we have Independent<T>, which is enough simpler that you don’t need codegen. The old way still works (as long as you don’t have Visual Studio Express, which doesn’t support add-ins), but Independent<T> does a better job of encapsulating the boilerplate code, so IMO it’s the way to go.

Unfortunately, most of the code samples and screencasts still use the old way. You’ll see (and hear, in the videos) lots of references to Ctrl+D G, which tells the VS add-in to do its code generation. And you’ll see a lot of code like this:

private string _firstName;

#region Independent properties
// Generated by Update Controls --------------------------------
private Independent _indFirstName = new Independent();

public string FirstName
{
    get { _indFirstName.OnGet(); return _firstName; }
    set { _indFirstName.OnSet(); _firstName = value; }
}
// End generated code --------------------------------
#endregion

My advice: Don’t install the MSI (in these days of NuGet, the MSI is really just there to install the VS add-in). Ignore the VS add-in entirely. Tune out whenever the videos talk about Ctrl+D G.

Just add the NuGet package to your project, and then use Independent<T>. The above code becomes this, which is simple enough to write and maintain by hand:

private Independent<string> _firstName;

public string FirstName {
    get { return _firstName; }
    set { _firstName.Value = value; }
}

By the way, that’s not a typo in the getter. You can return _firstName.Value if you like, but Independent<T> also has an implicit conversion to T, so as long as it’s not Independent<object> you can indeed just return _firstName;.

{u:Update} vs. plain old bindings

Originally, UpdateControls had a XAML markup extension ({u:Update}) that you were supposed to use in place of {Binding}. It took care of turning on dependency-recording mode whenever values were bound to the UI, so that it knew how to watch for changes and update the UI when ingredients change later.

Unfortunately, not all the XAML platforms support markup extensions. Silverlight didn’t get them until v5. Windows Phone 7 doesn’t have them; not sure about 8. WinRT doesn’t support them. {u:Update} isn’t going to cut it for those platforms. I suspect that {u:Update} also wouldn’t play well with visual designers like Blend; they’re all about the {Binding}.

So UpdateControls added ForView.Wrap(), which you can use in combination with plain old {Binding}. If the objects you expose to your XAML and your DataContexts and your Bindings are wrapped for view, you get the same magic, but without needing markup extensions.

Any time you see {u:Update} in the documentation, just mentally substitute {Binding}, and make sure the viewmodel gets wrapped with ForView.Wrap before the view sees it. For example:

// Using the PersonViewModel class from the first code sample, above:
var viewModel = new PersonViewModel();
view.DataContext = ForView.Wrap(viewModel);

<!-- This will automatically update whenever ingredients (FirstName, LastName) change. -->
<TextBlock Text="{Binding Name}"/>

Gotchas

If you’re starting with UpdateControls on a new project, I would imagine it’s not too hard to follow the rules and have things work well. If you’re integrating it into an existing code base, you’re more likely to run into gotchas. Here are some of the problems I ran into when trying to refactor my project to use UpdateControls.

Don’t use INotifyPropertyChanged

If your viewmodel implements INotifyPropertyChanged, UpdateControls assumes you know what you’re doing, and ForView.Wrap won’t wrap that class; instead it presents your class as-is to the view. The consequence is that the computed-property notification magic won’t work for your INPC class or anything inside it. If you implement INotifyPropertyChanged, it’s all on you.

Which means that, if you’re trying to refactor from INPC to UpdateControls, you can’t do it one property at a time. To use Independent<T>, you can’t have INotifyPropertyChanged. You’ll have to change your entire viewmodel class at once: remove INotifyPropertyChanged, add Independent<T>s for everything, all in one fell swoop.

If you do viewmodel composition — where one viewmodel exposes other viewmodels as properties (think nested panels inside a larger screen) — then you probably want to start at the top level (the whole screen), and work toward the leaves (nested panels).

Corollary: Don’t use ObservableCollection<T>

I had viewmodels that exposed collections, and nothing was happening when the collection items’ properties changed. It turns out that ObservableCollection<T> implements INotifyPropertyChanged (makes sense when you think about it; you might want to bind to its Count) — so UpdateControls just exposed the collection instance directly to the UI, without attaching any of the dependency-recording logic: not for the collection itself, and not for the items inside it, either.

So don’t use ObservableCollection<T> with UpdateControls. Use IndependentList<T> instead (it’s the UpdateControls equivalent of an observable collection). Or just a plain old List<T> if the contents aren’t going to change. Or even a LINQ query (great for filtering — as long as the filter conditions boil down to Independent<T>, changing them will automatically re-run the LINQ query). But if you start using UpdateControls, you should get rid of all your references to ObservableCollection<T>.

ForView.Wrap and dependency properties

This one may be peculiar to my code, but I had some custom dependency properties whose value was a custom class. Once I started using UpdateControls, their value wasn’t that custom class anymore; the view layer (where dependency properties live) operates on the wrapper objects, not the actual viewmodels. Since my DependencyProperty.Register call specified that the property value should be of type MyCustomClass, but the actual instance was a DependentObject<MyCustomClass>, the bindings saw a type mismatch and never set my property. To get around this, I had to change my DependencyProperty.Register call to specify object as the property’s value type. (And of course my property’s change event had to use ForView.Unwrap<T> instead of casting directly to the class type.) This probably won’t affect many people, but it’s worth noting since I burned some time trying to figure it out.

Debugging wrapper objects

If you’re in the debugger, and you’re looking at a wrapper object (from ForView.Wrap), the tooltip will show the ToString() from the wrapped class — which is often the name of the wrapped class. It can be hard to even realize that the object you’re looking at is a wrapper, and not the viewmodel itself.

It’s not hard if you know how, though. If you expand the tooltip, wrappers will have a “HasErrors” property, and not much else. That should be easy to tell apart from your actual viewmodel (which will typically have lots of properties).

If you then want to drill down to see the properties of the wrapped instance, you can expand “Non-Public Members”, then “_wrappedObject”.

Debugger tooltip with UpdateControls

Integrating with Caliburn.Micro

I tried combining both UpdateControls and Caliburn.Micro in the same project, mostly because I was already using Caliburn.Micro’s IViewAware so my viewmodels could fire animations on the view and wait for them to complete. Here’s what I learned:

  • Don’t use Caliburn.Micro’s base viewmodel classes, because they implement INotifyPropertyChanged (see above).
  • Caliburn.Micro doesn’t know about UpdateControls’ wrapper classes. If you’re doing viewmodel-first (where Caliburn.Micro automatically discovers and instantiates the correct view type for you), and your DataContext is a DependentObject<PersonViewModel>, Caliburn.Micro’s conventions will probably look for a DependentObjectView or something — it doesn’t know that it’s supposed to look for a PersonView. This isn’t hard to deal with, though; Caliburn.Micro has good extensibility points for this sort of thing.
  • The IViewAware stuff won’t work out of the box either, because Caliburn.Micro takes the DataContext and says “does it implement IViewAware?” and of course it doesn’t, because it’s got the wrapper object, not your viewmodel. None of the lifecycle stuff (IGuardClose and the like) would work either, because it’s also based on interfaces. Again, you could hook CM’s extensibility points to make this work.
  • No idea how Caliburn.Micro’s {x:Name}-based binding conventions would play with UpdateControls. I didn’t get that far.

In the end, I decided not to use Caliburn.Micro for this app. I had a lot of custom UI, so the conventions weren’t much use to me; I was really only using CM for IViewAware, which would require some coding to integrate with UpdateControls. Easier to roll my own at that point.

But I’m confident you could use the two together. If anyone digs into this further and wants to share their code, drop me a line and I’ll either post it or link to you.

Conclusion

I’m pretty excited about UpdateControls. Yeah, I spent a lot of time here talking about the downsides and gotchas. But I wouldn’t have bothered if it didn’t show so much promise.

If you’ve used Knockout, or if you’re tired of keeping track of which calculated properties to fire PropertyChanged events for whenever something changes, you owe it to yourself to take a look at UpdateControls.

Here’s where to start:

  • First, look through the notes above about API drift. You’ll want to be able to mentally translate the out-of-date code samples as you see them.
  • Then head over to the UpdateControls documentation and read through all half-dozen or so pages; they’re short. Also take a quick look through the other sections in the sidebar (“Examples”, “Tips”, “Advanced Topics”).
  • Then check out the videos, which cover different material than the docs, and which dig a lot deeper. They’ll really give you an idea of what UpdateControls can do.

My current project: Stupid Quest

I haven’t blogged much in a while, and I need to. I’ve been writing a video game (aren’t I always?), and there’s stuff to blog about.

But for now, I’ll just post an early screenshot. (The real thing will run fullscreen, as a Windows 8 app.)

Screenshot of the Stupid Quest battle screen

Attacking isn’t working yet, so the monsters just taunt you.

Hmm. It looks a lot better with animation. Oh well.

User group presentation on AvalonEdit

This month, the Omaha .NET user group did lightning rounds. I did a presentation on AvalonEdit.

If anyone’s interested, here’s the video: 2012 December Omaha .NET User’s Group. My part goes from 1:02 to 1:20. The slides are pretty readable in the video, the code less so. The audio isn’t great, but is mostly intelligible. If anyone’s interested, check it out.

I haven’t made my code available for download, but I keep intending to. If anyone’s interested in the code, drop me a note.

Also presenting were:

  • Volker Schulz, “Windows Azure – Build, Debug and Deploy” (0:00 to ~0:35)
  • Naveen Akode, “MSBuild – Basics and Usage” (~0:35 to ~1:02)
  • Brian Olson, “WebAPI and Moustache” (~1:20 to ~1:35)

XamlParseException in WinRT

I’m writing a video game (as always), this time as a Windows 8 app. Currently I’m still developing on a VM running the Release Preview of Windows 8 and Visual Studio 2012, but I just got a chance to build and run on a machine running the final RTM versions of both.

When I ran my app, it showed the splash screen for a second or so, then dumped me back to the Start screen. So I tried running under the debugger, and got a XamlParseException: “XAML parsing failed.”

<rant>

I’ve commented before that Microsoft obviously put their most junior programmers to work on writing the WinForms ToolStrip in .NET 2.0. (If you haven’t had to deal with the flaky design, and bugs, of ToolStrip, be glad.) They had to give ToolStrip to their junior devs, because all their experienced devs were already busy working on WPF.

With WinRT, it’s pretty clear that all their junior people were working on error handling. The number of things that fail with absolutely meaningless errors (e.g. “A COM error occurred”) is staggering. Makes me wonder what they’ve got the senior devs busy on, if it’s not WinRT.

</rant>

Anyway, it turns out the problem is a codegen bug if your assembly has a dot in its name. There’s a simple workaround: go into Project Properties > Application tab > Assembly name, and change it to something with no dots in it. (I’ll probably also rename the .csproj and the folder to match, but that’s not necessary.)

The knowledgebase article says this is a problem with XAML-based controls, but I haven’t seen a problem with our WPF4 code at work. So either it’s only WinRT (rather than all XAML as the KB article suggests), or it’s only a problem with .NET 4.5.

There’s allegedly a hotfix that will fix the codegen bug properly, but there’s no actual way to download the hotfix. Easiest thing is to rename the assemblies, or wait for the service pack.

System colors in WinRT/XAML

Windows apps have always adapted to the Windows color settings. But over time, Microsoft has made this progressively harder.

In WinForms, you had SystemColors and SystemBrushes, which were well-documented and easy to use. In WPF, you had a new flavor of SystemColors, which were fairly well-documented, but using them required a lengthy incantation involving DynamicResource. In HTML Metro (WinJS), you can expand out the references in Solution Explorer and read the theme CSS files, which is less discoverable than anything before, but is still a little like documentation.

But in XAML Metro (WinRT/XAML), the system colors are buried in theme resources that you can’t even see. If you want to use one of the system colors, you can find them in the visual designer’s Properties page, but you can’t find them in the documentation. This bugs me, since I’m a coder and tend not to bother much with the designer.

So I went ahead and wrote the documentation myself. I now have a metro.excastle.com subdomain, which contains documentation for the system brush resources in WinRT/XAML. I even show color swatches for both the Dark and Light themes. (I recommend you use a modern browser that understands CSS alpha transparency.)

(BTW, if anyone can suggest a better algorithm for deciding whether a semi-transparent color’s RGB code should be shown in black or white for best contrast, I’m all ears. I admit I didn’t spend a lot of time on that part.)

If you have suggestions for other content or links I could add to metro.excastle.com, leave a comment here or drop me a line.

Contributing to open source: uhttpsharp

I’ve been using open-source since at least my senior honors project in college, 15 years ago. I’m well overdue to give something back.*

Last night I made my very first commit to an open-source project: uhttpsharp, “a very lightweight & simple embedded http server for c#”. And I’ve added quite a bit of stuff in the day since that first commit — file serving, customizable index and error pages, keep-alive support. I’m thinking about adding NuGet support at some point.

If you need a simple HTTP server for .NET, and you don’t want to use HttpListener (e.g. because you don’t want to require admin permissions to register the URI prefix), go check it out.

* Actually, I’ve done plenty of open-source work before, if you count stuff that I wrote myself. And some of that stuff does count; I think a few people have found DGrok helpful. But I have a strong tendency toward not-invented-here syndrome… and this time I offered to contribute to an existing open-source project, that I heard about through posts on StackOverflow. So it’s not just me writing something by myself, which is cool.

Well, okay, I’m contributing to this project so I can use it in another project that I am writing by myself…