Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, 10 February 2014

Getting Started with SignalR - and not a Chat room in sight!

You might have heard of SignalR, a real-time communications library for the web from Microsoft. It’s open source, it’s hip (it supports WebSockets!) – and just about all the Getting Started tutorials are about Chat applications. How many times have you had to write a Chat application in your career? I’d bet a two-toed sloth could keep count for you on one foot and still have digits to spare.

I want to show you how SignalR can solve elegantly a problem you will almost certainly have faced at some point: reporting progress of long-running operations on web pages. I say you’ve probably faced the problem – and if you’re anything like me, you’ve probably ducked out of solving it too, leaving your web site visitors in the tender care of a wait cursor while your web application does its thing in its own sweet time. Getting a server to report back to a web page has always been a fiddle, and many of the techniques in common use feel like hacks. SignalR changes all of that.

Read my three-part guest series on the Safari Books Online blog:

Thursday, 30 May 2013

How to debug silent crashes in .Net

Here’s a quick note to my future self, and any other interested parties in the present on how to diagnose a particularly tricky kind of unhandled exception. I’m talking about those ninja exceptions which manage to evade any kind of unhandled exception logging you’ve rigged up around your .Net applications.

I was debugging just such a problem today. A customer would double click the application, and nothing would happen. Our application is configured to log any unhandled exceptions to a log file. But no log file was being created. There was, however, an entry written to the application event log: it told me that a TypeInitializationException had been thrown, and even gave me a stack trace. But it told me nothing about why the type had failed to initialize.

To complicate matters, this was one of those heisenbugs where, though I could replicate it under normal circumstances, it would go away if I attached a debugger to the process. What I needed was a crash dump – a snapshot of the entire state of the application at the moment the exception happened.

DebugDiag was my first port of call. That’s a nifty tool from Microsoft which can be configured to create dumps from your application under particular circumstances,  including when it crashes. Handily, it will also analyse the dump file, and help you work out why the application crashed. Inexplicably, DebugDiag failed to capture any dumps for my application.

So I turned to Windows Error Reporting. From Windows Vista SP1 onwards you can tweak some flags in the registry, and have windows automatically capture dumps for you – assuming you’re using .Net 4.0.

Capturing dump files with Windows Error Reporting

All you need to do is set create a key at HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Windows Error Reporting\LocalDumps\[Your Application Exe Name]. In that key, create a string value called DumpFolder, and set it to the folder where you want dumps to be written. Then create a DWORD value called DumpType with a value of 2.

image

Now get those ninjas to crash your app.

You should see a *.dmp file appearing in the folder you chose. Double click it – and you’ll see some Visual Studio magic, introduced in VS 2010. You can debug a dump file almost as if it were a live application. When you see the Minidump File Summary screen, you just need to click Debug with Mixed.

image

Unmasking the ninja

So what was this ninja exception that was evading my logging routines? It was an exception being thrown by my exception handling code!

The original exception was a ConfigurationErrorsException, thrown by the configuration API when loading my application’s user settings from a corrupt user.config file. My exception handling code looked like this:

private void ReportUnhandledException(Exception exception)
{
    try
    {
        Tracing.TraceUnhandledError(exception);

        ReportExceptionToUser(exception);
    }
    catch (Exception fatalException)
    {
        Tracing.TraceUnhandledError(fatalException);
    }
}

The problem was caused by a static constructor in the Tracing class. We’re using the System.Diagnostics TraceSource api to log our exceptions, and the constructor was setting all of that up. The TraceSource API, it turns out, also tries to load the application configuration, so that was throwing an exception.

The solution? Use Environment.FailFast instead of trying to log the secondary exception. That simply writes a message to the event log then bails out, with no chance of causing mayhem by raising further exceptions.

private void ReportUnhandledException(Exception exception)
{
    try
    {
        Tracing.TraceUnhandledError(exception);

        ReportExceptionToUser(exception);
    }
    catch (Exception fatalException)
    {
        Environment.FailFast("An error occured whilst reporting an error.", exception);
    }
}

Monday, 4 March 2013

Bootstrap a Startup in a Week: Day 1

Hurricane Rob (aka Rob Ashton) is the mildest-mannered whirlwind one could ever hope to meet, and he passed through my office today leaving in his wake a wonderful trail of construction. It was Day 1 of my “Build a Startup in a Week” challenge, and Rob arrived at my house (we’re working from my garden office) bright and early, eager to re-caffinate. Whilst he patched up his scarcely-used Windows laptop with Asp.Net MVC 4 (am I the only Windows developer still actually using a PC and not a Macbook Air?) we talked tactics.

There are three major components for my sermon sharing service that I want to get built this week. One is the administration website, where churches will upload and manage sermons. Second is the public-facing website which will embed sermon listings in churches websites. And third is “The Studio” – a super-easy-to-use desktop application for recording, editing and uploading sermons.

Since Rob’s strength lies in web development and my expertise is centred on desktop applications, a natural division of labour emerged. So whilst Rob got started on the web stuff, I cracked open Visual Studio and created a fresh WPF project.

Some of the ground work for our weeks work, I laid last week.

Ground Work

After much toing and froing I’ve settled on Amazon to host the services, and in particular, Amazon EC2 for the servers. I considered AppHarbour, and Azure Websites, with their promises of painless deployments, but in the end I decided I’d trade off a little extra work on deployment in return for complete control of the stack.

Wherever you turn, Amazon seem to have you covered. The TruthVine landing page is currently hosted as a static website on Amazon S3, and we’ll be using S3 for sermon storage too. The truthvine.com domain is pointed at Amazon’s Route 53 DNS service. We’ll be using SES for sending notification emails. If only Amazon Flexible Payments service worked in the UK, I’d be use that in a shot.

For hosting our source code and managing issues, I’ve settled on BitBucket, with a Git repo. Whilst I prefer Mercurial from an ease-of-use perspective, and would have loved to use Fogcreek’s Kiln, it seems Git has become the lingua franca for DVCS, particularly after Microsoft announced they were adopting it for TFS. Why BitBucket rather than GitHub? Because I think their pricing model makes more sense. GitHub charges per repository, whereas BitBucket charge per user. I can see our repository count growing over time, whereas the number of developers I’m likely to involve in my projects is going to remain small.

The last thing to get sorted before Rob’s arrival was a UI theme for Admin pages. We’re going to be using Twitter Bootstrap to make the UI a little easier to develop. I found a wonderful site called WrapBootstrap which sells themes built on Twitter Bootstrap, all for very reasonable prices. From that, I’ve picked the Optimus Dashboard theme, which not only looks the part, but is responsive, so it resizes to accommodate tablets and smartphones.

Progress Report

So how did we get on today?

Rob made a sterling effort. Starting with some code I’d written for our church website (which he seemed to like) he got a good chunk of the admin website done today – login, sermon management, and series management.

My efforts were a bit more lacklustre. They amounted to this:

TruthVine Studio

I did make a few useful discoveries though. A while back, I found the NAudio library, which does a lot of the grunt work when working with Audio in .Net. Today I discovered that they’ve added code to handle AAC encoding using the encoder built into Windows as of Windows 7. I was thinking I’d need to spend a day or translating C++ samples into C# interop to get that working.

All in all, a profitable day. Hopefully a sign of a good week to come.

