Testing cross-post.

Please ignore.

Moq, Callbacks and Out parameters: a particularly tricky edge case

In my current project we’re using Moq as our mocking framework for unit testing. It’s a very nice package – very simple, very intuitive for someone who has his wrapped around basic mocking concepts, but tonight I ran into an annoying limitation that, while rare, impeded my tests considerably.

Consider the following code:

  1: public interface IOut
  2: {
  3:    void DoOut (out string outval);
  4: }
  5: 
  6: [Test]
  7: public void TestMethod()
  8: {
  9:   var mock = new Mock();
 10:   string outVal = "";
 11:   mock.Setup(out => out.DoOut(out outVal))
 12:       .Callback<string>(theValue => DoSomethingWithTheValue(theValue));
 13: }

What this code SHOULD do is create a mock object for the IOut interface that, when called with an out parameter, both assigns a value to it, and does something with the value in the Callback.

Unfortunately, this does not work.

The reason it doesn’t work is that the Callback method has many overloads, but they are all to various variants of the Action<> delegate. Either Action, which receives one parameter, or to Action, which receives three. None of these support out parameters. But none of these delegates has a signature with an out parameter. The result, at runtime, would be an error to the effect of

“Invalid callback parameters <string> on object ISetup<string&>”

Note the highlighted bits – The Setup method referred to a string& (a ref/out param), while the Callback inferred an Action delegate, which expectes a regular string param.

So what CAN we do?

The first option is submit a patch to the Moq project. It’s open-source, and a solution might be appreciated, especially since the project’s lead, Daniel Cazzulino, pretty much acknowledged that this is not supported right now. I might do that later, but right now it’s the middle of the night and I just want my tests to pass. So I manage to hack together this workaround which does the trick:

  1: public static class MoqExtension
  2: {
  3:    public delegate void OutAction (out TOut outVal);   
  4:    public static IReturnsThrows 
  5:                         OutCallback
  6:                                  (this ICallback mock, 
  7:                                   OutAction action) 
  8:                                      where TMock : class
  9:    {
 10:       mock.GetType()
 11:           .Assembly.GetType("Moq.MethodCall")
 12:           .InvokeMember("SetCallbackWithArguments", 
 13:                         BindingFlags.InvokeMethod 
 14:                             | BindingFlags.NonPublic 
 15:                             | BindingFlags.Instance, 
 16:                         null, mock, new object[] {action});
 17:       return mock as IReturnsThrows;
 18:    }
 19: }

 

We’ve created a new delegate, OutAction, that has out T as its parameters, and we’ve added a new extension method to Moq, OutCallback, which we will use instead of Callback. What this extension method does is use brute-force Reflection to hack into Moq’s internals and call the SetCallbackWithArguments method, which registers the Callback with Moq. Yes, it even works. I’m as surprised as you are.

Note and Caveats:

1) This code works for the very specific void Function (out T) signature. You will have to tailor it to the specific methods you want to mock. To make it generic, we’ll have to create a bucket-load of OutAction overloads, with different combinations of out and regular parameters.

2) This is very hacky and very fragile. If Moq’s inner implementation changes in a future version (the one I’m using is 4.0.10827.0), it will break.

3) I don’t like using out params, usually, but this is a 3rd party library, so I have to work with what I got.

Comments? Questions? Scathing criticisms on how ugly my code is? A different, simpler method of accomplishing this that I totally missed? Bring’em on.

WPF: Snooping Attached Properties

When developing WPF applications, Snoop is a wonderful tool that can let us see our visual tree at runtime, and find errors in data binding that are otherwise hard to track down in debugging. However, Snoop has an annoying limitation – it can’t show us data-bound Attached Properties. Let’s say we have the following XAML:

<Canvas>
   <Button Canvas.Left="{Binding Location.X}"
           Canvas.Top="{Binding Location.Y"}/>
Canvas>

Snooping this application won’t show Canvas.Left and Canvas.Top among the Button’s properties, since they’re not a part of the Button object. If we have a bug in our binding, we won’t be able to find it.

So what do we do? We can set various TraceLevel attributes to save the binding errors to a log, but a quick workaround during debugging is to bind our data, in addition to the attached properties, to the element’s Tag property, a generic object that can bind to anything, and allow us to Snoop the binding – and find out any problems:

<Canvas>
   <Button Canvas.Left="{Binding Location.X}"
           Canvas.Top="{Binding Location.Y}"
           Tag="{Binding Location}" />
Canvas>

This allowed me to find out, quickly, that my bug was simple – I had forgotten to make my Location property public, causing the binding to fail silently.

Saving Your Settings

Tomorrow I am bidding my laptop farewell, and will soon buy me a new one. This results in what I like to call Settings Anxiety. I spend months tuning various aspects of my computer to my liking, and starting afresh with a new machine is wearisome. There are solutions to this, of course. I can make a full settings backup using Windows Easy Transfer or some such tool to store my settings and registry information and reload them on my new computer. I am, however, leery of it. First of all, I don’t trust WET to backup everything, especially 3rd party settings and application data. Secondly, I don’t want to copy all the cruft that’s accumulated in my user settings. One advantage to leaving the old computer is to start fresh.

