Showing posts with label VSTO. Show all posts
Showing posts with label VSTO. Show all posts

Wednesday, 14 July 2010

C# 4 broke my code! The Pitfalls of COM Interop and Extension methods

A couple of weeks back I got the go-ahead from my boss to upgrade to Visual Studio 2010. What with Microsoft’s legendary commitment to backwards compatibility, and the extended beta period for the 2010 release, I wasn’t expecting any problems. The Upgrade Wizard worked its magic without hiccup, the code compiled, everything seemed fine.

Banana Skin - Image: Chris Sharp / FreeDigitalPhotos.netThen I ran our suite of unit tests. 6145 passed. 15 failed.

When I perused the logs of the failing tests they all had this exception in common:

COMException: Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))

How could that happen? Nothing should have changed: though I was compiling in VS 2010, I was still targeting .Net 3.5. The runtime behaviour should be identical. Yet it looked like COM Interop itself was broken. Surely not?

A footprint in the flowerbed

I dug deeper. In every case, I was calling an extension method on a COM object – an extension method provided by Microsoft’s VSTO Power Tools, no less.

These Power Tools are painkillers that Microsoft made available for courageous souls programming against the Office Object Model using C#. Up until C# 4, calling a method with optional parameters required copious use of Type.Missing – one use for every optional parameter you didn’t wish to specify. Here’s an example (you might want to shield your eyes):

var workbook = application.Workbooks.Add(Missing.Value);
workbook.SaveAs(
    "Test.xls", 
    Missing.Value, 
    Missing.Value, 
    Missing.Value, 
    Missing.Value, 
    Missing.Value, 
    XlSaveAsAccessMode.xlNoChange, 
    Missing.Value, 
    Missing.Value, 
    Missing.Value, 
    Missing.Value, 
    Missing.Value);

The Power Tools library provides extension methods that hide the optional parameters:

using Microsoft.Office.Interop.Excel.Extensions;

var workbook = application.Workbooks.Add();
workbook.SaveAs(
    new WorkbookSaveAsArgs { FileName = "Test.xls"} );

Can you see what the problem is yet? I couldn’t. So I thought I’d try a work-around.

A big part of C# 4 is playing catch-up with VB.Net improving support for COM Interop. The headline feature is that fancy new dynamic keyword that makes it possible to do late-bound COM calls, but the one that’s relevant here is the support for optional and named parameters. The nice thing is that, whereas using the dynamic keyword requires you to target .Net 4.0, optional and named parameters are a compiler feature, so you can make use of them even if you are targeting .Net 3.5.

That meant that I didn’t need Power Tools any more. In C# 4 I can just rewrite my code like this:

var workbook = application.Workbooks.Add();
workbook.SaveAs( Filename: "Test.xls" );

And that worked. COM Interop clearly wasn’t broken. But why was the code involving extension methods failing?

Looking again over the stack traces of the exceptions in my failed tests I noticed something very interesting. The extension methods didn’t appear. The call was going directly from my method into the COM Interop layer. I was running a Debug build, so I knew that the extension method wasn’t being optimised out.

The big reveal

Then light dawned.

Take a look at the signature of the SaveAs method as revealed by Reflector:

void SaveAs(
   [In, Optional, MarshalAs(UnmanagedType.Struct)] object Filename,
    /* 11 other parameters snipped */)

Notice in particular how Filename is typed as object rather than string. This always happens to optional parameters in COM Interop to allow the Type.Missing value to be passed through if you opt out of supplying a real value.

Now when C# 3.0 was compiling my code and deciding what I meant by

workbook.SaveAs(new WorkbookSaveAsArgs { ... } );

it had to choose between a call to the SaveAs instance method with 12 parameters or a call to the SaveAs extension method with a single parameter. The extension method wins hands down.

But the landscape changes in C# 4.0. Now the compiler knows about optional parameters. It’s as if a whole bunch of overloads have been added to the SaveAs method on Workbook with 0 through to 12 parameters. Which method does the compiler pick this time? Remember that it will always go for an instance method over an extension method. Since new WorkbookSaveAsArgs { … } is a perfectly good object the compiler chooses the SaveAs instance method, completely ignoring the extension method.

All seems well until we hit Run and Excel is handed the WorkbookSaveAsArgs instance by COM Interop. Not knowing how to handle it, it spits it back out in the form of a Type Mismatch exception.

Mystery solved.

The moral

So watch out if your code uses extension methods on COM objects and you’re planning on upgrading to VS 2010. Don’t assume that your code works the same as before just because it compiled OK. Unit tests rule!