Friday, 28 September 2012

A quick guide to Registration-Free COM in .Net–and how to Unit Test it

A couple of times recently I’ve needed to set up a .Net application to use Registration-Free COM, and each time I’ve had to hunt around to recall the details. Further, just this week I needed to write some unit tests that involve instantiating these un-registered COM objects, and that wasn’t straight forward. So, as much for the benefit of my future self as for you, my loyal reader, I’m going to summarise my know-how in quick blog post before it becomes used-to-know-how.

What is Registration-Free COM?

If you’re still reading, I’ll assume you know all about COM, Microsoft’s ancient technology for enabling components written in different languages to talk to each other (I wrote a little about it here, with some links to introductory articles). You are probably also aware of DLL Hell. That isn’t a place where bad executables are sent when they are terminated. Rather, it was a pain inflicted on developers by the necessity of registering COM components (and other DLLs) in a central place in the OS. Since all components were dumped into the same pool, one application could cause all kinds of hell for others by registering different versions of shared DLLs. The OS doesn’t police this pool, and it certainly doesn’t enforce compatibility, so much unexpected weird and wonderful behaviour was the result.

Starting with Windows XP, it has been possible to more-or-less escape this hell by not registering components in a central location, and instead using Registration-Free COM. This makes it much easier to deploy applications, because you can just copy a bunch of files – RegSvr32 is not involved, and there are no Registry keys to be written. You can be confident that your application will have no impact on others once installed.

It is all done using manifests.

Individual Manifest Files

For each dll, or ocx file (or ax files in my case – I’m working with DirectShow filters) containing COM components you need to create a manifest.

Suppose your dll is called MyCOMComponent.dll. Your manifest file should be called MyCOMComponent.sxs.manifest, and it should contain the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">

<assemblyIdentity
    type="win32"
    name="MyCOMComponent.sxs"
    version="1.0.0.0" />

<file name="MyCOMComponent.dll">
    <comClass
        description="MyCOMComponent"
        clsid="{AB12C3D4-567D-4156-802B-40A1387ADE61}"
        threadingModel="Both" />
</file>
</assembly>

Obviously you need to make sure that the clsid inside comClass is correct for your component. If you have more than one COM object in your dll you can add multiple comClass elements. For those not wanting to generate these manifests by hand, a StackOverflow answer lists some tools that might help.

About Deployment

When you deploy your application you should deploy both the dll/ocx/ax file and its manifest into the same directory as your .Net exe/dlls. When developing in Visual Studio, I customise the build process to make sure all these dlls get copied into the correct place for running and debugging the application. I stole the technique for doing this from the way ASP.Net MVC applications manage their dlls.

Put all the dlls and manifests into a folder called _bin_deployableAssemblies alongside the rest of your source code. Then modify your csproj file and add the following Target at the end of it:

<!--
  ============================================================
  CopyBinDeployableAssemblies

  This target copies the contents of ProjectDir\_bin_deployableAssemblies to the bin
  folder, preserving the relative paths
  ============================================================
  -->
<Target Name="CopyBinDeployableAssemblies" Condition="Exists('$(MSBuildProjectDirectory)\_bin_deployableAssemblies')">
  <CreateItem Include="$(MSBuildProjectDirectory)\_bin_deployableAssemblies\**\*.*" Condition="Exists('$(MSBuildProjectDirectory)\_bin_deployableAssemblies')">
    <Output ItemName="_binDeployableAssemblies" TaskParameter="Include" />
  </CreateItem>
  <Copy SourceFiles="@(_binDeployableAssemblies)" DestinationFolder="$(OutDir)\%(RecursiveDir)" SkipUnchangedFiles="true" Retries="$(CopyRetryCount)" RetryDelayMilliseconds="$(CopyRetryDelayMilliseconds)" />
</Target>

To make sure that target is called when you build, update the AfterBuild target (uncomment it first if you’re not currently using it):

 <Target Name="AfterBuild" DependsOnTargets="MyOtherTarget;CopyBinDeployableAssemblies" />

The Application Manifest

Now you need to make sure your application declares its dependencies.

First add an app.manifest file to your project, if you haven’t already got one. To do this in Visual Studio, right click the project, select Add –> New Item … and then choose Application Manifest File. Having added the manifest, you need to ensure it is compiled into your executable. You do this by right-clicking the project, choosing Properties, then going to the Application tab. In the resources section you’ll see a Manifest textbox: make sure your app.manifest file is selected.

image

Now you need to add a section to the app.manifest file for each dependency.

By default your app.manifest file will probably already have a dependency for the Windows Common Controls. After that (so, nested directly inside the root element) you should add the following for each of the manifest files you created earlier:

<dependency>
  <dependentAssembly>
    <assemblyIdentity
        type="win32"
        name="MyCOMComponent.sxs"
        version="1.0.0.0" />
  </dependentAssembly>
</dependency>

Notice that we drop the “.manifest” off the end of the manifest file name when we refer to it here. The other important thing is that the version number here and the one in the manifest file should exactly match, though I don’t think there’s any reason to change it from 1.0.0.0.

Disabling the Visual Studio Hosting Process

There’s just one more thing to do before you try running your application, and that is to turn off the Visual Studio hosting process. The hosting process apparently helps improve debugging performance, amongst other things (though I’ve not noticed greatly decreased performance with it disabled). The problem is that, when enabled, application executables are not loaded directly- rather, they are loaded by an intermediary executable with a name ending .vshost.exe. The upshot is that the manifest embedded in your exe is ignored, and COM components are not loaded.

Disabling the hosting process is simple:  go to the Debug tab of your project’s Properties and uncheck “Enable the Visual Studio hosting process

image

With everything set up, you’ll want to try running your application. If you got everything right first time, everything will go smoothly. If not you might see an error like this:

image

If you do, check Windows’ Application event log for errors coming from SideBySide. These are usually pretty helpful in telling you which part of your configuration has a problem.

Summary

To re-cap briefly, here are the steps to enabling Registration-Free COM for you application:

  1. Create a manifest file for each COM dll
  2. Make sure both COM dlls and manifest files are deployed alongside your main executable
  3. Add a manifest file to your executable which references each individual manifest file
  4. Make sure you turn off the Visual Studio hosting process before debugging

Unit Testing and Registration-Free COM

And now, as promised, a word about running Unit Tests when Registration-Free COM is involved.

If you have a Unit Test which tries to create a Registration-Free COM object you’ll probably get an exception like

Retrieving the COM class factory for component with CLSID {1C123B56-3774-4EE4-A482-512B3AB7CABB} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

If you don’t get this error, it’s probably because the component is still registered centrally on your machine. Running regsvr32 /u [Path_to_your_dll] will unregister it.

Why do Unit Tests fail, when the application works? It is for the same reason that the Visual Studio hosting process breaks Registration-Free COM: your unit tests are actually being run in a different process (for example, the Resharper.TaskRunner), and the manifest file which you so carefully crafted for your exe is being ignored. Only the manifest on the entry executable is taken into account, and since that’s a generic unit test runner it says nothing about your COM dependencies.

But there’s a workaround. Win32 has some APIs –the Activation Context APIs- which allow you to manually load up a manifest for each thread which needs to create COM components. Spike McLarty has written some code to make these easy to use from .Net, and I’ll show you a technique to incorporate this into your code so that it works correctly whether called from unit tests or not.

