Unhandled MissingMethodException

9 May

I came across an interesting product bug while analyzing Watson crash dumps today. Our application was crashing due to an unhandled MissingMethodException on a background thread. Looking at the managed stack trace revealed the exception was coming from a method which uses the Dispatcher.Invoke(Delegate, params object[]) overload, added in the .NET Framework 3.5 SP1. This is an unsupported configuration; nonetheless we don’t want to be crashing hard.

When I investigated the offending method I was perplexed to find a top level exception handler wrapping all calls to Dispatcher.Invoke. This method is invoked on a background thread so we are careful not to allow an unhandled exception which would result in a crash. Needless to say I wasted a bit of time pouring over the version history, assembly versions, etc. Finally I took a look at the native callstack

0:004> kb
RetAddr                       : Args to Child            : Call Site
00000000`74e196d0 : 00000000`1c25d650 00000000`1c25c8e8 00000000`00000100 00000000`00000000 : KERNEL32!RaiseException+0x39
00000000`771f54a1 : 00000000`00000000 00000000`1c25db20 00000000`00000000 00000000`00000000 : MSVCR80!_CxxCallCatchBlock+0x180
000007fe`f33ef38a : 00000000`1b18d6f0 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!RcConsolidateFrames+0x3
000007fe`f33b5eaf : 00000000`00000000 00000002`00000000 00000000`00000000 00000000`1b190980 : mscorwks!MethodDesc::MakeJitWorker+0x1ea
000007fe`f33a560b : 00000000`00000000 00000000`00295200 00000000`00000000 00000000`02a21758 : mscorwks!MethodDesc::DoPrestub+0x116f
000007fe`f34e2207 : 00000000`02a22028 00000000`00000000 00000000`02a21fe8 00000000`1b185110 : mscorwks!PreStubWorker+0x1eb
000007ff`001903ce : 00000000`02a216b8 00000000`00000000 00000000`1c25f5c0 00000000`00000000 : mscorwks!ThePreStubAMD64+0x87
000007fe`f174174b : 00000000`02a216b8 00000000`00000000 00000000`1c25f5c0 00000000`00000000 : 0x7ff`001903ce
000007fe`f179d786 : 00000000`00000018 00000000`00000000 00000000`00250288 00000000`771f7b1a : mscorlib_ni+0x2f174b
000007fe`f34e2322 : 00000000`02a21758 000007fe`f3976ea0 ffffffff`fffffffe 00000000`00002400 : mscorlib_ni+0x34d786
000007fe`f33e3bb3 : 00000000`0000017e 000007fe`f18b8aa8 00000000`002a0588 00000000`00000000 : mscorwks!CallDescrWorker+0x82
000007fe`f33ebc46 : 00000000`1c25f9e8 000007fe`f33d353d ffffffff`fffffffe 00000000`00000000 : mscorwks!CallDescrWorkerWithHandler+0xd3
000007fe`f343bd7f : 000007fe`f14d5730 000007fe`f1451000 000007fe`f3af7c78 000007fe`f336c1d8 : mscorwks!DispatchCallDebuggerWrapper+0x3e
000007fe`f32f6a5e : 00000000`1c25fb78 00000000`1b185101 00000000`00000001 00000000`1b185110 : mscorwks!DispatchCallNoEH+0x5f
000007fe`f3327598 : 00000000`02a21758 00000000`02a21758 00000000`00000001 000007fe`f33e0f6a : mscorwks!AddTimerCallback_Worker+0x92
000007fe`f342eb85 : 00000000`00000001 00000000`00000000 ffffffff`fffffffe 00000000`1c25fb98 : mscorwks!Thread::DoADCallBack+0x488
000007fe`f331a515 : 00000000`002a0230 00000000`1b185110 00000000`1c25faa0 00000000`1b1822f0 : mscorwks!SVR::gc_heap::make_heap_segment+0x155
000007fe`f331487e : 00000000`1c25fb98 ffffffff`ffffffff 00000000`1b185110 00000000`1c25a8f0 : mscorwks!AssemblySecurityDescriptor::GetZone+0x169
000007fe`f32f5a7b : ffffffff`fffffffe 00000000`00000001 ffffffff`fffffffe 00000000`002c9920 : mscorwks!AddTimerCallbackEx+0xba
000007fe`f336dc77 : 00000000`00000000 00000000`00000001 00000000`00000000 00000000`00000001 : mscorwks!ThreadpoolMgr::AsyncTimerCallbackCompletion+0x53

