Snoop 2.7.0

This post is long overdue. I have written about Snoop for WPF a couple times, and it’s been a while since I gave an update.

Back in September, we published v2.7.0 (release announcement). One of the coolest new features is the ability to drag and drop a cross-hair to the app you want to snoop. You no longer have to wait for the list of applications to refresh.  We added a DataContext tab and various bug fixes.

CropperCapture35

I’ve been spending a bit of my RECESS time lately getting back into contributing to the code base. We have some really cool features in the works — I’ll post again when the next version hits the streets.

Prism 4, MEF and the CompositionInitializer

So I have been using MEF (Managed Extensibility Framework) for a while now on most of my WPF projects. Lately, I have been really getting a lot of use out of Prism 4.0 as well and utilizing the built in MEF with the MefBootstrapper.

One of the things that I always found a bit troublesome however was what to do when you need a non-exported class to satisfy its imports from MEF. This came up on a recent project, as I was using the IEventAggregator from Prism, thought it would be useful to have it in classes that may not come from MEF- i.e. classes that are new’ed up depending on the business logic dictated. Now, the true MEF heads may say, ‘Nooooo! That’s not what MEF is for!’. But I thought I would see how it worked anyway.

To solve this, one approach was to pass in my IEventAggregator to my class through the constructor, but this didn’t seem too elegant. What if I need other imports besides the IEventAggregator? Then potentially I need to pass in more and more stuff to the constructor.

What I really needed, was some way to tell the class that it has imports it needs to satisfy, and notify that class that it needs to check the already existing container for this. This is where the CompositionInitializer comes in. One problem with that is that the CompositionInitializer was designed for Silverlight, and my application is MEF. But, no worries, Glenn Block had anticipated my need and kindly written a WPF CompositionInitializer, to be found here. Thanks Glenn. And in addition, I found lots of other great info from Reed Copsey’s site. Thanks Reed.

So I placed my CompositionInitializer in my non-exported class in the constructor:

// No export here
public class MyClass
{
	public MyClass()
	{
		CompositionInitializer.SatisfyImports( this );
	}

	[Import]
	private IEventAggregator EventAggregator { get; set; }
}

But when I ran the code, even though I had a valid import for my IEventAggregator, none of my messages were being received. A bit of googling brought me here. Aha! Simply placing my CompositionInitializer.SatisfyImports( this ) in the constructor is insufficient. How, after all, does the CompositionInitializer know what container you are using? I was so used to MEF magic that it hadn’t occurred to me that CompositionInitializer needs to have its container set.

By adding the following line to my BootStrapper file in a location that gets called after CreateShell():

CompositionHost.Initialize( Container );

My CompositionInitializer was now armed with the appropriate container, and everything worked great in the constructor. Now I was able to new up an instance of any class and satisfy its imports against my Container.

XamlReader, Loose ResourceDictionary Files, and the ParserContext

In a few WPF projects that I have been on I have needed to load in loose ResourceDictionary files to provide different runtime styling. When there isn’t any external content being referenced (ie. images, videos, etc…) it is as simple as calling XamlReader.Load and then merging the dictionary into the application’s resources:

var resourceDictionary = XamlReader.Load(fileStream) as ResourceDictionary;
if(resourceDictionary != null)
{
    Resources.MergedDictionaries.Add(resourceDictionary)
}

When external content is being referenced there is the possibility that the XamlReader won’t be able to find those files, even if they are in the exact same folder as the ResourceDictionary files. To solve this issue, you will need to create a ParserContext and set its BaseUri to the root folder containing the files. For example, if the ResourceDictionary and content files are located in a folder called RuntimeResources, which is in the same folder as the application’s exe, then the BaseUri needs to point to that RuntimeResources folder. Then when the XamlReader loads the ResourceDictionary, it uses the provided ParserContext to know where to look for the actual files. NOTE: In the ResourceDictionary you will still need to include the root folder (RuntimeResources) at the beginning of the uri otherwise it will look in the parent directory for the desired file.

Below is the related code:

C#

var applicationDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if(!String.IsNullOrEmpty(applicationDirectory ))
{

    var runtimeResourcesDirectory = Path.Combine(applicationDirectory , "RuntimeResources");
    var pc = new ParserContext
    {
        BaseUri = new Uri(runtimeResourcesDirectory , UriKind.Absolute)
    };
    if(Directory.Exists(runtimeResourcesDirectory ))
    {
        foreach (string resourceDictionaryFile in Directory.GetFiles(runtimeResourcesDirectory , "*.xaml"))
        {
            using (Stream s = File.Open(resourceDictionaryFile, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    var resourceDictionary = XamlReader.Load(s, pc) as ResourceDictionary;
                    if (resourceDictionary != null)
                    {
                        Resources.MergedDictionaries.Add(resourceDictionary);
                    }
                }
                catch
                {
                    MessageBox.Show("Invalid xaml: " + resourceDictionaryFile);
                }
            }
        }
    }
}

Resource Dictionary

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

	<ImageBrush x:Key="LogoImage"
			  ImageSource="RuntimeResources/logo.png" />

</ResourceDictionary>

Now you’ve got the ability to change your WPF application’s styling at runtime.

Merging a WPF application into a single EXE