Here’s Spike’s code, with a few minor modifications of my own:

/// <remarks>
/// Code from http://www.atalasoft.com/blogs/spikemclarty/february-2012/dynamically-testing-an-activex-control-from-c-and
/// </remarks>
class ActivationContext
{
    static public void UsingManifestDo(string manifest, Action action)
    {
        UnsafeNativeMethods.ACTCTX context = new UnsafeNativeMethods.ACTCTX();
        context.cbSize = Marshal.SizeOf(typeof(UnsafeNativeMethods.ACTCTX));
        if (context.cbSize != 0x20)
        {
            throw new Exception("ACTCTX.cbSize is wrong");
        }
        context.lpSource = manifest;

        IntPtr hActCtx = UnsafeNativeMethods.CreateActCtx(ref context);
        if (hActCtx == (IntPtr)(-1))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
        try // with valid hActCtx
        {
            IntPtr cookie = IntPtr.Zero;
            if (!UnsafeNativeMethods.ActivateActCtx(hActCtx, out cookie))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            try // with activated context
            {
                action();
            }
            finally
            {
                UnsafeNativeMethods.DeactivateActCtx(0, cookie);
            }
        }
        finally
        {
            UnsafeNativeMethods.ReleaseActCtx(hActCtx);
        }
    }

    [SuppressUnmanagedCodeSecurity]
    internal static class UnsafeNativeMethods
    {
        // Activation Context API Functions
        [DllImport("Kernel32.dll", SetLastError = true, EntryPoint = "CreateActCtxW")]
        internal extern static IntPtr CreateActCtx(ref ACTCTX actctx);

        [DllImport("Kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool ActivateActCtx(IntPtr hActCtx, out IntPtr lpCookie);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DeactivateActCtx(int dwFlags, IntPtr lpCookie);

        [DllImport("Kernel32.dll", SetLastError = true)]
        internal static extern void ReleaseActCtx(IntPtr hActCtx);

        // Activation context structure
        [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Unicode)]
        internal struct ACTCTX
        {
            public Int32 cbSize;
            public UInt32 dwFlags;
            public string lpSource;
            public UInt16 wProcessorArchitecture;
            public UInt16 wLangId;
            public string lpAssemblyDirectory;
            public string lpResourceName;
            public string lpApplicationName;
            public IntPtr hModule;
        }

    }
}

The method UsingManifestDo allows you to run any code of your choosing with an Activation Context loaded from a manifest file. Clearly we only need to invoke this when our code is being called from a Unit Test. But how do we structure code elegantly so that it uses the activation context when necessary, but not otherwise? Here’s my solution:

public static class COMFactory
{
   private static Func<Func<object>, object> _creationWrapper = function => function();

   public static T CreateComObject<T>() where T:new()
   {
       var instance = (T)_creationWrapper(() => new T());
       return instance;
   }

   public static object CreateComObject(Guid guid)
   {
       Type type = Type.GetTypeFromCLSID(guid);
       var instance = _creationWrapper(() => Activator.CreateInstance(type));

       return instance;
   }

   public static void UseManifestForCreation(string manifest)
   {
       _creationWrapper = function =>
           {
               object result = null;
               ActivationContext.UsingManifestDo(manifest, () => result = function());
               return result;
           };
   }
}

Whenever I need to create a COM Object in my production code, I do it by calling COMFactory.CreateCOMObject. By default this will create the COM objects directly, relying on the manifest which is embedded in the executable.

But in my Test project, before running any tests I call COMFactory.UseManifestForCreation and pass in the path to the manifest file. This ensures that the manifest gets loaded up before we try to create any COM objects in the tests.

To avoid duplicating the manifest file, I share the same file between my Test project and main executable project. You can do this right clicking your test project, choosing Add->Existing Item… then app.manifest in your main project. Finally, click the down arrow on the Add split button, and choose Add as Link.

If you’ve got any tips to share on using Registration-Free COM, whether in Unit Tests or just in applications, please do leave a comment.

Tuesday, 14 August 2012

Data virtualization in Silverlight

When I first went freelance (15 months ago – how time has rocketed by!) I promised myself that, with the reigns of my schedule tightly held in my own fist, I would dedicate more time to blogging. Well! You can all see from my blog archives how that turned out. I have discovered that when you have clients willing to pay for as much time as you can give them, there’s a strange temptation to give them as much time as you’ve got!

However.

Just before I went on vacation last week, I found made the time to write a mini-blizzard of blog posts, though not for Functional Fun. Ayende, my client for the last few months, has published them on his company’s blog. In the first batch, I wrote about some exciting new features I’ve coded up for the user interface of RavenDb, Hibernating Rhino’s Document Database server.

But I think you’ll most enjoy a couple of posts I wrote about data virtualization in Silverlight. The problem is a common one. How do you display huge lists of data items in a client application without pulling data unnecessarily from the server? Often applications fall back on paging – show one page of data, and make the user click a Next button when they want to see more. But in terms of usability, this technique feels pretty neolithic. So I figured out a way of using ListBoxes and DataGrids without needing to load all the data up front, but with properly proportioned scrollbars, slurping data from the server just in time as the user scrolls.

Over on Hibernating Rhino’s blog you’ll find the two posts I wrote about this:

There’s also a bonus post on how I created a VirtualizingWrapPanel for Silverlight – built so that we could display data in a card view rather than a list view.

And best of all, I published a sample application on GitHub with all the code you need to use this technique in your own applications. For those WPF-aficionados amongst you, you should find that the code translates without much difficulty.

Monday, 19 March 2012

Weak Events in .Net, the easy way

I’ve written before about one kind of memory leak the .Net Garbage Collector cannot protect against: those caused by event handlers keeping objects alive beyond their best-before date. Daniel Grunwald has a very comprehensive article on CodeProject explaining the problem in depth, and giving a number of solutions, some of which I’ve used in the past.

Nowadays, my preferred solution is one made possible by the fabulous Reactive Extensions (Rx) framework.

Suppose, as one example, you want to subscribe to a CollectionChanged event, but don’t want your object to be kept alive by that subscription. You can just do:

collection.ObserveCollectionChanged()
          .SubscribeWeakly(this, (target, eventArgs) => target.HandleEvent(eventArgs));

private void HandleEvent(NotifyCollectionChangedEventArgs item)
{
    Console.WriteLine("Event received by Weak subscription");
}

How it works

Like all remedies for un-dying object problems, the active ingredient in this one is the WeakReference class. It works like this

public static class IObservableExtensions
{
    public static IDisposable SubscribeWeakly<T, TTarget>(this IObservable<T> observable, TTarget target, Action<TTarget, T> onNext) where TTarget : class 
    {
        var reference = new WeakReference(target);

        if (onNext.Target != null)
        {
            throw new ArgumentException("onNext must refer to a static method, or else the subscription will still hold a strong reference to target");
        }

        IDisposable subscription = null;
        subscription = observable.Subscribe(item =>
                                                    {
                                                        var currentTarget = reference.Target as TTarget;
                                                        if (currentTarget != null)
                                                        {
                                                            onNext(currentTarget, item);
                                                        }
                                                        else
                                                        {
                                                            subscription.Dispose();
                                                        }
                                                    });

        return subscription;
    }
}

You can see that we hold the intended recipient of the notifications, target, as a WeakReference, so that if the Garbage Collector wants to sweep it up, this subscription won’t stand in its way. Then we subscribe a lambda function of our own to the observable. When we receive a notification from the observable, we check that target is still alive, and then pass along the message. If we discover that target has died, we mourn briefly, then cancel the subscription.

Notice though, that all our clever use of WeakReferences could be subverted if the onNext delegate refers to an instance method on the target. That delegate would then be smuggling in the implicit this pointer as a strong reference to the target. onNext is itself held strongly by the closure that is created for the lambda function, so the net effect would be that the target is kept alive by the subscription.

All of which explains why we do a check to ensure that onNext.Target is null, hence, that onNext is referring to a static method.

To be clear, this doesn’t mean that you can only handle events using static methods. It just means that when you call SubscribeWeakly, the lambda function you supply as onNext must call instance methods via the reference to the target it is given as a parameter (like I showed in the example above) rather than capturing an implicit this reference.

Observing .Net events using Rx

If you’re going to start using this, you’ll need to know how to turn .Net events into IObservables. Fortunately, the Rx framework includes a magic wand in the shape of Observable.FromEventPattern.

Working with events that have been coded-up post-generics, and thus use EventHandler<TEventArgs> delegates, is easiest. Here’s how you would observe the TaskScheduler.UnobservedTaskException event, for example:

Observable.FromEventPattern<UnobservedTaskExceptionEventArgs>(
                handler => TaskScheduler.UnobservedTaskException += handler,
                handler => TaskScheduler.UnobservedTaskException -= handler);

You simply instruct Rx how to attach and detach the event handler it supplies.

Events defined pre-generics all had to roll their own delegate types, and that makes observing them 1-line-of-code more difficult. Here’s the definition of ObserveCollectionChanged which I used earlier:

public static IObservable<EventPattern<NotifyCollectionChangedEventArgs>> ObserveCollectionChanged(this INotifyCollectionChanged collection)
{
    return Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
        handler => (sender, e) => handler(sender, e),
        handler => collection.CollectionChanged += handler,
        handler => collection.CollectionChanged -= handler);
}