Update: Microsoft have confirmed that this is indeed a breaking change that they didn’t spot before shipping.

Monday, 12 April 2010

Back from a bug hunt [or, Don’t Call Excel on a Background Thread]

I’m just back from a two-day bug hunt: an exhausting experience, but with a successful outcome that I’d like to share in case anybody else comes across this critter.

Photoxpress_8059464As he was testing our Excel Add-in, our Tester, Rich, noticed some rather odd behaviour. Whenever he used the Scan Tables feature,  then subsequently closed Excel, Excel.exe would refuse to vacate its slot in Task Manager until forcibly evicted.

The feature in question had my grubby fingerprints all over it, so I signed up to fix the bug. But where to start?

There are abundant examples of this kind of behaviour when automating Excel from the outside – usually caused by managed code not releasing its references to the COM objects. But my Add-in is inside Excel: any references it holds will be trashed when Excel is shutdown.

What then? I clearly remembered testing for just this kind of problem a couple of weeks back, and I was sure the application closed cleanly then. This gave me my starting point for a spot of Binary-Search debugging.

The Find

I began by grabbing a version of the code as it was at the time I thought the code was bug-free. Running it confirmed that was indeed the case. Then I pulled down a version that lay about half-way between then and now. That one exhibited all the symptoms of infestation. Hah! So the bug must have slipped in some time between the first version I checked and the half-way version. And thus I proceeded, wading through version after version, at each step slashing in half the list of changes in which the bug must have concealed itself.

After a couple of hours searching I narrowed it down to two versions: version 3320 had the bug, version 3319 was bug free. The check-in comment on version 3320 was rather revealing:

“Moved long-running table-scan operation to a background thread, and introduced progress reporting”

Those two words “background thread” were a smoking gun if ever I saw one, but who pulled the trigger? (I did mention that this bug was wanted for murder, right?). Now to adjust my binary-search-magnifying glass to zoom in, not on versions, but on lines of code.

I started by hacking the method where I launched the BackgroundWorker that did the table-scan so that, once again, it did its stuff in the UI thread. Sure enough, the bug went away, Excel closing cleanly on request.

Then, having restored the BackgroundWorker, I chopped its DoWork method in two, stubbing out one half at a time so that I could see which bunch of code was causing the problem. DoWork called out to a couple of other components, and I subject their methods to the same treatment. As method-call after method-call confirmed its innocence I closed in on the culprits: calls to the Excel Object model – specifically, calls to the Excel Object model made from a background thread.

Excel gave no indication that it had a problem being called in this way. When called on the background thread, it did exactly as when called on the foreground thread, with nary an exception. Seems it preferred to sulk, and protest in a more underhand way.

The Fix

Having found the problem, how was I to fix it?

I didn’t want to move all the work back on to the foreground thread: but clearly Excel wouldn’t listen if I talked to it from any other. Enter SynchronizationContext. SynchronizationContext is a handy little class that wraps up the complexities of executing code in another thread’s context. In the olden days of Windows Forms you’d use Control.BeginInvoke or Control.Invoke to do this kind of thing; these days WPF’s Dispatcher provides the same features. SynchronizationContext abstracts either Control or Dispatcher depending on what kind of message loop you’re running, and gives you two methods, Send and Post: Send executes code synchronously, Post asynchronously.

So all I needed to do was add a SynchronizationContext parameter to my two services which do all the talking to Excel (my IoC container kindly absorbed the consequences of this change – no ripple-down effect here).

Most places where I was calling Excel, I was querying some value. Like this, for example:

var result = (string)_application.Run("MyMacro")

Afterwards my change it looked like this:

var result = Query(() => (string)_application.Run("MyMacro"));

...

private TResult Query<TResult>(Func<TResult> query)
{
    return _synchronizationContext.SendQuery(query);
}

SendQuery is an extension method I created for SynchronizationContext that looks like this:

public static SynchronizationContextExtensions
{
    public static TResult SendQuery<TResult>(this SynchronizationContext context, Func<TResult> query)
    {
        var result = default(TResult);
        context.Send(parameter => result = query());
        return result;
    }
}

And that nailed it good and proper.

The Finale

So, Bing, if anybody asks you why their Excel Process doesn’t close after running an Add-in (managed or otherwise), tell them to make sure they are not calling into its object model from a background thread.

Friday, 2 October 2009

Work around for WPF Bug: Drag and Drop does not work when executing a WPF application in a non-default AppDomain