It looks like the exception is actually being thrown from native code during the JIT. Here is a simple repro

public class BackgroundWorker
{
    private Timer _timer;

    public BackgroundWorker()
    {
        _timer = new Timer((state) => DoWork(), null, 0, 1000);
    }

    public void DoWork()
    {
        // top level handler
        try
        {
            // ...
            // call missing method here
            // ...
        }
        catch (Exception e)
        {
            // some logging
        }
    }
}

Before the thread pool thread executes the anonymous method it must be JITed.

[CompilerGenerated]

private void <.ctor>b__0(object state)

{

this.DoWork();

}

When the JITer encounters missing method inside of DoWork it throws a MissingMethodException. Since this takes place outside the try/catch block the process crashes.

Regedit Favorites

6 May

Embarrassingly, I just now realized Regedit supports favorites!

I’ve spent far too many seconds navigating b/w Visual Studio’s experimental and non-experimental HKCU registry settings when validating functionality. Not to mention having to remember to look in HKLM’s wow6432 node on my 64 bit machine. What a revolutionary feature 🙂

Dynamically load assembly with strong name verification

3 May

I recently needed to load an assembly into a temporary AppDomain. This assembly was being loaded from a random location in the current user’s temp directory. Since the temp directory is less secure than say Program Files, I wanted to ensure it was indeed my strongly named assembly being loaded.

After wasting a bit too much time trying to (unsuccessfully) decipher how to use to get the Assembly.LoadFrom overload with the Evidence parameter I landed on the much simpler solution using the AssemblyName type.

 

var fqn = "ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1452a42f10e38892";
var assemblyName = new AssemblyName(fqn);
assemblyName.CodeBase = ""; // path to assembly to load

var assembly = Assembly.Load(assemblyName);

 

This approach allows you to specify the fully qualified assembly name and the location from which to load the assembly.

Dialog UI

3 Feb

 

Graphics card drivers have notoriously bad dialogs, but this one takes the cake. What’s with the red exclamation mark!?

 

Oil Change

7 Sep

Finally a use for those old programming books.

IMG_0237

New Bike!

19 Jul

Finally got my new bike this Thursday. Ridley Excalibur Team Unibet frameset, mostly Shimano Dura-Ace 10 speed components, DT Swiss wheelset.

Just finished building it, now it’s time to hang it on the wall… I mean ride it.

IMG_0094

Localize Enum Values

16 Jul

In a previous post I created a markup extension which could be used to bind an Enum’s values to an ItemsControl. Now what if we want those values to be localized? The following is a little trick I use to solve this problem.

My translations are stored in .NET resources. When I add a resource representing an Enum value I use the naming convention <EnumName>_<EnumValueName> for the key.

public enum DevicePointFormat
{
    Binary,
    Decimal,
    Hex
}

image

 

I have a Value Converter that converts an Enum value to a resource string.

public class LocalizeEnumValue : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        var enumType = value.GetType();
        var key = String.Format(CultureInfo.InvariantCulture, "{0}_{1}",
            enumType.Name, Enum.GetName(enumType, value));
 
        return MyResources.ResourceManager.GetString(key);
    }
 
    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Now imagine we have a ComboBox bound to the values of the DevicePointFormat Enum. We can set the ItemTemplate attribute to a custom DataTemplate which invokes the LocalizeEnumValue converter on the EnumValue and displays the string in a TextBlock.

 

<Window.Resources>
    <src:LocalizeEnumValue x:Key="LocalizeEnumValueConverter" />
    <DataTemplate x:Key="LocalizedEnumDataTemplate" DataType="{x:Type s:Enum}">
        <TextBlock Text="{Binding Converter={StaticResource LocalizeEnumValueConverter}}" />
    </DataTemplate>
</Window.Resources>
 
<StackPanel>
    <ComboBox ItemsSource="{Binding Source={src:EnumValues {x:Type src:DevicePointFormat}}}"  
        ItemTemplate="{StaticResource LocalizedEnumDataTemplate}" />
</StackPanel>
image  image 

Resource Markup Extension

16 Jul