What’s happening here, in the first parameter to FromEventPattern, is that we are adapting an event handler delegate in standard form (i.e EventHandler<NotifyCollectionChangedEventArgs>) given to us by Rx into one appropriate for this specific event. In fact, the compiler is doing all the work, inferring the necessary types of the delegates for us. Then, as before, we show Rx how to hook the adapted handler up to the appropriate event, and how to detach when the subscription is cancelled.

Prove It

To prove this all works as it should, I’ve created a little test:

class Program
{
    static void Main(string[] args)
    {
        var collection = new ObservableCollection<object>();

        var strongSubscriber = new StrongSubscriber();
        strongSubscriber.Subscribe(collection);

        var weakSubscriber = new WeakSubscriber();
        weakSubscriber.Subscribe(collection);

        collection.Add(new object());

        strongSubscriber = null;
        weakSubscriber = null;

        GC.Collect();
        Console.WriteLine("Full collection completed");

        collection.Add(new object());

        Console.Read();
    }

    private class StrongSubscriber
    {
        public void Subscribe(ObservableCollection<object> collection)
        {
            collection.CollectionChanged += delegate { Console.WriteLine("Event Received By Strong Subscription"); };
        }
    }

    private class WeakSubscriber
    {
        public void Subscribe(ObservableCollection<object> collection)
        {
            collection.ObserveCollectionChanged().SubscribeWeakly(this, (target, item) => target.HandleEvent(item));
        }

        private void HandleEvent(EventPattern<NotifyCollectionChangedEventArgs> item)
        {
            Console.WriteLine("Event received by Weak subscription");
        }
    }
}

In the blue corner we have StrongSubscriber who subscribes to an event on a collection the standard way. And in the red corner we have WeakSubscriber who listens to events using SubscribeWeakly. We trigger an event to show that both are paying attention, then we attempt to nuke them, setting their references to null and doing a full garbage collection. Finally, we trigger another event, to see who survived the apocalypse. Here’s the result:

image

As expected, the StrongSubscription clung on to life, whilst the WeakSubscription dutifully died.

Here – take it!

As with all the code on my blog, feel free to take this and use it in your own projects. I’d love to hear how you get on with it.

Saturday, 28 January 2012

Crunch, the RESTful Accountants (And Introducing the Crunch API Explorer)

One of the things that scared me a little when I thought about starting my own business was the thought of the bookkeeping. I know, I know – I have a Maths degree, so I ought to be able to cope with adding up a few numbers then working out the 20% I owe to the tax man. And the 20% I owe to the VAT lady. And how to take just the right amount of salary to avoid giving anything to the PAYE person. But my arithmetic has always been terrible, and the mathematicians who lectured me, strange to say, rarely used actual numbers. It was all xs and ys and βs and πs. So that didn’t help.

CrunchA big factor in persuading me to make the leap into running a company was finding an excellent online accounting service to handle all those troublesome numbers for me. Crunch are a smart bunch of accountants based down in Brighton who have teamed up with an equally smart bunch of developers to create bookkeeping software that is actually quite fun to use (I know – I couldn’t quite believe that when I read it on another freelancer’s blog, but it’s true!). You enter all the numbers in the website as you rake in the profits, or fork out to your suppliers, and at the end of the year, Crunch will put together your accounts and send them off to H.M.R.C. They’ll even submit your VAT returns for you. And handle your payroll, if you should happen to have any minions employees. All for £59.50 a month. It’s great. Sign up here and we’ll both get a £25 Amazon voucher!

And as if all that wasn’t awesome enough, earlier this month they launched an API. It its RESTful, speaking XML, with OAuth authentication. That’s right – a REST API from an accountancy company! I should caution that the first release is limited to dealing with expenses and suppliers, but the dev team plan to add areas according to the priorities indicated by us users.

The Crunch API Explorer

Well, you know me. I couldn’t leave a shiny new toy like that lying on the shelf. So I had a play, and knocked together something that I think you’ll like.

Allow me to introduce the Crunch API Explorer:

image

It’s a little tool to help you poke and prod the Crunch API. You enter a URL, set the appropriate Http Method, hit Go!, and it will show you the XML that Crunch returns.

You can download it here (it installs using ClickOnce, so it will auto-update when I add new features. If you don’t already have .Net 4.0 on your machine, you should be prompted to install it). To connect to Crunch using the Crunch API Explorer, you’ll need your own API key which you can get by contacting the nice folks at api-dev@crunch.co.uk. Then you can make REST calls to your hearts delight. All the documentation you need about the resource URLs and the structure of the XML for submitting updates can be found here on the Crunch website.

Here are a few of my favourite features:

  • XML Syntax colouring when you’re editing requests (this courtesy of AvalonEdit, the open source WPF text editor component that is part of SharpDevelop)
  • Makes you confirm any update/delete requests made to the live server (but not to the test server)
  • All the source is available on GitHub, so if ever you wanted an example of how to connect to an OAuth API with DotNetOAuth, well – now you have one (see CrunchFacade.cs). It’s all in C#, with some WPF, and of course a topping of MVVM.

