Tuesday, June 29, 2010

Windows 7 Easter Egg

There is a GOD MODE easter egg in Windows 7.  Not quite as cool as it sounds but still very useful.

Create a folder on your desktop and rename it to: GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}

This creates a folder that looks like this:

Opening this you get:

This gives you a window full of shortcuts to all the configuration features in Windows 7.  You can use the search box at the top of the window to quickly find the configuration icon you want! 


Monday, June 28, 2010

Xaml Serialization and Blend Sample Data

For a project I am currently working on, we are using specialised UI Designers and they are using Blend to import, draw and arrange the graphic assets.  One of the coolest features in Blend 4 is the very nice Sample Data features.  Our process involves delivering partially constructed MVVM controllers so the Designers can use Blend to generate random sample data.  This is all well and good, but it still means the application is totally blank when it runs, hence the generated sample data is called "Design-time Sample Data".  However, the sample data is actually a serialised format of instances of objects:

Blend's Design-time Sample Data
Blend offers 3 ways of creating sample data:
  1. From an XML file you have handcrafted yourself. 
  2. From a code class.
  3. Or manually creating it using a designer within Blend. (Not terribly useful in my opinion as the developers generally set the underlying class structure and names).
I have been using the code class option.
This generates a sample data item in the Data tab.
From this we can now be more specific on what kind of data each field is.  For example string fields can use the following templates to generate sample data:
Blend has created an xaml file to store in serialised form the object instances it has created.
Having sample data in the application makes the designer's job much easier as the see the data in the fields. It also means its easier to create custom templates for collection based items.

Xaml Serialised Data
The Xaml markup is actually just a form of XML serialisation. Here's an example of the file format generated by Blend:


        <WpfApplication:FormController State="Active">
                    Company="A. Datum Corporation" 
                    FirstName="Aaberg, Jesper" 
                    MainLine="(111) 555-0100" 
                    Mobile="(111) 555-0100" 
                    Surname="Aaberg, Jesper" />

            Status="Amet dictumst curae donec eleifend" 
            StatusEnum="Online" />

This syntax is significantly better than standard Xml serialisation because the xml type elements are namespaced back to the assembly they are declared in.  Also it follows the same serialisation process as WCF Service contract serialisation in that it serialises all public properties. Standard Xml serialisation only serialises fields and those must be decorated with Xml Attributes! Way too much hassle.  Xaml serialisation is definitely the way of the future.

The Problem
Having design time data is a very tidy solution as it guarantees the design time data doesn't make it into your compiled executable.  The only drawback is that the designers can't run the application to do final visual testing.  One solution to this problem is to use the Xaml Serialisation classes to deserialise the Xaml back into objects and bind to those at runtime.

I feel like I need to come up with a safer more elegant solution so the design time cannot be accidentally left in the executable code, but for now I use a compilation switch #SAMPLEDATA. But hopefully the likelihood of someone releasing the product with the SAMPLEDATA switch intact is low.

public partial class App
        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        public App()
            // Sample data used at runtime.  Sometimes useful for visual testing in addition to design time testing in Blend.
            SampleData.SampleDataRepository.MainWindowController =

        private static T SetUpSampleData<T>(string sampleDataFile) where T : class, new()
            // Using Xaml
            if (File.Exists(sampleDataFile))
                var deserialisedObject = XamlServices.Load(sampleDataFile);
                return deserialisedObject as T;
            return null;

You can see I am using a static class with static properties to store the pre-made sample data controllers ready for use.  The sample controllers replace runtime controllers when the SAMPLEDATA switch is present.  .Net 4 includes a new class designed to simplify Xaml serialisation System.Xaml.XamlServices.