In my spare time I’m working on a smallish WPF application which will need to be localized. Looking at WPF’s current localization story left me wanting. What I really wanted was good old fashioned .NET resources accessible in xaml.

One option is to generate public resource files using the PublicResXFileCodeGenerator custom tool new to VS 2008. This provides access to the System.Windows.Markup.StaticExtension allowing us to reference a resource in xaml like so

<TextBlock Text="{x:Static src:MyResources.HelloWorld}" />

This is ok but it feels a bit verbose and we may not want to make our resources public. In that case we can create our own ResourceExtension markup extension which will have access to internals (provided it is defined in the same assembly).

internal class ResourceExtension : MarkupExtension
{
    private readonly string _key;
 
    public ResourceExtension(string key)
    {
        if (key == null)
            throw new ArgumentNullException("key");
        if (key == String.Empty)
            throw new ArgumentException("Argument key cannot be empty.");
 
        _key = key;
    }
 
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var propertyInfo = typeof(MyResources).GetProperty(_key,
            BindingFlags.Static | BindingFlags.NonPublic);
 
        Debug.Assert(propertyInfo != null, String.Format(CultureInfo.InvariantCulture,
            "Unable to find specified key '{0}' in resource file.", _key));
 
        // return null if the key does not exist
        return propertyInfo != null ? propertyInfo.GetValue(null, null) : null;
    }
}

Then we can use the following xaml

<TextBlock Text="{src:Resource HelloWorld}" />

Now we have fewer characters to type in our markup, our resources are internal, but we can’t reuse this class with the resource type hard coded into the ProvideValue method.

 

We can refactor the common code to a generic base class like so.

internal abstract class ResourceExtensionBase<T> : 
    MarkupExtension where T : class
{
    protected string Key { get; set; }
 
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var propertyInfo = typeof(T).GetProperty(Key,
            BindingFlags.Static | BindingFlags.NonPublic);
 
        Debug.Assert(propertyInfo != null, String.Format(CultureInfo.InvariantCulture,
            "Unable to find specified key '{0}' in resource file.", Key));
 
        // return null if the key does not exist
        return propertyInfo != null ? propertyInfo.GetValue(null, null) : null;
    }
 
    protected static void ValidateArguments(string key)
    {
        if (key == null)
            throw new ArgumentNullException("key");
        if (key == String.Empty)
            throw new ArgumentException("Argument key cannot be empty.");
    }
}

Then we need to declare the following markup extension for each resource file we need access to

internal class ResourceExtension : 
    ResourceExtensionBase<MyResources>
{
    public ResourceExtension(string key)
    {
        ValidateArguments(key);
        Key = key;
    }
}
 

I wouldn’t say I love this approach. Creating a custom type for each resource file won’t scale well for large projects but it is working well for my small project.

Veggie Box

10 Jul

Everybody’s doing it… A variety of delicious organic fruits and vegetables tailored by you to your unique preferences and delivered to your door! What could be wrong with that?

image

Enum GetValues markup extension

8 Jul

There are plenty of posts dealing with binding an ItemsControl to an Enum’s values. Beatriz Costa demonstrates how to accomplish this purely in xaml. We end up with something like the following.

<ObjectDataProvider MethodName="GetValues" 
    ObjectType="{x:Type s:Enum}" x:Key="EnumValues">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="src:DevicePointFormat" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>        

   

This feels a little on the verbose side to me. The Enum type itself (DevicePointFormat) is in the xaml so each time we need another Enum type’s values we will need to essentially duplicate the xaml snippet. Sounds like we could use a markup extension.

public class EnumValuesExtension : MarkupExtension
{
    private readonly Type _enumType;
 
    public EnumValuesExtension(Type enumType)
    {
        if (enumType == null)
            throw new ArgumentNullException("enumType");
        if (!enumType.IsEnum)
            throw new ArgumentException("Argument enumType must derive from type Enum.");
 
        _enumType = enumType;
    }
 
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Enum.GetValues(_enumType);
    }
}

 

With the EnumValuesExtension we no longer need to create an ObjectDataProvider, we simply hand the Enum type we’re interested in to the markup extension and bind to the returned values.

<ComboBox ItemsSource="{Binding Source={c:EnumValues {x:Type src:DevicePointFormat}}} />

 

Not rocket science but you might find it useful.