There are a couple of things I wanted to add, but didn’t get time for – maybe next week:

  • Remembering frequently used resource URIs, and maybe saving template Xml request documents
  • Ability to choose a file and insert it into the XML request documents in Base64 format for the APIs that support file upload
  • Saving Base64 encoded data in the responses to files

Anything else?

I’d love to hear from anyone who finds this useful. Feature requests are welcome (pull requests even more so). And if you fancy forking this and adapting it to explore other APIs, be my guest.

Thursday, 16 June 2011

Resharper 6 XAML Tip: Intellisense for your Databindings

Anybody who has installed the Resharper 6 Beta (and that should be all of you – it’s awesome, and no major problems that I can see) will find in it a feature I’ve been wanting ever since WPF was first released: intellisense for databindings.

Mark up your Xaml so that Resharper knows the type of your DataContext and it will tell you what properties you can bind to, and warn you if it doesn’t recognize what you’ve typed. I’m always switching back and forth between my Views and ViewModels to make sure I get my property names right, so this will be a real time-saver.

There are lots of places where Resharper can already deduce the type of the DataContext – within DataTemplates where you’ve specified a DataType, for example. In other cases, there's just one thing you have to do to enable this awesome feature.

At the root of your file, you need to add the d:DataContext attribute and set it to the type of you Datacontext. Here’s an example:

<UserControl x:Class="MyApp.Views.MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:ViewModels="clr-namespace:MyApp.ViewModels"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance ViewModels:MyViewModel, IsDesignTimeCreatable=False}">

Now if you press Ctrl-Space within a binding element, you’ll get lovely intellisense:

image

Friday, 10 June 2011

XmlSerializerFormat is NOT supported by WCF Rest 4.0 in Medium Trust

Here’s one for you googlers (or bingites): Using the XmlSerializerFormat attribute on methods that you expose over WCF Rest (i.e. services using the webHttpBinding) is not supported if your service is running in Medium Trust (as it most likely is if you’re using Shared Hosting, like Rackspace Cloud Sites).

This is contrary to what you might expect from reading documents like this, which say that XmlSerializer is supported in partial trust. I guess they forgot to test the webHttpBinding scenario. I should be clear: webHttpBinding itself works fine in Medium Trust: it’s using XmlSerializerFormat with webHttpBinding that will give you problems.

That’s the short story.

Here’s the amplified version.

How I learned: the hard way

I’m building a web service that my friends running MacOSX want to be able to use. Out in the Apple orchards they’re not so keen on SOAP as we are who sit behind Windows. So I turned to WCF Web Http, now part of .Net 4.0, which lets you take control of your urls and keep your messages to the bare necessities.

With WCF REST you have the choice of XML or JSON. I chose XML, and by default WCF will use the DataContractSerializer. That produces reasonably clean XML, but it is picky about ordering of elements within messages, it annotates elements with type attributes that are often unnecessary, and it has a rather clunky syntax for serializing arrays.

Then I read about the XmlSerializerFormat attribute. If you apply that to your Operation Contracts, it switches to using the XmlSerializer, and then, by decorating your data contracts with the appropriate attributes, you can take complete control of the xml which gets written to the wire.

All well and good – while the service was running on my machine. But when I pushed the bits to our web host, who run all websites under Medium Trust, it was a different story. All the calls to the service threw a ProtocolException with the helpful message: “(400) Bad Request”.

Turning on includeExceptionDetailInFaults, then spying on the interaction using Fiddler shed more light on the situation. I was getting back a stack trace with this at the top:

at System.ServiceModel.Dispatcher.UnwrappedTypesXmlSerializerManager.BuildSerializers()
   at System.ServiceModel.Dispatcher.UnwrappedTypesXmlSerializerManager.GetOperationSerializers(Object key)
   at System.ServiceModel.Dispatcher.SingleBodyParameterXmlSerializerMessageFormatter.EnsureSerializers()
   at System.ServiceModel.Dispatcher.SingleBodyParameterXmlSerializerMessageFormatter.GetInputSerializers()
   at System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.ReadObject(Message message)
   at System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.DeserializeRequest(Message message, Object[] parameters)

A bit of hunting around using Reflector revealed that the BuildSerializers method always calls XmlSerializer.FromMappings, and if you check that out on MSDN, you’ll see that it requires Full Trust.

So there’s no getting away from it. You can’t use XmlSerializer together with WebHttpBinding under Medium Trust. I did try the usual work-around for getting XmlSerializer to work in Medium Trustpre-generating the serialization assemblies at build time: but that was before Reflector showed me the clinching evidence that my efforts were futile.

So what are your options? Either stick with DataContractSerializer, or switch to JSON1. Or, if time is on your side, wait for the next version of WCF which has a new extensible Web API specially designed to let you take complete control of your message formats and such like.


  1. Decorate your methods like this to switch to JSON format:
[ServiceContract()]
public interface IService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "/MyOperation", 
               Method = "POST",
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json)]
    Response MyOperation(Dto dto);
}

Thursday, 3 March 2011

Unpacking Simon Squared: My mini framework-independent animation library

Animation is the trick a computer uses to make math come alive. Our minds are wired to see movement. A video game where the characters and props jumped instantly between the positions where the math says they ought to be would be incomprehensible and unplayable. Which explains why I spent a good part of the few precious days I had building Simon Squared on developing a little animation framework.

I’m pretty pleased with the result. It’s by no means polished or complete, but it makes it very easy to implement one-off animations, and to schedule groups of animations together. Best of all, it’s not tied to the XNA framework – you could use it to implement animation in Windows Forms if you so desired!

Fluent Animations

Here’s one example:

_storyboard.Plan()
    .AfterDelay(TimeSpan.FromSeconds(0.5))
    .Begin(b => b.Animate(this, (Shape target, float value) => target.RotationY = value)
                 .From(RotationY)
                 .To(RotationY + MathHelper.Pi)
                 .In(TimeSpan.FromSeconds(MovementAnimationTime)));

This shows off several aspects of the framework.

First, the Storyboard class. This is responsible for keeping track of all the animations that are currently in flight, or scheduled for later on. In my Game’s Update method I call

_storyboard.AdvanceTimeTo(gameTime.TotalGameTime);
and that takes care of updating all the animations that are in progress. 

The Plan() method returns a StoryboardPlanner which is used to schedule animations using a fluent interface. No prizes for guessing what AfterDelay does: it leaves a gap of what ever duration you specify before starting subsequent animations. These animations are scheduled using the Begin method: you pass it a function which uses the AnimationFactory it supplies to fabricate animations to your exact specifications.

Most important of all is the Animate method. In the definition of the Animate is the secret sauce that makes this animation framework independent of whatever framework it is you’re trying to animate. It works like this:

  1. you set up an animation, RotationY goes from Pi to Pi/2 in 2 seconds, for example;
  2. the animation framework calculates values as the animation progresses;
  3. every time it calculates a new value, it calls the lambda function that you’ve provided, so that you can update the appropriate object with the new value.

The first parameter I’m passing to Animate is the object that has the property I want to animation, RotationY. Then I pass in a lambda function that receives both the target object, and the value that should be assigned to the target property or field1.

How the animations work

When it comes to the actual animations, I’ve abstracted the majority of the animation logic into a couple of base classes, which makes it very easy to add animations for different types.

Here are the critical parts of the Animation base class:

public abstract class Animation
{
    // snip

    public void UpdateForTime(TimeSpan currentElapsedTime)
    {
        var normalisedTime = GetNormalisedTimeInAnimation(currentElapsedTime);
        if (normalisedTime.HasValue)
        {
            SetValueForTime(normalisedTime.Value);
        }
    }

    protected abstract void SetValueForTime(double normalisedTime);

    protected double? GetNormalisedTimeInAnimation(TimeSpan currentElapsedTime)
    {
        var normalisedPosition = 0.0;

        var millisecondsAfterStart = currentElapsedTime.TotalMilliseconds - StartTime.TotalMilliseconds;
        if (millisecondsAfterStart < 0)
        {
            return null;
        } 
        else if (millisecondsAfterStart > Duration.TotalMilliseconds && RepeatMode == RepeatMode.None)
        {
            return 1;
        }
        else
        {
            var quotient = millisecondsAfterStart / Duration.TotalMilliseconds;
            var integerPart = Math.Floor(quotient);

            normalisedPosition = quotient - integerPart;

            if (AutoReverse && (integerPart % 2) == 1)
            {
                normalisedPosition = 1 - normalisedPosition;
            }
        }

        return normalisedPosition;
    }
}

Start at the top: UpdateForTime is called by the Storyboard on every frame, to inform the animation of the time, and to give it an opportunity to update its target.

The first thing Animation does then is to work out the normalised time – that is a value between 0 and 1 indicating the progress through the animation. If the clock says that we’re bang on the animation’s start time then we return 0; halfway through (however long the animation lasts), and the normalised time is 0.5; and a clock time of StartTime + Duration gets a normalised time of 1. All this is calculated by GetNormalisedTimeInAnimation. Notice from the code how it is also smart enough to handle animations that repeat over and over, and animations that cycle -  repeating, but reversing when they get to the end value.

Once the normalised value has been calculated it is passed to SetValueForTime which is an abstract method on the Animation base class.

Next level down in the hierarchy we have SetterInvokingAnimation: 

public abstract class SetterInvokingAnimation<TValue, TTarget> : Animation where TTarget : class 
{
    public TValue StartValue { get; set; }

    public TValue EndValue { get; set; }

    private WeakReference _target;
    private readonly Action<TTarget, TValue> _setter;

    public SetterInvokingAnimation(TTarget target, Action<TTarget, TValue> setter)
    {
        _setter = setter;
        _target = new WeakReference(target);
    }

    protected override void SetValueForTime(double normalisedTime)
    {
        var value = GetValueForNormalisedTime(normalisedTime);
        var target = _target.Target as TTarget;
        if (target != null)
        {
            _setter(target, value);
        }
    }

    protected abstract TValue GetValueForNormalisedTime(double normalisedTime);
}

This is the class that takes care of pushing calculated values to the target - though it doesn't actually calculate any values itself – it leaves that to derived classes, by way of the GetValueForNormalisedTime abstract method.

And here is one of those derived class, FloatAnimation. Since it is descended from some hard-working ancestors, there’s little it has to do – just a simple mathematical interpolation between the StartValue and EndValue of the animation:

public class FloatAnimation<TTarget> : SetterInvokingAnimation<float,TTarget> where TTarget : class 
{
    public FloatAnimation(TTarget target, Action<TTarget, float> propertySetter) : base(target, propertySetter)
    {
    }

    protected override float GetValueForNormalisedTime(double normalisedTime)
    {
        var delta = EndValue - StartValue;
        var value = StartValue + delta * normalisedTime;

        return (float)value;
    }
}

So there you have it: a whistle-stop tour of my mini-animation framework.

See it for yourself

You can see the full source code - in use - in my Simon Squared game up on Codeplex. And if you shout loud enough, I might pull it out of there and stick it in a NuGet for easy consumption in your own games.

Go check it out – and then make sure you tell Red Gate how much you love it, over on my Simon Squared competition entry page!


  1. I could have defined Animate like this:

    Animate(value => this.RotationY = value);
    which would have looked a lot neater. But that has the downside of capturing a reference to my target object in a closure and smuggling it down into the animations which are held by the Storyboard; and since my Storyboard is longer-lived than many of the objects that I’m animating, this would have had the effect of keeping my target objects alive when they would otherwise have been Garbage Collection. So I pass in the target object separately so that I can hold it using a WeakReference, and then I use a lambda function that is, in effect, a static method.

    Another way, of course, would be to remove animations from the Storyboard explicitly (and it does support that). But I'm lazy, and it's much easier to use this fire-and-forget approach!

Tuesday, 1 March 2011

Want to see inside a Windows Phone 7 game? I’ve opened-sourced Simon Squared

SSquaredEntryShotThe deed is done: I’ve thrown my hat into the ring. Simon Squared is now officially standing for election as the App developers will love most. Go and vote for it here.

Why does it deserve your vote? Because, not only is it a thoroughly addictive little puzzle game, with a multi-phone-multi-player mode that will have you coming back for more, but I’ve just released the source code! It’s all there on CodePlex, released under the GPL v2 license. Build it, try it out, and let me know what you think.

Over the next little while I’m intending to publish some posts highlighting the points of interest in the source code. In the meantime:

If you visit my blog, you’ll find a new page dedicated to Simon Squared. I’ll be updating that as I blog about the source code; and I’ve also indexed all the posts I made during development – bookmark it, because I’m sure you’ll want to go back and re-live those hectic days!

It only remains for me to thank everyone who has spurred me on over the last few months with comments, tweets and links, and to remind you all to go and exercise your democratic right.

Friday, 25 February 2011

Simon Squared – We have Multi-player: Days 4, 5 and (ahem!) 6

OK. So you let me have one more day, and I took 3. But I got it working. After 6 days of work, I can show you Simon Squared in all its Windows Azure powered multi-player glory:

Simon Squared Multi-player, nicely showcasing my Multiple-instances-of-the-WP7-emulator hack

So what took me so long? Surely after getting the Windows Phone 7 emulator to talk to the Windows Azure emulator, finding a UI library for XNA and enabling multiple instances of the WP7 emulator to run at once, everything else should have been easy? If only!

Here’s what happened.

Day 4

9:00 Start by setting up a Windows Azure subscription, making use of my MSDN subscription benefits: it's pretty generous: 750 hours/month of Compute Time, 10 GB storage, 7/14 GB traffic in/out.

I get a little worried when the sign up screen tells me that I'll receive an activation email "within 24 hours" - but I'm relieved to see that within a couple of minutes of being redirected to the Azure management console (very swish Silverlight app) my subscription appears, and I can start creating deployments.

10:11 Got side-tracked into a discussion with my boss about possibilities for future products and offerings based on the work we've been doing here

12:45 Implemented the phone side behaviour for running the count down to the games beginning. Making heavy use of the Reactive Framework (which comes built into WP7) for hiding away the messiness of asynchronous calls.

13:45 Problem with WCF REST: if I return a derived type of message from my operation, the client only receives the properties defined on the base type. This is the problem that the KnownType attribute solves elsewhere in WCF, but it doesn’t seem to be working for WCF REST.

15:22 Discovered that WCF REST uses XmlSerializer by default rather than DataContractSerializer - so KnownTypes woudn't work. Also discovered that RestSharp is using XmlSerializer when sending data to the server, so not serializing inherited types in the way that DCS is expecting.

