Partilhar via


How to Generate Code Using Custom Activities

You can generate code for a custom activity by using a type derived from ActivityCodeGenerator or CompositeActivityCodeGenerator and associating it with your custom activity by using the ActivityCodeGeneratorAttribute. You must override GenerateCode, which will be called during workflow compilation and allow you to add additional code to the workflow partial class that is generated by the compiler, in the form of CodeDOM, before it is passed on to the C# compiler. This scenario can be useful for Web service activities, where you can generate a proxy class on the fly, or other scenarios where the activity needs to emit code based on its configuration for use at run time.

The following example shows how to generate code for your custom activity.

public override void GenerateCode(CodeGenerationManager manager, object obj)
{
    if (manager == null)
    {
        throw new ArgumentNullException("The CodeGenerationManager object is null.");
    }

    if (obj == null)
    {
        throw new ArgumentNullException("The object to generate code for is null.");
    }

    // Cast obj to your custom activity for access to its members.
    Activity1 customActivity = obj as Activity1;

    if (customActivity == null)
    {
        throw new ArgumentException("The obj variable cannot be cast to the Activity type.");
    }

    // Retrieve a type provider object.
    ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));

    if (typeProvider == null)
    {
        throw new InvalidOperationException();
    }

    // TODO: Use types in the System.CodeDOM namespace to generate 
    // code. 
}

To associate your custom code generator with your custom activity, you must decorate your activity with the ActivityCodeGeneratorAttribute as shown in the following example.

[ActivityCodeGenerator(typeof(CustomCodeGenerator))]

For more information about using CodeDOM, see Using the CodeDOM.

Note

You do not have to use CodeDomProvider or any of the CodeDOM compiler types in the System.CodeDOM.Compiler namespace when using CodeDOM in your custom ActivityCodeGenerator implementation.

See Also

Concepts

Creating Custom Activities

Other Resources

Developing Windows Workflow Foundation Activities