Serialization and deserialization in Wf

Source: Internet
Author: User

There are two methods for workflow in WF: code mode and code mode. the xoml mode, the two can be converted to each other, which is the serialization provided in WF.
And deserialization support. The following important classes in the WF framework:

  • The workflowmarkupserializer class is the serialization base type used in the serialization infrastructure. This type provides some basic services for serialization rules. This class
    The serialize method of can create a markup file from the workflow model in the memory, and deserialize is its opposite operation.
  • The activitymarkupserializer class inherits from the workflowmarkupserializer class. This type is used to serialize all basic activities. Basic activities are activities other than compound activities.
  • The compositeactivitymarkupserializer class inherits from the activitymarkupserializer class, which provides serialization for composite activities. Compositeactivitymarkupserializer
    More methods are added to process subactivities. subactivities can be serialized using their own serialization providers.

1. In the following example, we first create a workflow using Code. The Code is as follows:

Private Static activity createworkflow () {carybaseworkflow workflow = new carybaseworkflow (); workflow. name = "caryworkflow"; ifelseactivity ifelse = new ifelseactivity ("ifelseactivity1"); ifelsebranchactivity branch = new ifelsebranchactivity ("ifelsebranchactivity1 "); // 2.add a rule condition to the branch ruleconditionreference rulecondition = new ruleconditionreference (); rulecondition. conditionname = "condition"; branch. condition = rulecondition; // 0.1.code condition // codecondition condition = new codecondition (); // activitybind bind = new activitybind ("caryworkflow", "condition"); // condition. setbinding (codecondition. conditionevent, bind); // branch. condition = condition; caryprintactivity = new caryprintactivity (); caryprintactivity. name = "caryprintactivity1"; caryprintactivity. message = "the number you entered is greater than 0"; branch. activities. add (caryprintactivity); ifelse. activities. add (Branch); branch = new ifelsebranchactivity ("ifelsebranchactivity2"); caryprintactivity = new caryprintactivity (); caryprintactivity. name = "caryprintactivity2"; caryprintactivity. message = "the number you entered is less than or equal to 0"; branch. activities. add (caryprintactivity); ifelse. activities. add (Branch); workflow. activities. add (ifelse); Return workflow ;}
For the carybaseworkflow class and custom activity caryprintactivity, see the article "workflow creation mode without code.
 

2. serialize the in-memory workflow to the file. The Code is as follows:

private static void SerializeWorkflow(Activity workflow, String fileName){    try    {        using (XmlWriter xmlWriter = XmlWriter.Create(fileName))        {            WorkflowMarkupSerializer markupSerializer= new WorkflowMarkupSerializer();            markupSerializer.Serialize(xmlWriter, workflow);        }     }     catch (Exception e)     {            Console.WriteLine("Exception during serialization: {0}",e.Message);     } }
 

3. Then we can use the following code for testing:

Static void main (string [] ARGs) {activity workflow = createworkflow (); serializeworkflow (workflow, "serializedworkflow. xoml "); Using (workflowruntime runtime = new workflowruntime () {autoresetevent waithandle = new autoresetevent (false); runtime. workflowcompleted + = delegate (Object sender, workflowcompletedeventargs e) {waithandle. set () ;}; console. writeline ("START workflow execution"); dictionary <string, Object> paras = new dictionary <string, Object> (); paras. add ("Number", 6); try {// 0. serialezeworkflow demo xmlreader reader = xmlreader. create ("serializedworkflow. xoml "); workflowinstance instance = runtime. createworkflow (reader, null, paras );
Instance. Start ();

} Catch (workflowvalidationfailedexception e) {foreach (validationerror error in E. errors) {console. writeline (error. errortext) ;}} catch (exception e) {console. writeline (E. message);} waithandle. waitone (); console. writeline ("workflow execution completed \ n \ r ");}}
In the above test code, we first use the code to create a workflow, then serialize the workflow to serializedworkflow. xoml, and finally use the workflow.
 
4. In the above example, we directly load serializedworkflow. xoml into the runtime so that the workflow can be verified only when the workflow instance is executed.
We can also compile the workflow into the DLL so that we can check the type of the workflow during compilation.
. A new type is created when the workflow is compiled. Therefore, add the following code in createworkflow to set the X: class attribute.
workflow.Activities.Add(ifElse);//1.Compile Demoworkflow.SetValue(WorkflowMarkupSerializer.XClassProperty, "CaryWF.CompileWorkflowClass");return workflow;
. The following describes how to compile a workflow:

Private Static void compileworkflow (string filename, string assemblyname) {workflowcompiler compiler = new workflowcompiler (); workflowcompilerparameters parameters = new workflowcompilerparameters (); parameters. outputassembly = assemblyname; parameters. referencedassemblies. add ("carywflib. DLL "); // 2.add. rules file for this workflow as a resource // The format of the rule should be fixed to such parameters. embeddedresources. add ("carywf. compileworkflowclass. rules "); workflowcompilerresults Results = compiler. compile (parameters, filename); If (results. errors. count> 0) {foreach (system. codedom. compiler. compilererror error in results. errors) {console. writeline ("Compilation error: Row {0 }:{ 1}", error. line, error. errortext );}}}
. Note that when the rule file is added as an embedded resource of the Assembly, the naming method of the rule must include the namespace and workflow class.
4.4.in addition to using the workflowcompilerclass to compile the workflow, we can also use the command line's formula wfc.exe. The format is as follows:
 wfc.exe SerializedWorkflow.xoml /target:assembly 
/debug:- /resource:CaryWF.CompileWorkflowClass.rules
/reference:CaryWFLib.dll /out:CaryCompile.dll
 
5. test again. The Code is as follows:
Static void main (string [] ARGs) {activity workflow = createworkflow (); serializeworkflow (workflow, "serializedworkflow. xoml "); // 1. compile demo compileworkflow ("serializedworkflow. xoml "," carycompile. DLL "); Using (workflowruntime runtime = new workflowruntime () {autoresetevent waithandle = new autoresetevent (false); runtime. workflowcompleted + = delegate (Object sender, workflowcompletedeventargs e) {waithandle. set () ;}; console. writeline ("START workflow execution"); dictionary <string, Object> paras = new dictionary <string, Object> (); paras. add ("Number", 6); try {type workflowtype = type. getType ("carywf. compileworkflowclass, carycompile "); workflowinstance instance = runtime. createworkflow (workflowtype, paras); instance. start ();} catch (exception e) {console. writeline (E. message);} waithandle. waitone (); console. writeline ("workflow execution completed \ n \ r ");}}
Because the workflow is compiled, the catch does not need to capture the specific exceptions that failed verification.
 
6. The above code serializes the workflows in the memory to the xoml file. We can also deserialize them.
private static Activity DeserializeFromMarkup(String fileName){    Activity workflow = null;    try    {                        ServiceContainer container = new ServiceContainer();        TypeProvider provider = new TypeProvider(container);                     provider.AddAssembly(typeof(CaryWFLib.CaryBaseWorkflow).Assembly);        container.AddService(typeof(ITypeProvider), provider);                DesignerSerializationManager dsm= new DesignerSerializationManager(container);        using (dsm.CreateSession())        {            using (XmlReader xmlReader = XmlReader.Create(fileName))            {                //deserialize the workflow from the XmlReader                WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();                workflow = markupSerializer.Deserialize(dsm, xmlReader) as Activity;                if (dsm.Errors.Count > 0)                {                    foreach (WorkflowMarkupSerializationException error in dsm.Errors)                    {                        Console.WriteLine("Deserialization error: {0}", error);                    }                }            }        }    }    catch (Exception e)    {        Console.WriteLine("Exception during deserialization: {0}",e.Message);    }    return workflow;}
This is a brief introduction.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.