So my compromise is to do a set of manual exports for various pieces of software, to carry it with me to the new computer, whenever it arrives. I’m going to list the various programs I use here that I bothered to customize, and detail the steps needed to do a manual export. This way I can come back to it the next time I reformat.

1. Outlook 2007

I use Outlook to connect to an Exchange server and to Gmail via IMAP. Both of these use OST files for local offline caching, but the primary storage is on the server. No real need for me to back this up.

Unfortunately, there’s no way to export my Outlook profile’s entire Accounts list to a file, and reimport it later. It means I always have to go to Gmail’s help page to remember the port numbers they use for encrypted IMAP and SMTP, but it’s not too much of a hassle.

2. Visual Studio 2008

Two important customizations here – color scheme (I like grey background) and keyboard shortcuts (single-click build-current-project ftw!). Both are easily exported using Tools –> Import and Export Settings –> Export selected environment settings.

3. Google Chrome

Bookmarks, cookies and stored passwords – things I really don’t feel like retyping again and again after I got my Chrome to memorize it for me. Basically, with all major browsers importing favorites and settings from one another, you only really need to backup one browser’s settings.

Unfortunately, Google haven’t quite gotten around to implementing Export Settings in Chrome – like a lot of other things. To backup my settings, I am copying the C:UsersusernameAppDataLocalGoogleChromeUser Data folder. There’s a lot of useless junk there – the cache, Google Gears data – but it should contain all the interesting bits too.

4. RSSBandit

RSSBandit’s “Export Feeds” option will probably export the feed definitions, but not the actual text of the actual feeds that I already have, offline, in my reader. It does support exporting the list of items in a feed, including read/unread state, though. But a better solution, assuming I am unbothered by space or time, is to use RSS Bandit’s “Remote Storage” option to save the entire feed database to a ZIP file that can be “downloaded” into a new installation. Under Tools –> Options –> Remote Storage set the destination (I use a file share), then do Tools –> Upload Feeds.

When recovering, I’ve found that RSS Bandit doesn’t always succeed in reading the ZIP file – I got a “file was closed” error. What I did was simply open the ZIP file and copy all the XML files into the %AppData%RssBandit folder, et voila.

5. Windows Live Writer

Another useful tool that wasn’t given an Export Settings option. There are two things to backup here:

1. My blog settings – I have 5 different blogs I manage through WLW. Here I had to go back to the Registry. Funny how it seems so old-fashioned. Export all settings from HKEY_CURRENT_USERSoftwareMicrosoftWindows LiveWriter.

2. Blog drafts and recently-written posts are stored in My DocumentsMy Weblog Posts. Would be a good idea to back those up as well.

3. When restoring settings, it initially appears that while the blog settings are properly recovered, the drafts aren’t. All you need to do, though, is double-click on one of the .wpost files in the My Weblog Posts folder, and the Drafts and Recently Posted lists will get populated.

6. Digsby

Digsby, the multi-protocol IM and Social Networking tool, uses a centralized login to store the settings of my different protocols – so I only need to log in with my Digsby ID to have all my IM networks working. There are some tweaks to the client itself which I would like to not lose, but they don’t provide an Export Settings feature either, and it’s nothing I can’t live without.

 

For most other things, I’d rather not bother until I actually need it.

Tales from the Unmanaged Side – System.String –> char* (pt. 2)

A while ago, I posted an entry about marshalling a managed System.String into an unmanaged C string, specifically a plain char*. The solution I suggested, back in 2007, involved calling Marshal::StringToHGlobalAuto method to allocate memory and copy the string data into it, and then cast the HGlobal pointer into a char*.

It seems that in Visual Studio 2008 a new way of doing it was added, as part of the new Marshalling Library. This library provides a whole set of conversions between System.String and popular unmanaged string representations, like char*, wchar_t*, BSTR, CStringT and others I am even less familiar with.

The smarter string representations, like std::string, have their own destructors so I can carelessly let them drop out of scope without worrying about leaks. The more primitive ones, like char*, need to be explicitly released, so that’s why the Marshalling Library contains a new (managed) class called marshal_context which gives me exactly this explicit release.

Let’s compare my old code with the new:

   1:  const char* unmanagedString = NULL;
   2:  try
   3:  {
   4:      String^ managedString = gcnew String("managed string");
   5:      // Note the double cast.
   6:      unmanagedString = (char*)(void*)Marshal::StringToHGlobalAnsi(managedString);
   7:  }
   8:  finally
   9:  {
  10:      // Don't forget to release. Note the ugly casts again.
  11:      Marshal::FreeHGlobal((IntPtr)(void*)unmanagedString);
  12:  }

And the new:

   1:  marshal_context^ context = gcnew marshal_context();
   2:  String^ managedString = gcnew String("managed string");
   3:  const char* unmanagedString = context->marshal_as<const char*>( managedString );
 