public partial class Sample {
        public Sample() {

            this.DataContext = SampleData.SampleDataRepository.MainWindowController;
Ordinarily when running in "Production" mode the DataContext is set in Xaml (my personal preference), or if it is set in code behind then it would need to be above the #if.

For more complicated scenarios the controllers might need to be interfaced if the are tightly bound to other data sources. This would allow the sample controllers to bypass any data service calls etc.

It doesn't apply to this scenario but it is equally as easy as deserialisation.

string serialised = XamlServices.Save(myObject);
No need to tell it the type or anything else. There are other overloads that take streams and writers and parameters.

For more information:

Saturday, June 26, 2010

WCF: Address Already In Use Exception

If you get this exception:

AddressAlreadyInUseException: Cannot listen on pipe name 'net.pipe://myservice/' because another pipe endpoint is already listening on that name.

Chances are you have one of the following issues:
  1. You have duplicate endpoints with exactly the same address. Double check your app.config endpoint declarations and/or code endpoint declarations.
  2. Ensure all ServiceContracts attributes have been uniquely namespaced.     [ServiceContract(Namespace = "http://services.rees.biz/myservice1")]
  3. Not sure how relevant this is, but I had an instance when this exception was resolved by changing my net.pipe endpoint url to net.pipe://localhost/servicename.  It was something like net.pipe://myservice/servicename.  Seems like a reasonable best-practice to always use localhost anyhow.
  4. Ensure the system tray Visual Studio WCF Host is not present in the system tray. Sometimes this thing can get confused at not restart correctly.
Yes you can have multiple processes all using net.pipe binding as long as they are using unique endpoint urls and unique service contract namespaces.

Hope that helps someone else.

Tuesday, June 22, 2010

Wpf Animations and Mvvm

One of the many topics I have been wanting to look into in more detail lately has been how animations specifically work with MVVM.  It seems to be more complicated than it first appears on the surface.  If the state of a controller (ViewModel) changes then the view follows suit by binding to a state property or at least using a DataTrigger etc.  The View either changes immediately to the new visual state (like show/hiding a panel) or beginning an animation to show or hide something. But what if you wanted to play the animation storyboard and once it finished then allow the state to change?

One of the best MVVM resources I have read recently is Josh Smith's Advanced MVVM mini-book.

In this book he talks about this very topic among many other relevant topics under the heading Advanced MVVM.

You can download his source code for this book here. Its a rather simple but cool game.

Chapter 5 of Josh's book talks about this very topic.  The challenge is to be able to trigger a series of animations each one starting only when the other has completed.  Each transition could take an unknown period of time. I won't steal his book's thunder, just a reference so the an example of a good answer can be found.

If I was to approach this, my simplistic approach simply would be to expose events on the controller for each phase passing through any necessary information as an EventArgs subclass. This isn't as elegant, but would still be suitable.  The challenge is effectively communicating back to the controller the view has completed its animation transition.  This could be achieved one of two ways:
1) Use the completed event on the storyboard to call a method on the controller.
2) Pass a delegate as a event args parameter which is called when on the storyboard complete event is raised.

The real question here is: Is there a better way using Blend4 with visual states? Like most things in life the question to one answer simply leads to at least 2 more questions.  I suspect not, as a visual state cannot help you define dynamic storyboards that change.

Monday, June 7, 2010

I have been doing a lot of talking about WCF lately, and thought it would be useful to have a good working example to show anyone interested.

This example makes use of NamedPipeBinding, of course this can easily be changed to any other kind of binding. The exposed services use both request/response and subscribe/publish using callbacks.  The request/response service uses asynchronous calls.  Unfortunately the NamedPipeBinding does not allow use of the Metadata-Exchange (mexHttpBinding) end-point to allow easy client-side discovery and client proxy code generation. In my example netNamedPipeBinding is the best to use seeing as the service is on the same machine.

For more information around choosing a binding see this great blog post  Here is a chart outlining selection of a binding from Soledad Pano's blog. And here's a handy reference to all different bindings and their matching config element (I always get the casing wrong first time) http://msdn.microsoft.com/en-us/library/ms731092.aspx.

Most developers I know respond best to a good extensive code example better than long drawn out talks with plenty of acronyms thrown in.  This example is a basic to intermediate use of WCF.

Use Instructions:
  1. If you're using Windows 7 be sure to Unblock the zip before extracting the files (yes you can trust me unless... you're on my black list LOL)
  2. Build the code. Then run the ServiceHostConsole project. This will host the services inside a Console application, then we can run the client application. The client application won't run if the services are not hosted and running somewhere.

  3. Once the console window appears and confirms all the end-points are up, you can detach the Visual Studio debugger.
  4. Now we can run the client application - press F5.

    The first panel "Dashboard" retrieves its data from net-pipe://myservice/status using the IStatusService interface.

    The second panel "Form" retrieves its data from net-pipe://myservice/contact using the IContactDataService interface.

    Here's an overall application schematic:

    Follow the code through, I hope you find it informative.

Sunday, June 6, 2010

Windows XP Sp3 Sunset

Microsoft Windows XP Sunset Policy and Lifetime page.

Basically boils down to sunset of mainstream support for XP SP3 in 2011, includes all support and release of Sps. Beyond 2011 Extended support will be available up to 2014, but Extended Support will be available to paying support subscribers only.

Thursday, June 3, 2010

Delay signed assembly problem

If you are using delay signing feature in Visual Studio, to defer the signing of your assemblies. You quickly run into problems trying to reference them during development.  Delay signing is used when the private key is closely guarded and developers do not have access to it.  Only the public key is available to partially sign the assemblies.  The final signing of the assemblies with the matching private key is done usually during the build process.

When you reference a compiled binary that is only partially signed during development (you would not do this outside of a developer environment), you will get an exception as follows:

FileLoadException as unhandled.
Could not load file or assembly 'AssemblyAbc, Version=, Culture=neutral, PublicKeyToken=b4571042c8aa084e' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)

To enable this reference in Development, you can skip the certificate verification process using the Sn.exe tool.
sn.exe -Vr *,b4571042c8aa084e

Run that command in the Visual Studio 2010 Command Line and thereafter the reference will work.
The Vr option signifies you wish to skip verification for this assembly. * signifies any user, and the hex value is the public key token of the partially signed assembly.

If you're running a 64-bit installation of Vista you'll need to use the sn.exe located at C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\sn.exe