Today's task was implementing Drag/Drop to move items into folders. My estimate of yesterday was 6 hours to get the job done. That should have been plenty: then I discovered the bug.

We're creating an Excel Addin using Addin-Express (which is very like VSTO). All the UI for our add-in is built with WPF (naturally). When Addin Express hosts Add-ins for Excel, it isolates them each in their own App-Domain. Which is why today I came to add myself to the list of people who have reproduced this issue on the Connect website: "Drag and Drop does not work when executing a WPF application in a non-default AppDomain"

Googling around the problem, I found that Tao Wen had also encountered the problem, and had managed to find something of a work-around.

Having Reflectored around the WPF source-code a little, I can see that when WPF is hosted in a non-default App Domain, the check that the HwndSource class (which manages the Win32 Window object on behalf of the WPF Window class) does to ensure the code has the UnmanagedCode permission fails, so Windows do not register themselves as OLE Drop Targets (see the last few lines of the HwndSource.Initialize method)

Tao Wen's solution is to use reflection to directly call the internal DragDrop.RegisterDropTarget method. What his solution doesn't take into account is that, when the Window is closed it must unregister itself as a drop target.

Fortunately, by incrementing the _registeredDropTargetCount field in the HwndSource class we can ensure that HwndSource will itself call DropDrop.RevokeDropTarget when it's disposed (see about half-way down the HwndSource.Dispose method).

For anybody else who is blocked by the same issue, I've created a little class that will implement the hack on a Window class. Be warned: it uses evil reflection code to access private members of WPF classes, and it might break at any time. Use it at your own risk.

/// <summary>
/// Contains a helper method to enable a window as a drop target.
/// </summary>
public static class DropTargetEnabler
{
    /// <summary>
    /// Enables the window as drop target. Should only be used to work around the bug that
    /// occurs when WPF is hosted in a non-default App Domain
    /// </summary>
    /// <param name="window">The window to enable.</param>
    /// <remarks>
    /// This is a hack, so should be used with caution. It might stop working in future versions of .Net.
    /// The original wpf bug report is here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=422485
    /// </remarks>
    // This code was inspired by a post made by Tao Wen on the Add-in Express forum:
    // http://www.add-in-express.com/forum/read.php?FID=5&TID=2436
    public static void EnableWindowAsDropTarget(Window window)
    {
        window.Loaded += HandleWindowLoaded;
    }

    private static void HandleWindowLoaded(object sender, RoutedEventArgs e)
    {
        // See the HwndSource.Initialize method to see how it sets up a window as a Drop Target
        // also see the HwndSource.Dispose for how the window is removed as a drop target
        var window = sender as Window;

        IntPtr windowHandle = new WindowInteropHelper(window).Handle;

        // invoking RegisterDropTarget calls Ole32 RegisterDragDrop
        InvokeRegisterDropTarget(windowHandle);

        // to make sure RevokeDragDrop gets called we have to increment the private field
        // _registeredDropTargetCount on the HwndSource instance that the Window is attached to
        EnsureRevokeDropTargetGetsCalled(windowHandle);
    }

    private static void InvokeRegisterDropTarget(IntPtr windowHandle)
    {
        var registerDropTargetMethod = typeof(System.Windows.DragDrop)
            .GetMethod("RegisterDropTarget", BindingFlags.Static | BindingFlags.NonPublic);
        if (registerDropTargetMethod == null)
        {
            throw new InvalidOperationException("The EnableWindowAsDropTarget Hack no longer works!");
        }

        registerDropTargetMethod
            .Invoke(null, new object[] { windowHandle });
    }

    private static void EnsureRevokeDropTargetGetsCalled(IntPtr windowHandle)
    {
        var hwndSource = HwndSource.FromHwnd(windowHandle);
        var fieldInfo = typeof(HwndSource).GetField("_registeredDropTargetCount", BindingFlags.NonPublic | BindingFlags.Instance);
        if (fieldInfo == null)
        {
            throw new InvalidOperationException("The EnableWindowAsDropTarget hack no longer works!");
        }

        var currentValue = (int) fieldInfo.GetValue(hwndSource);
        fieldInfo.SetValue(hwndSource, currentValue + 1);
    }
}

Use it like this:

public partial class MyWindow
 {
        public MyWindow()
        {
            InitializeComponent();
            DropTargetEnabler.EnableWindowAsDropTarget(this);
        }
}

Monday, 19 May 2008

