(WF4) Adding VB namespace Imports to your workflow programmatically

These questions (paraphrased) have come up a bunch of times so it’s not that hard to find the answer, but I just rediscovered them so it’s on topic for today.

“I want to add a namespace to the Imports designer automatically at design time, so the user doesn’t have to do it manually. How can I do that?”

“I modified a workflow using C# code to add/remove VB expressions. None of my VB expressions work at runtime because it can’t resolve the types involved (e.g. System.Collections.ObjectModel.Collection)”

…and https://support.microsoft.com/kb/2015702 etc.

The code’s pretty simple:

But needs one word of explanation. What is ‘rootObject’? RootObject is the root of your workflow definition, i.e. it should usually be the ActivityBuilder object. But in the case of a workflow Service (I guess you’re generating a XAMLX file?) there is no ActivityBuilder, and I believe it would either be the Service… I think (unchecked fact).

        /// <summary>
        /// Useful to patch up your non-designer generated workflow with any missing VB namespaces it needs.
        /// </summary>
        public static void AddVBNamespaceSettings(object rootObject, params Type[] types)
        {
            var vbsettings = VisualBasic.GetSettings(rootObject);
            if (vbsettings == null)
            {
                vbsettings = new VisualBasicSettings();
            }

 
            foreach (Type t in types)
            {
                vbsettings.ImportReferences.Add(
                    new VisualBasicImportReference
                    {
                        Assembly = t.Assembly.GetName().Name,
                        Import = t.Namespace
                    });
            }
 
     VisualBasic.SetSettings(rootObject, vbsettings);
        }

You can also use it on a manually constructed DynamicActivity object, if e.g. you just want to build a DynamicActivity for execution and skip ActivityBuilder.

Other examples:

There’s a more extensive example by Frank Holden on the forums which does a little extra stuff, it’s designed to monitoring assemblies added as assembly references to your workflow in a rehosted app.