Much shorter, I’m sure you’ll agree. And neater – no need for all the icky, icky casting between different pointer types. And most importantly, I don’t have to explicitly release the char* – the marshal_context class keeps a reference to all the strings that were marshalled through it, and when it goes out of scope its destructor makes sure to release them all. Very efficient, all in all.

Static Constructor throws the same exception again and again

Here’s a little gotcha I ran into today – if you have code in a class’s static constructor that throws an exception, we will get a TypeInitializationException with the original exception as the InnerException – so far, nothing new.

However, if we keep on calling methods on that object, we’ll keep receiving TypeInitializationExceptions. If it cannot be initialized, it cannot be called. Every time we try, we’ll receive the exact same exception. However, the static ctor will not be called again. What appears to happen is that the CLR caches the TypeInitializationException object itself, InnerException included, and rethrows it whenever the type is called.

What are the ramifications? Well, we received an OutOfMemoryException in our static ctor, but the outer exception was caught and tried again. So we got an OutOfMemoryException again, even though the memory problem was behind us, which sent us down the wrong track of looking for persistent memory problems. Theoretically, it could also be a leak – the inner exception holding some sort of reference that is never released, but that’s an edge case.

Here’s some code to illustrate the problem. The output clearly shows that while we wait a second between calls, the inner exception contains the time of the original exception, not any subsequent calls. Debugging also shows that the static ctor is called only once.

   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:   
   6:          for (int i = 0; i < 5; i++)
   7:          {
   8:              try
   9:              {
  10:                  Thread.Sleep(1000);
  11:                  StaticClass.Method();
  12:   
  13:              }
  14:              catch (Exception ex)
  15:              {
  16:                  Console.WriteLine(ex.InnerException.Message);
  17:              }
  18:          }
  19:   
  20:          Console.ReadLine();
  21:      }
  22:  }
  23:   
  24:  static class StaticClass
  25:  {
  26:      static StaticClass()
  27:      {
  28:          throw new Exception("Exception thrown at " + DateTime.Now.ToString());
  29:      }
  30:   
  31:      public static void Method()
  32:      { }
  33:   
  34:  }

Upgrading all projects to .NET 3.5

A simple macro to change the Target Framework for a project from .NET 2.0 to .NET 3.5, hacked together in a few minutes. This will fail for C++/CLI projects, and possibly VB.NET projects (haven’t checked). Works fine for regular C# projects, as well as web projects:

 

For Each proj As Project In DTE.Solution.Projects
   Try
       proj.Properties.Item("TargetFramework").Value = 196613
       Debug.Print("Upgraded {0} to 3.5", proj.Name)
   Catch ex As Exception
       Debug.Print("Failed to upgrade {0} to 3.5", proj.Name)
   End Try

Next proj

Why 196613, you ask? Well, when I see such a number my first instinct is to feed it into calc.exe and switch it to hexadecimal. And I was right: 196613 in decimal converts to 0x00030005 – You can see the framework version hiding in there. Major version in the high word, minor in the low word. The previous TargetFramework number was 131072 – 0x00020000, or 2.0.

 

(Nitpickers might point out that I could simply set it to &30005 rather than messing with the obscure decimal number. They would be correct – but I got to this number through the debugger, so that’s how it will stay)

Sneaking past the SharePoint Usage Log

I’m writing a piece of code that regularly polls a MOSS server and checks several files. This can happen quite a few times a day, and this totally skews my Usage Reports for my sites.

Does anyone know of a way to tell MOSS to ignore calls made by a specific user, a specific IP (my code runs on a dedicated server), a specific UserAgent or whatever?

Any signs of life for the SharePoint Extensions for Visual Studio?

Has anything been released – or, in fact, talked about – since August’s release of the v1.1 CTP?

Haven’t done any web-part development in a while and wanted to get back in the game. I last used the v1.0 extensions, and was surprised that nothing much has changed in that field except for the CTP release, and even that can’t be downloaded – I just get a broken link.

Seeking advice – strong names and config files

I’ll use my blog for a bit of fishing for advice and guidance on an issue that’s been bugging me.

We’ve been moving towards using strong names on all of our assemblies. The benefits are obvious, and it’s a must before we deploy to clients out in the wild.

The problem is that we have several different processes running, each with its own app.config or web.config file. These config files contain references to custom configuration sections, whether they’re application configuration, Enterprise Library extensions or whatnot. Seeing as my DLLs are signed, I have to use the fully qualified assembly name in all my references. This means that in a nightly build scenario where my version number is bumped continuously, I have to change 5-6 references in 5-6 configuration files with every build.

Doing this kind of string manipulation on a large scale scares me, since it can break, or we miss something. I’ve tried using and directives, but they require a specific version to point to as well.

 

I’m sure I’m not the first person to encounter this problem. What are the solutions that you use to bypass this? Scripts as part of the automated installation? Moving all configuration sections to a separate assembly whose version is static? What’s the least painful way to manage this?