Gotta Compile the .XAMLX file before it will work right with CSharpExpressions

May 25, 2013 at 10:26 PM
Edited May 25, 2013 at 10:29 PM
Your workflow will fail if it includes C# statements

From the UnitTesting Samples:
Microsoft.Activities.UnitTesting\C#\MathServiceLibrary.Tests\IncrementServiceTest.cs

instead of creating the host like this:

line: 83
// Setup the host
        var host = WorkflowInvokerTest.Create(xamlInjector.GetWorkflowService().Body);
        host.Extensions.Add(stubExtension);
Use this:
//Compile the Expressions First:
// Setup the host
        var activity = xamlInjector.GetWorkflowService().Body;
        WorkflowCompiler.CompileExpressions(activity);
        var host = WorkflowInvokerTest.Create(activity);
        host.Extensions.Add(stubExtension);
 public static class WorkflowCompiler
    {
        public static void CompileExpressions(Activity activity)
        {
            // activityName is the Namespace.Type of the activity that contains the
            // C# expressions.
            string activityName = activity.GetType().ToString();

            // Split activityName into Namespace and Type.Append _CompiledExpressionRoot to the type name
            // to represent the new type that represents the compiled expressions.
            // Take everything after the last . for the type name.
            string activityType = activityName.Split('.').Last() + "_CompiledExpressionRoot";
            // Take everything before the last . for the namespace.
            string activityNamespace = string.Join(".", activityName.Split('.').Reverse().Skip(1).Reverse());

            // Create a TextExpressionCompilerSettings.
            TextExpressionCompilerSettings settings = new TextExpressionCompilerSettings
            {
                Activity = activity,
                Language = "C#",
                ActivityName = activityType,
                ActivityNamespace = activityNamespace,
                RootNamespace = null,
                GenerateAsPartialClass = false,
                AlwaysGenerateSource = true,
                ForImplementation = false
            };

            // Compile the C# expression.
            TextExpressionCompilerResults results =
                new TextExpressionCompiler(settings).Compile();

            // Any compilation errors are contained in the CompilerMessages.
            if (results.HasErrors)
            {
                throw new Exception("Compilation failed.");
            }

            // Create an instance of the new compiled expression type.
            ICompiledExpressionRoot compiledExpressionRoot =
                Activator.CreateInstance(results.ResultType,
                    new object[] { activity }) as ICompiledExpressionRoot;

            // Attach it to the activity.
            CompiledExpressionInvoker.SetCompiledExpressionRoot(
                activity, compiledExpressionRoot);
        }

    }