DebuggerNonUserCode: Suppressing ignorable exceptions in the debugger

Have you ever written code that made you want to wash your hands (or your keyboard!) the minute you'd finished typing? So dirty it was, that you surreptitiously looked around to see if anyone else had noticed the smell emanating from your instance of Visual Studio. We don't like it, but sometimes it's unavoidable. The clock is ticking; Google mentions no alternatives, so you put a peg on your nose, and plunge on.

It doesn't happen often in the clean, fresh-smelling environment of C#; usually it's when I'm writing VBA code that I feel like putting on the rubber gloves. One case that I do encounter in .Net more often than I would like though, is when Exceptions are thrown in non-exceptional cases, and I have to catch those exceptions to determine what to next.

Take Enum.Parse as an example. It converts a string value to an enum value. More likely than not, the string value will have been entered by the user, so there's a good chance that it's not valid. If it can't be parsed, then an ArgumentException is thrown. So if you want to trap for invalid values, you're forced to do this:

enum MyEnum
{
    Value1,
    Value2,
}

bool TryParse(string value, out MyEnum convertedValue)
{
    try
    {
        convertedValue = (MyEnum)Enum.Parse(typeof(MyEnum), value);
        return true;
    }
    catch (ArgumentException)
    {
        convertedValue = 0;
        return false;
    }
}

Apart from looking nasty, there's another problem that you only notice when you start using the debugger. If you've set the debugger to break whenever an exception is thrown - as I usually do to make sure there are no problems sneaking through overly generic catch handlers - it will break in this method whenever there's invalid input, even though you have the catch statement there and it wouldn't really crash your app. You could configure the debugger to ignore ArgumentException - but then you'll likely miss cases that you really do want to know about.

As of .Net 2.0, there's an easy solution to this problem: DebuggerNonUserCode. This is an attribute that you put against a method to tell the debugger "Nothing to do with me guv'. Ain't my code!". The gullible debugger will believe you, and won't break in that method: using the attribute makes the debugger skip the method altogether, even when you're stepping through code; exceptions that occur, and are then caught within the method won't break into the debugger. It will treat it as if it were a call to a Framework assembly, and should an exception go unhandled, it will be reported one level up the call stack, in the code that called the method. All this is part of the Just-My-Code feature, which Mike Stall gives the low-down on here.

Obviously this is powerful stuff. Make sure you've tested your code well before you apply the attribute -  or you won't be able to debug where it's going wrong (actually there is a way to do it - see the note below). For this reason, I'd suggest using it on the smallest method you can. Also make sure that you are catching very specific exceptions - notice that I'm using ArgumentException in this case, rather than a catch-all Exception.

I've found this especially useful when programming Excel. In the Excel object model, collections give you no API for discovering  if particular members exist. The only way to find out is to make the call, and see if you get an exception. Here's an example of an extension method that checks whether a Worksheet exists, decorated with the DebuggerNonuserCode attribute:

using System.Diagnostics;
using XL = Microsoft.Office.Interop.Excel;

public static class WorkbookExtensions 
{
    [DebuggerNonUserCode]
    public static bool TryGetWorksheet(this XL.Workbook wb, string worksheetName, out XL.Worksheet retrievedWorksheet)
    {
        bool exists = false;
        retrievedWorksheet = null;

        try
        {
            retrievedWorksheet = GetWorksheet(wb, worksheetName);
            exists = retrievedWorksheet != null;
        }
        catch(COMException)
        {
            exists = false;
        }

        return exists;
    }

    [DebuggerNonUserCode]
    public static XL.Worksheet GetWorksheet(this XL.Workbook wb, string worksheetName)
    {
        return wb.Worksheets.get_Item(worksheetName) as XL.Worksheet;
    }
}

Notes:

  1. If ever you need to see everything that's going on in your code, including in the DebuggerNonUserCode methods you can turn off the "Just My Code" feature in Visual Studio by going to Tools->Options, then expanding the Debugging node, and selecting General:

    JustMyCodeOption

  2. Jacob Carpenter has written up a Generic version of the TryParse pattern for enums; Michael Goldobin has actually created a TryParse that avoids the exception altogether - but don't read about that yet, because then you won't need my trick!.
  3. The TryParse pattern is already implemented for parsing other primitive types; int, double, decimal, etc. all have their TryParse methods: go and vote for Enum to get it too. As Peter Richie points out in that Feedback issue I linked to, this forced use of exception handling that Enum.Parse makes you do violates the Framework Design Guidelines. Shame on you, Microsoft ;-).