I always dislike handing off little applications to people. Not because I can’t, but because of the steps involved to make sure it all just works. Small apps are the most problematic because I never want to take the time to create a whole installer project for just a few assemblies, and packaging up a zip file must be accompanied by “Unzip this into a folder in your programs directory and create a shortcut…” which brings us back to the whole installer business we started with.

There are a few tools already out there such as ILMerge by Microsoft Research (Which works great for most .NET-y things, but chokes on WPF applications) and a few paid tools by third party vendors that you could fork over a few hundred for to get. But, I’m a developer, which means I want to do it the Hard Way™. I did a little research and found the following blog posts on setting up and merging in DLL’s as resources into the main assembly and then extracting and loading them into memory when you run your application.

Links:

There were a few things I didn’t like about each solution. The first one (richarddingwall.name) ends up having you directly adding the .dll’s as resources directly. I hate maintaining things manually, especially when it will run fine on my machine but break when when I move it somewhere else because I forgot to update the resources when I added a new project. The one from blog.mahop.net builds on the previous one and changes the resolve location to a custom class with its own startup method. Better, because it resolves the resources earlier. Finally, the one from Daniel Chambers (digitallycreated.net) added in the final piece that automatically including the assemblies as resources. Unfortunately, the way he looks for culture specific assemblies didn’t work and I had to remove / change it to be closer to the one on mahop.net.

Final solution I’m currently using is as follows:

To the main executable project, unload and edit the .csproj file, and below the following line:

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

Add this XML to the project file, save, and load it back up.

 <Target Name="AfterResolveReferences">
  <ItemGroup>
    <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
      <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
    </EmbeddedResource>
  </ItemGroup>
</Target>

It should look something like this when your done:

You’ll then add a new code file to the main project and add the following code to it (modified to fit how your application is named / structured):

        [STAThread]
        public static void Main()
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;

            App.Main(); // Run WPF startup code.
        }

        private static Assembly OnResolveAssembly(object sender, ResolveEventArgs e)
        {
            var thisAssembly = Assembly.GetExecutingAssembly();

            // Get the Name of the AssemblyFile
            var assemblyName = new AssemblyName(e.Name);
            var dllName = assemblyName.Name + ".dll";

            // Load from Embedded Resources - This function is not called if the Assembly is already
            // in the same folder as the app.
            var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(dllName));
            if (resources.Any())
            {

                // 99% of cases will only have one matching item, but if you don't,
                // you will have to change the logic to handle those cases.
                var resourceName = resources.First();
                using (var stream = thisAssembly.GetManifestResourceStream(resourceName))
                {
                    if (stream == null) return null;
                    var block = new byte[stream.Length];

                    // Safely try to load the assembly.
                    try
                    {
                        stream.Read(block, 0, block.Length);
                        return Assembly.Load(block);
                    }
                    catch (IOException)
                    {
                        return null;
                    }
                    catch(BadImageFormatException)
                    {
                        return null;
                    }
                }
            }

            // in the case the resource doesn't exist, return null.
            return null;
        }

Finally, make sure you update the target method for your main application to be the main method for the project you just added:

And, that’s it!

When you build your application you’ll still see all the assemblies in the output directory, but you should be able to take just the executable, move it somewhere else, and run it just as it is.

Presentation Materials for San Diego Code Camp

Thanks to everyone for coming!

Harnessing XAML Templates: Slides | Code (WPF, SL4, SL5)

Easy Async with Async CTP: Slides | Code

Look at the AddingAsync section for the multi-step conversion from synchronous to async with cancellation and error handling that we didn’t have time to walk through.

Get the Async CTP at http://msdn.microsoft.com/en-us/vstudio/async.aspx

Presentation Materials for New Hampshire Code Camp 2011

Thanks to the organizers and to everyone for coming inside on a beautiful day!

Real World Reactive Extensions: Slides | Code

Rx Home: http://msdn.microsoft.com/en-us/data/gg577609

Reactive UI: http://www.reactiveui.net/

Harnessing XAML Templates to Power Your UI: Slides | Code (WPF, SL4, SL5 Beta)

Binding to alternate DataContexts

The DataContext is one of the most important parts of the WPF data binding system, especially in MVVM applications. Being built into the Binding type as the common source for bindings in a specific scope reduces plumbing code needed and makes XAML more concise. Unfortunately, for any given element there is only one DataContext available to bind against. Most of the time this isn’t a problem, but complex data hierarchies often lead to situations where an element needs to bind to the DataContext of some parent element in addition to its own local DataContext.

I most often run into this with ItemsControls where something inside the ItemTemplate needs to bind to the ViewModel containing the entire collection:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <DockPanel>
                <TextBlock Text="{Binding Name}"/>
                <Button Content="Remove" Command="<Remove item command on parent VM>" CommandParameter="{Binding}"/>
            </DockPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Continue reading

Event Leapfrogging

(Thanks to Sam Bent from the WPF team for identifying and giving a name to the problem)

Event Leapfrogging is an issue that arises from a combination of two inherent aspects of .NET events: multicasting and synchronous handler execution. A common place that it shows up is in property change handlers in WPF controls and INotifyPropertyChanged objects.

Here’s some code demonstrating the problem: Continue reading