15:39 Now got inherited message types passing correctly: WCF Rest and RestSharp are both pretty pluggable, so I was able to implement a custom ISerializer in RestSharp, and a custom MediaTypeProcessor in WCF Rest, both using DataContractSerializer instead of XmlSerializer

17:30 Caught out by Http response caching. The symptom was that I’d launch a fresh HttpWebRequest,  but get back stale data. Investigation showed that the requests weren’t ever leaving the phone – it never showed up in Fiddler. I spent ages prodding my Reactive Framework query, convinced that it wasn’t issuing the requests properly. Then I remembered Http Caching. In my haste, and newbie-ness, I solved the problem by putting a NoCache on all the responses on the server side. A better way would probably have been to set the WebRequest.CachePolicy.

Day 5

09:00 Thought occurs to me that I might get on faster if I don't have to keep waiting for the Azure Emulator to start up and shut down every time I build my server. Why not just run my server project directly in IIS? I try it – and WCF Http stops working. I eventually discover that the CTP bits I’m using don’t yet support HTTPS, and I had a HTTPs binding configured on my default Website in IIS.

10:30 Fortunately Cassini works - why did it take me an hour and half to discover that!

10:43 Start work on refactoring puzzle generation, so I can do it on the server side. The goal is that the server will generate rounds of 5 puzzles, and send them out to all the players in advance. Within a round, the server will send out a message saying “start puzzle X at Time T” – and thus synchronize the experience of each of the players

12:00 Working on updating the Phone side to play the puzzles that server sends out.

13:16 Finished refactoring the Game screen so that it is backed by a GameController - allowing me to implement a SinglePlayerGameController and MultiPlayerGameController.

17:20 Got some simple state machines working on the client and server. It looks something like this:

image

17:40 With two instances of the emulator running, I can now see the same puzzles displayed on each. The problem is, they’re horribly out of sync – player 1 might get the puzzle two seconds ahead of player 2, which for small puzzles means he’s certain to win!

Day 6

09:21 Implemented Christian’s algorithm to estimate the clock skew between server and phone. The implementation is pretty straight-forward using the Reactive Framework, and quite elegant, if I do say so myself. Remind me to show you, sometime.

10:33 Couldn’t figure out why changes I was making in the code weren’t having any effect when I ran the game. Then discovered that Visual Studio had some how set itself to “Never Build on Run”.

12:00 It’s working! Multiple players now receive the puzzles beautifully in sync, one after another. As soon as one player completes a puzzle, it vanishes from all the other players screens, and the count-down to the next puzzle begins

13:20 Implemented a scoreboard to show the position at the end of each round

14:30 Having deployed the game to my phone, I challenge Vinod to a dual – me on the emulator, him on the phone. I now discover a serious downside to being a games developer: once a game reaches playability, you inevitably get sucked into playing when you should just be testing.

15:35 Use Expression Design 4 to recreate a game logo that Neil designed using Word. What do you think?

SimonSquaredLogo200x200

17:05 Spitting and polishing. Tidying up the various screens. I might not have time to make them pretty, but at least I can make the buttons big enough to touch. That’s the downside of testing with an emulator using a mouse – it doesn’t alert you to the imprecision of fat fingers!

17:30 Waiting for Windows Azure to deploy the server. Visual Studio 2010 is supposed to be able to package and deploy your project straight into the cloud, but I couldn’t get that to work (something about it not being able to resolve the URL of my storage account). Instead, I uploaded the package manually.

17:45 Still waiting for Windows Azure to start up my role instance. Give up and go home.

21:00 Wife gives me permission to interrupt our traditional Thursday evening film (The Prestige last night, – recommended) to see whether the Azure role has started up yet. It hasn’t, so in the time-honoured way I tell it to reboot – and that fixes it. A few minutes later, she’s thrashing me – mainly because she’s using the phone, and I’m using the emulator over Remote Desktop (my laptop is old, and doesn’t support XNA games in the emulator) – in that setup the emulator doesn’t respond to my mouse moves!

What I need is another phone.

Ah, what’s this I see – the Windows Phone Marketplace Developer Newsletter, announcing Windows Phone 7 Handsets for Developers. The Newsletter says that local evangelists have codes for free phones to give away. I think Mike Ormond is the WP7 evangelist for the UK …

Friday, 11 February 2011

Multi-player enabling my Windows Phone 7 game: Day 3 – The Server Side

I’m building a game to enter in Red Gate’s Windows Phone 7 App competition. I built the core of the game in 3 days from a standing start. Now I’ve challenged myself to make the game multi-player in 3 days, using Windows Azure for the server side.  Day 1 was spent getting up to speed with Windows Azure and networking on WP7. On Day 2 I got the UI sketched out. Here’s Day 3:

8:30 Begin the day with excellent news. With barely any badgering at all Red Badger have kindly offered me an non-expiring build of their XPF UI library for XNA. Thanks chaps!

And thanks to everyone who's shown support by tweeting the last couple of blog posts. I can't tell you how motivating it is as I set to work again this morning.