Thursday, 15 May 2008

(Mis)Using IDisposable: beyond resource clean-up

Anybody who has ever done any work with files, databases and so on, in C#, has had it drummed into them that they must be good citizens and always tidy up after themselves. Usually that means using using. But did you know that the using statement has uses that go far beyond resource cleanup?

As you know, using works in tandem with the IDisposable interface. Whenever you write something like this:

using (StreamReader reader = new StreamReader("MyFile.txt"))
{
    // do some stuff with the file
}

the compiler translates it into this:

StreamReader reader = new StreamReader("MyFile.txt");
try
{
    // do some stuff with the file
}
finally
{
    if (reader != null)
    {
        ((IDisposable)reader).Dispose();
    }
}

The effect of this is to ensure that, however dodgy the stuff you're doing with reader, whatever exceptions are thrown, its Dispose method will always be called.

Traditionally, this pattern has been used to ensure that files are closed, database connections are severed, GDI Brushes are washed up, etc. as soon as code has finished with them. But it's not limited to that. Think laterally. What does the using statement actually do? It guarantees that, at the end of the using block the Dispose method will be called on the variable that you are are using. But the Dispose method doesn't need to dispose of things. It can do anything you like!

Suppose for example that you need to change the state of something temporarily, whilst you do a job, but want to make sure that it gets changed back when you've finished. Then the using statement is here to help!

An example from VSTO Programming

For a practical example, consider the Excel object model. If you want to get good performance whilst you change lots of cells about, you have to tell Excel not to bother redoing calculations, or updating the screen for the duration. But when you've finished mucking about with its worksheets, you certainly do want Excel to repaint and recalculate.

Now suppose that you have several methods, each modifying cells, and each wanting to do it efficiently. Each of them could turn off recalculation and screen updating before they start, and back on when they've finished. But then, if those methods start calling each other you'll end up with a disco, as the screen flashes each time updating is turned off then on again. To get round this, each method should capture the current state, then restore that when it has finished. But think how mucky the code in each method would look if you started doing that in-line. Now consider this:

public void Update1()
{
    using (excel.DisableUpdating())
    {
        // change lots of cells, etc.
        Update2();
    }
}
public void Update2()
{
    using (excel.DisableUpdating())
    {
        // change other cells
    }
}

The DisableUpdating method takes care of capturing the current state, turning off repainting and recalculation, and then returns an IDisposable that will restore the original state. So whatever the nesting of method calls, the right thing will always happen.

Here's the extension method that makes this possible:

using Xl = Microsoft.Office.Interop.Excel;
public static class ApplicationExtensions
{
    public static IDisposable DisableUpdating(this Xl.Application application)
    {
        // preserve the current settings
        var originalScreenUpdating = application.ScreenUpdating;
        var originalCalculationMode = application.Calculation;

        // disable the updates
        application.ScreenUpdating = false;
        application.Calculation = Xl.XlCalculation.xlCalculationManual;

        return new DelegateInvokingDisposer(
            () =>
            {
                // when disposed, restore the original settings
                application.ScreenUpdating = originalScreenUpdating;
                application.Calculation = originalCalculationMode;
            }
            );
    }
}

You can see that this makes good use of closures to capture the existing state from Excel so that it is available for use by the Disposer lambda function.

The DelegateInvokingDisposer class looks like this:

public struct DelegateInvokingDisposer: IDisposable
{
    private readonly Action _disposeMethod;

    public DelegateInvokingDisposer(Action disposeMethod)
    {
        if (disposeMethod == null)
        {
            throw new ArgumentNullException("disposeMethod");
        }

        _disposeMethod = disposeMethod;
    }

    public void Dispose()
    {
        _disposeMethod();
    }
}

You can find other examples of this idea around the blogosphere. Ian Griffiths, for example, has used this technique to improve on the C# lock statement, creating a version that will timeout if unable to acquire a lock. You'll find another example if you look at the WPF framework, and the ItemCollection class, which supplies items to ListBoxes and the like. In WinForms, if you had a block of code that updated the Items property, you would top and tail it with calls to ListBox.BeginUpdate and ListBox.EndUpdate so that the ListBox didn't get redrawn for every additional item. ItemCollection does things differently. It has the DeferRefresh method which returns an IDisposable object. You use it like this:

using (listBox.Items.DeferRefresh())
{
    listBox.Items.Add("MyItem");
    // add lots more items
}

I'm sure, once you get used to the idea, you'll be able to find new uses of using for yourself.