8:45 Microsoft have released the January 2011 Update to the Windows Phone Developer Tools (on the 4th of February mind, but I'll let that pass). This is the one that brings the promised Copy-Paste support and some performance updates. Being the good boy I am, I install it before beginning anything else.

9:32 Staring work on the server. I've never designed anything RESTful before, so I've taken a quick look at a couple of articles: one at quite a high level, and one in a little more detail.  A logical place to begin is starting a game. So what I think I need to do is define a /Game resource on my server, and make it respond to POST requests.

11:45 Hooked up AutoFac on the server so that I can inject dependencies into my REST services.

12:00 A good chunk of the day gone, and I still haven't implemented starting a game. WCF isn't playing nice at the moment: I can't get it to respond to the POST request I'm making to my Service.

12:01 Writing the above fixed the problem! Well, not quite. As soon as I had written that, I thought of fiddling with the UriTemplate on the WebInvoke attribute. Since I was posting a request to the /Games resource, and I had registered my Games service using routes.AddServiceRoute<GamesService>("Games", serviceConfiguration) I thought I could get away without specifying a value for UriTemplate on WebInvoke. Turned out I needed to specify "/"!

12:05 Next: list all available games, so that a player can choose one to join.

12:45 Done! I can now create several games through the Start a Game screen, and see them all listed on the Join a Game screen.

16:15 The afternoon passes in a blur. I’ve added several operations to my service, so that the basic game setup screens are working. This is what I’ve got on the server side:

Resource Http Method Meaning
/Games POST Start a Game
/Games GET List existing games
/Games/{id}/Players POST Join a game
/Games/{id}/Players GET List players belonging to a game

Notice any conspicuous absences? That’s right: there are no operations to support actually playing a game. Where has the time gone? But before I can move on, I should at least check that this service works if multiple devices connect to it.

16:25 Fustrated: the Microsoft Windows Phone 7 emulator is single-instance. How can I test a multi-player game if I can only run one copy of it?! I’ve got to find a way round this.

17:30 Eureka! After a journey deep into the bowels of the Microsoft.SmartDevice.Connectivity API and its associated XML datastore I’ve found a way to have multiple instances of the emulator running at once, and even debug them simultaneously.

Hey! Hang on just a minute: there’s already a post on my blog about that – is someone with a time machine playing around with me here? Smile

But never mind that. My 3 days are up, and all I’ve got to show for it are the game sign-up screens. So where do we go from here? Well, I’m going to make my excuses and plead for an extra day – just one more day, and I’m sure I can get it working!

My excuses:

  • It took me ages to get the Windows Phone 7 emulator talking to the Windows Azure emulator: the good folks at Microsoft haven’t connected the dots here.
  • A good two hours or more of my first day was taken up with the hunt for a working UI library for XNA. Thanks to Red Badger for saving me further frustrating hours.
  • Running multiple instances of the emulator really shouldn’t be that hard.

So what do you think? Can I have another day?

Friday, 4 February 2011

Multiplayer-enabling my Windows Phone 7 game: Day 2–Building a UI with XPF

I’m building a game to enter in Red Gate’s Windows Phone 7 App competition. The first challenge I set myself was to build the core of the game in 3 days from a standing start. Then Red Gate moved the goal posts. So I’ve set myself a new challenge: make the game multi-player in 3 days, using Windows Azure for the server side.  Day 1, was spent getting up to speed with Windows Azure and networking on WP7. Here’s Day 2:

9:00 Decided to take the plunge and go with Red Badger's XPF framework for the UI - what else can I do, if I want to get this thing done in three days? I’m going to need TextBoxes, ListBoxes and the like, and I certainly wouldn’t be able to write them from scratch in the time I have. On Red Badger’s roadmap, there’s no word on a likely release date. I wonder if I can badger them into at least giving me a build that won’t expire before the competition gets judged?

9:43 Got my first "Hello World" screen working using XPF. For ages I couldn't get buttons to respond to clicks, until I noticed from a sample that I needed to supply an InputManager instance to the RootElement.

10:47 Created a TextBox control using XPF. They've done a good job of mimicking the Silverlight API. And in some ways, their DependencyProperty implementation is even better! It uses generics for a start. And the key classes are actually called ReactiveProperty and ReactiveObject because their change notification is based on IObservable from the Rx Framework (which, by the way, comes in the box on WP7). Text input on XNA is pretty limited. Your only option is to call Guide.BeginShowKeyboardInput, which is an async method that takes care of showing the soft keyboard as well as the editor, and then returns to you the text that was entered.

11:40 Refactored my game so it now has Screen classes to represent the states that it can be in - Showing the Game, Showing the Welcome Screen, Showing Help, etc. It’s nice that XNA has the concept of Components and Services built in.

14:21Got a simple dialog working:

clip_image001

14:36 Borrowed the Messenger code from Laurent Bugnion's MVVM Light Toolkit to enable me to pass messages in a loosely coupled way between my screens.

15:06 Seeing strange behaviour in XPF where clicks on a button seem to be handled twice: once by the button, and then by widgets on the following screen (which is made visible by the button click). Realise that this is what comes of changing one screen for another in the middle of handling events. I'm going to have to implement a mini message queue so I can queue the change of screen after the button event has been handled.

15:15 Implemented the message queue, and magically another bug goes away too! That bug was most odd – after I clicked one button, moved to a different screen, then moved back again, all the other buttons would stop working. It turned out that the first button was capturing the mouse events, so the other buttons didn’t get a look in. Making sure that events completed before changing screens obviously fixed the mouse capture problem too.

16:05 Dialogs are coming on nicely now, but it sure is tedious building up a control hierarchy in C#. Oh XAML, how I miss you!

17:21 Got a very basic ListBox working on top of XPF. The time I’ve spent delving around in WPF and Silverlight certainly helps out here!

image

17:30 I think that’s enough of the multi-player UI done for now. That leaves me with one day to implement the multi-player logic, and the server.

Do you think I can do it?

Tuesday, 25 January 2011

A FindResource implementation for Silverlight

Here’s an interesting omission in Silverlight that I stumbled upon today: Silverlight doesn’t provide you with a way to do a hierarchical resource look-up in code.

You can do it in XAML. Write

<Grid>
    <Grid.Resources>
        <Style x:Key="MyStyle>
        </Style>
    </Grid.Resources>
    <DockPanel>
        <Button>
            <TextBlock Style="{StaticResource MyStyle}"/>
        </Button>
    </DockPanel>
</Grid>

and the TextBlock will find the appropriate style in the Grid’s resource dictionary, even though it’s several layers up the hierarchy. And if the resource isn’t found in any of the parent elements, StaticResource will then look in the Application’s Resource Dictionary.

But, whereas WPF provides the TryFindResource method to do the same kind of look-up in code, the best you can do in Silverlight is

element.ResourceDictionary[“MyStyle”]
and that returns null if the resource isn’t in the element’s own ResourceDictionary. 

No matter. It’s easy to a proper lookup yourself:

public static class FrameworkElementExtensions
{
    public static object TryFindResource(this FrameworkElement element, object resourceKey)
    {
        var currentElement = element;

        while (currentElement != null)
        {
            var resource = currentElement.Resources[resourceKey];
            if (resource != null)
            {
                return resource;
            }

            currentElement = currentElement.Parent as FrameworkElement;
        }

        return Application.Current.Resources[resourceKey];
    }
}

With that in place

textBox.TryFindResource("MyStyle");
will do what you expect.

Which of course makes me wonder why this was omitted from Silverlight in the first place. Am I missing something?

Friday, 10 December 2010

Can I build a Windows Phone 7 game in 3 days?

Red Gate Software launched a competition three weeks ago: three prizes of $10,000 to be won for the best Windows Phone 7 application, as judged by panels of developers. Now I’ve always had a hankering to write a game, particularly one involving 3D graphics. Microsoft made me hanker some more when they released the XNA framework a few years back. And, would you believe it, you can use the XNA framework to write 3D games for the Windows Phone 7.

Now it just so happens that I have 3 unplanned days in my schedule between tomorrow morning1 and the competition deadline on December 19th. And my colleague Vinod has had an idea for a memory game with a twist.

Taking stock, what do we have?

So, what do you think? Can I learn the XNA framework, and produce an award winning game in just three days? There’s only one way to find out.

On my marks … Get SetGo!


1. Yes, I am writing this at 1 o’clock in the morning. I couldn’t sleep for excitement. Sad, am I not?

Tuesday, 2 November 2010

C# 5.0 and the sample that made me go “wow!”

In the Visual Studio Async CTP there is one sample project called 101 Asyncs. This is a browser displaying 101 code-snippets involving the new C# 5.0 async functionality. As I was flicking through I found the following sample, which I think speaks volumes for the elegance and simplicity of the feature:

public async void AsyncSwitchToCPU()
{
    Console.WriteLine("On the UI thread.");

    // Switch to a thread pool thread:
    await new SynchronizationContext().SwitchTo();  
                
    Console.WriteLine("Starting CPU-intensive work on background thread...");
    int result = DoCpuIntensiveWork();
    Console.WriteLine("Done with CPU-intensive work!");

    // Switch back to UI thread
    await Application.Current.Dispatcher.SwitchTo();                

    Console.WriteLine("Back on the UI thread.  Result is {0}.", result);
}

public int DoCpuIntensiveWork()
{
    // Simulate some CPU-bound work on the background thread:
    Thread.Sleep(5000);
    return 123;
}