예제 #1
0
파일: Form1.cs 프로젝트: juansanti/Solution
        private void EditarReglasAutorizaciones(Type type, string fileName)
        {
            // Rules file name to serialize to and deserialize from

            RuleSet ruleSet = null;

            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();

            if (Existe(fileName))
            {
                ruleSet = GetRuleSetFromFile(fileName);
            }

            // Create a RuleSet that works with Orders (just another .net Object)
            RuleSetDialog ruleSetDialog = new RuleSetDialog(type, null, ruleSet);

            // Show the RuleSet Editor
            DialogResult result = ruleSetDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                ruleSet = ruleSetDialog.RuleSet;
                // Serialize to a .rules file

                XmlWriter rulesWriter = XmlWriter.Create(fileName);
                serializer.Serialize(rulesWriter, ruleSet);
                rulesWriter.Close();
            }
        }
예제 #2
0
        private RuleSet getRuleSet(string content)
        {
            object objectRuleSet = null;

            // Deserialize the .rules file that contains one RuleSet
            StringReader sr = new StringReader(content);
            using (XmlTextReader reader = new XmlTextReader(sr))
            {
                WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
                objectRuleSet = serializer.Deserialize(reader);
            }

            RuleSet ruleSet = null;
            if (objectRuleSet != null && objectRuleSet is RuleSet)
            {
                ruleSet = (RuleSet)objectRuleSet;
            }
            RuleDefinitions ruleDef = null;
            if (objectRuleSet != null && objectRuleSet is RuleDefinitions)
            {
                ruleDef = (RuleDefinitions)objectRuleSet;
            }
            if (ruleDef == null && ruleSet == null && objectRuleSet != null)
            {
                // Throw an exception if file does not contain any RuleSet
                throw new InvalidOperationException("RuleSet is null, objectRuleSet.Type: " + objectRuleSet.GetType().FullName);
            }
            if (ruleDef.RuleSets != null && ruleDef.RuleSets.Count > 0)
            {
                ruleSet = ruleDef.RuleSets[0];
            }
            return ruleSet;
        }
예제 #3
0
 public RuleSet Load(string filename)
 {
     using (XmlTextReader reader = new XmlTextReader(filename))
     {
         WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
         return serializer.Deserialize(reader) as RuleSet;
     }
 }
예제 #4
0
 public void Save(RuleSet ruleset, string filename)
 {
     using (XmlTextWriter writer = new XmlTextWriter(filename, null))
     {
         WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
         serializer.Serialize(writer, ruleset);
     }
 }
 // �����́A�A�����[�h (�ۑ�) ���ɌĂ΂�܂�
 public override void Flush()
 {
     IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
     Activity rootActivity = (Activity)host.RootComponent;
     XmlTextWriter xmlWriter = new XmlTextWriter(this.xomlfile, Encoding.Default);
     WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
     xomlSerializer.Serialize(xmlWriter, rootActivity);
     xmlWriter.Close();
 }
예제 #6
0
        public RuleSet GetRuleSetFromFile(string fileName)
        {
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();

            XmlTextReader rulesReader = new XmlTextReader(fileName);

            var ruleSet = (RuleSet)serializer.Deserialize(rulesReader);
            rulesReader.Close();

            return ruleSet;
        }
        // �����́A���[�h���ɌĂ΂�܂�
        protected override void PerformLoad(IDesignerSerializationManager serializationManager)
        {
            base.PerformLoad(serializationManager);

            XmlReader reader = new XmlTextReader(this.xomlfile);
            WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
            Activity rootActivity = (Activity)xomlSerializer.Deserialize(reader);
            reader.Close();

            NestedActivityLoad(rootActivity);
        }
 protected internal override Activity CreateInstance(XmlReader workflowDefinitionReader, XmlReader rulesReader)
 {
     if (workflowDefinitionReader == null)
     {
         throw new ArgumentNullException("workflowDefinitionReader");
     }
     Activity activity = null;
     ValidationErrorCollection errors = new ValidationErrorCollection();
     ServiceContainer container = new ServiceContainer();
     ITypeProvider service = base.Runtime.GetService<ITypeProvider>();
     if (service != null)
     {
         container.AddService(typeof(ITypeProvider), service);
     }
     DesignerSerializationManager manager = new DesignerSerializationManager(container);
     try
     {
         using (manager.CreateSession())
         {
             WorkflowMarkupSerializationManager serializationManager = new WorkflowMarkupSerializationManager(manager);
             activity = new WorkflowMarkupSerializer().Deserialize(serializationManager, workflowDefinitionReader) as Activity;
             if ((activity != null) && (rulesReader != null))
             {
                 object obj2 = new WorkflowMarkupSerializer().Deserialize(serializationManager, rulesReader);
                 activity.SetValue(ConditionTypeConverter.DeclarativeConditionDynamicProp, obj2);
             }
             foreach (object obj3 in manager.Errors)
             {
                 if (obj3 is WorkflowMarkupSerializationException)
                 {
                     errors.Add(new ValidationError(((WorkflowMarkupSerializationException) obj3).Message, 0x15b));
                 }
                 else
                 {
                     errors.Add(new ValidationError(obj3.ToString(), 0x15b));
                 }
             }
         }
     }
     catch (Exception exception)
     {
         errors.Add(new ValidationError(exception.Message, 0x15b));
     }
     if (errors.HasErrors)
     {
         throw new WorkflowValidationFailedException(ExecutionStringManager.WorkflowValidationFailure, errors);
     }
     return activity;
 }
예제 #9
0
파일: Loader.cs 프로젝트: ssickles/archive
        public void PerformFlush(IDesignerHost host)
        {
            if (host != null && host.RootComponent != null)
            {
                Activity service = host.RootComponent as Activity;

                if (service != null)
                {
                    using (XmlWriter writer = XmlWriter.Create(this.xamlFile))
                    {
                        WorkflowMarkupSerializer xamlSerializer = new WorkflowMarkupSerializer();
                        xamlSerializer.Serialize(writer, service);
                    }
                }
            }
        }
        public static Activity LoadXomlDocument(WorkflowMarkupSerializationManager xomlSerializationManager, XmlReader textReader, string fileName)
        {
            if (xomlSerializationManager == null)
                throw new ArgumentNullException("xomlSerializationManager");

            Activity rootActivity = null;
            try
            {
                xomlSerializationManager.Context.Push(fileName);
                rootActivity = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, textReader) as Activity;
            }
            finally
            {
                xomlSerializationManager.Context.Pop();
            }

            return rootActivity;
        }
        // This function will create a new root activity definition tree by deserializing the xoml and the rules file.
        protected internal override Activity CreateInstance(XmlReader workflowDefinitionReader, XmlReader rulesReader)
        {
            if (workflowDefinitionReader == null)
                throw new ArgumentNullException("workflowDefinitionReader");

            Activity root = null;
            ValidationErrorCollection errors = new ValidationErrorCollection();
            ServiceContainer serviceContainer = new ServiceContainer();
            ITypeProvider typeProvider = this.Runtime.GetService<ITypeProvider>();
            if (typeProvider != null)
                serviceContainer.AddService(typeof(ITypeProvider), typeProvider);

            DesignerSerializationManager manager = new DesignerSerializationManager(serviceContainer);
            try
            {
                using (manager.CreateSession())
                {
                    WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                    root = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, workflowDefinitionReader) as Activity;
                    if (root != null && rulesReader != null)
                    {
                        object rules = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, rulesReader);
                        root.SetValue(ConditionTypeConverter.DeclarativeConditionDynamicProp, rules);
                    }

                    foreach (object error in manager.Errors)
                    {
                        if (error is WorkflowMarkupSerializationException)
                            errors.Add(new ValidationError(((WorkflowMarkupSerializationException)error).Message, ErrorNumbers.Error_SerializationError));
                        else
                            errors.Add(new ValidationError(error.ToString(), ErrorNumbers.Error_SerializationError));
                    }
                }
            }
            catch (Exception e)
            {
                errors.Add(new ValidationError(e.Message, ErrorNumbers.Error_SerializationError));
            }

            if (errors.HasErrors)
                throw new WorkflowValidationFailedException(ExecutionStringManager.WorkflowValidationFailure, errors);

            return root;
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            XmlReader reader = new XmlTextReader(RuleFilePath);
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            RuleDefinitions ruleDef = (RuleDefinitions)serializer.Deserialize(reader);
            reader.Close();

            // ルートアクティビティを取得
            Activity root = this;
            while (root.Parent != null)
                root = root.Parent;

            for (int i = 0; i < ruleDef.RuleSets.Count; i++)
            {
                RuleSet myRuleSet = ruleDef.RuleSets[i];
                RuleEngine ruleEng = new RuleEngine(myRuleSet, root.GetType());
                ruleEng.Execute(root, executionContext);
            }

            return base.Execute(executionContext);
        }
예제 #13
0
 private RuleSet GetRuleSetFromFile(string ruleSetName, string ruleSetFileName)
 {
     XmlTextReader routingTableDataFileReader = new XmlTextReader(ruleSetFileName);
     RuleDefinitions ruleDefinitions = null;
     if (routingTableDataFileReader != null)
     {
         try
         {
             WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
             ruleDefinitions = serializer.Deserialize(routingTableDataFileReader) as RuleDefinitions;
         }
         catch (Exception e)
         {
             throw new ApplicationException("The specified file is not a valid rules file \"" + ruleSetFileName + "\"", e);
         }
         if (ruleDefinitions != null)
         {
             try
             {
                 RuleSet ruleSet = ruleDefinitions.RuleSets[ruleSetName];
                 return ruleSet;
             }
             catch (Exception e)
             {
                 throw new ApplicationException("The specified rules file does not have the ruleset with name : " + ruleSetName, e);
             }
         }
         else
         {
             throw new ApplicationException("There are no rulesets inside rules file");
         }
     }
     else
     {
         throw new ApplicationException("Can't find a valid file at the specified location. " + ruleSetFileName);
     }
 }
 internal IList Deserialize(IServiceProvider serviceProvider)
 {
     IList list2;
     DesignerSerializationManager manager = new LocalDesignerSerializationManager(this, serviceProvider);
     using (manager.CreateSession())
     {
         EventHandler<WorkflowMarkupElementEventArgs> handler = null;
         ArrayList list = new ArrayList();
         WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
         XmlTextReader reader = new XmlTextReader(this.serializedXmlString, XmlNodeType.Element, null);
         reader.MoveToElement();
     Label_0042:
         if (!reader.Read())
         {
             list2 = list;
         }
         else
         {
             if (handler == null)
             {
                 handler = delegate (object sender, WorkflowMarkupElementEventArgs eventArgs) {
                     if ((eventArgs.XmlReader.LookupNamespace(eventArgs.XmlReader.Prefix) == "http://schemas.microsoft.com/winfx/2006/xaml") && (xomlSerializationManager.Context.Current is Activity))
                     {
                         WorkflowMarkupSerializationHelpers.ProcessDefTag(xomlSerializationManager, eventArgs.XmlReader, xomlSerializationManager.Context.Current as Activity, true, string.Empty);
                     }
                 };
             }
             xomlSerializationManager.FoundDefTag += handler;
             object obj2 = new WorkflowMarkupSerializer().DeserializeObject(xomlSerializationManager, reader);
             if (obj2 == null)
             {
                 throw new InvalidOperationException(DR.GetString("InvalidOperationDeserializationReturnedNonActivity", new object[0]));
             }
             if (obj2 is Activity)
             {
                 (obj2 as Activity).UserData.Remove(UserDataKeys.CustomActivity);
             }
             list.Add(obj2);
             goto Label_0042;
         }
     }
     return list2;
 }
예제 #15
0
        private void LoadExistingScheduleType(Guid scheduleTypeId, Type scheduleType, bool isDynamic, Activity rootActivity)
        {
            if (rootActivity == null)
                throw new InvalidOperationException();

            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                using (XmlWriter xmlWriter = Helpers.CreateXmlWriter(stringWriter))
                {
                    WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
                    serializer.Serialize(xmlWriter, rootActivity);
                    string fileName = null;
                    string md5Digest = null;
                    Attribute[] attributes = scheduleType.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false) as Attribute[];
                    if (attributes != null && attributes.Length == 1)
                    {
                        fileName = ((WorkflowMarkupSourceAttribute)attributes[0]).FileName;
                        md5Digest = ((WorkflowMarkupSourceAttribute)attributes[0]).MD5Digest;
                    }

                    this.controllerConduit.ScheduleTypeLoaded(this.programId, scheduleTypeId, scheduleType.Assembly.FullName, fileName, md5Digest, isDynamic, scheduleType.FullName, scheduleType.Name, stringWriter.ToString());
                }
            }
        }
        System.Workflow.ComponentModel.Activity DeSerizalizeDefinition(byte[] workflowDefinition, byte[] ruleDefinition)
        {
            System.IO.Stream definitionStream = null;
            System.IO.Stream ruleStream = null;

            System.Xml.XmlReader definitionReader = null;
            System.Xml.XmlReader ruleReader = null;

            try
            {
                definitionStream = new System.IO.MemoryStream(workflowDefinition);
                definitionStream.Position = 0;
                definitionReader = System.Xml.XmlReader.Create(definitionStream);

                if (ruleDefinition != null)
                {
                    ruleStream = new System.IO.MemoryStream(ruleDefinition);
                    ruleStream.Position = 0;
                    ruleReader = System.Xml.XmlReader.Create(ruleStream);
                }

                System.Workflow.ComponentModel.Activity root = null;
                ValidationErrorCollection errors = new ValidationErrorCollection();
                ServiceContainer serviceContainer = new ServiceContainer();

                if (this.typeProvider != null)
                {
                    serviceContainer.AddService(typeof(ITypeProvider), this.typeProvider);
                }

                DesignerSerializationManager manager = new DesignerSerializationManager(serviceContainer);
                try
                {
                    using (manager.CreateSession())
                    {
                        WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                        root = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, definitionReader) as System.Workflow.ComponentModel.Activity;

                        if (root != null && ruleReader != null)
                        {
                            object rules = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, ruleReader);
                            root.SetValue(System.Workflow.Activities.Rules.RuleDefinitions.RuleDefinitionsProperty, rules);
                        }

                        foreach (object error in manager.Errors)
                        {
                            if (error is WorkflowMarkupSerializationException)
                            {
                                errors.Add(new ValidationError(((WorkflowMarkupSerializationException) error).Message, 1));
                            }
                            else
                            {
                                errors.Add(new ValidationError(error.ToString(), 1));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    errors.Add(new ValidationError(e.Message, 1));
                }

                if (errors.HasErrors)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WorkflowValidationFailedException(SR2.GetString(SR2.WorkflowValidationFailed), errors));
                }

                return root;
            }
            finally
            {
                if (definitionStream != null)
                {
                    definitionStream.Dispose();
                }
                if (ruleStream != null)
                {
                    ruleStream.Dispose();
                }
            }
        }
 public PropertySegmentSerializer(WorkflowMarkupSerializer containedSerializer)
 {
     this.containedSerializer = containedSerializer;
 }
        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Range cell;

            RuleSet myRuleset = new RuleSet("RuleSet1");

            // Define property and activity reference expressions through CodeDom functionality
            CodeThisReferenceExpression refexp = new CodeThisReferenceExpression();
            CodePropertyReferenceExpression refTotalCost = new CodePropertyReferenceExpression(refexp, "totalCost");
            CodePropertyReferenceExpression refParamCategory = new CodePropertyReferenceExpression(refexp, "paramCategory");
            CodePropertyReferenceExpression refParamPrivilege = new CodePropertyReferenceExpression(refexp, "paramPrivilege");

            // Example :
            // IF paramCategory == 3
            // THEN totalCost = totalCost + 300

            for (int row = 4; row <= 8; row++)
            {
                cell = (Excel.Range)this.Cells[row, 2];
                if (String.IsNullOrEmpty((string)cell.Value2))
                    break;
                Rule myRule = new Rule("Rule" + row);
                myRuleset.Rules.Add(myRule);

                // Example :
                // paramCategory == 3
                CodeBinaryOperatorExpression ruleCondition = new CodeBinaryOperatorExpression();
                if ((string)cell.Value2 == "種別 (category)")
                    ruleCondition.Left = refParamCategory;
                else if ((string)cell.Value2 == "特典 (privilige)")
                    ruleCondition.Left = refParamPrivilege;
                ruleCondition.Operator = CodeBinaryOperatorType.ValueEquality;
                cell = (Excel.Range)this.Cells[row, 3];
                ruleCondition.Right = new CodePrimitiveExpression((int)(double)cell.Value2);
                myRule.Condition = new RuleExpressionCondition(ruleCondition);

                // Example :
                // totalCost = totalCost + 300
                CodeAssignStatement ruleAction = new CodeAssignStatement();
                ruleAction.Left = refTotalCost;
                CodeBinaryOperatorExpression actionRight = new CodeBinaryOperatorExpression();
                actionRight.Left = refTotalCost;
                cell = (Excel.Range)this.Cells[row, 4];
                if((string)cell.Value2 == "+")
                    actionRight.Operator = CodeBinaryOperatorType.Add;
                else if ((string)cell.Value2 == "-")
                    actionRight.Operator = CodeBinaryOperatorType.Subtract;
                else if ((string)cell.Value2 == "*")
                    actionRight.Operator = CodeBinaryOperatorType.Multiply;
                else if ((string)cell.Value2 == "/")
                    actionRight.Operator = CodeBinaryOperatorType.Divide;
                cell = (Excel.Range)this.Cells[row, 5];
                actionRight.Right = new CodePrimitiveExpression((int)(double)cell.Value2);
                ruleAction.Right = actionRight;
                myRule.ThenActions.Add(new RuleStatementAction(ruleAction));
            }

            // 必要に応じ、RuleValidation オブジェクトを使ってチェック!
            // (今回は省略 . . . . . . .)

            // RuleDefinitions を設定して保存
            RuleDefinitions ruleDef = new RuleDefinitions();
            ruleDef.RuleSets.Add(myRuleset);
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            cell = (Excel.Range) this.Cells[11, 2];
            XmlTextWriter writer = new XmlTextWriter((string) cell.Value2, System.Text.Encoding.Unicode);
            serializer.Serialize(writer, ruleDef);
            writer.Close();

            // ここでは、すぐにコンパイルして実行
            // (Custom WorkflowRuntime Service と Custom Policy Activity を作成して、データベースなど独自の Rule Cache を作成することも可能 . . .)

            MessageBox.Show("ルールを反映しました");
        }
        internal IList Deserialize(IServiceProvider serviceProvider)
        {
            DesignerSerializationManager serializationManager = new LocalDesignerSerializationManager(this, serviceProvider);
            using (serializationManager.CreateSession())
            {
                ArrayList objects = new ArrayList();
                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(serializationManager);
                XmlTextReader reader = new XmlTextReader(this.serializedXmlString, XmlNodeType.Element, null);
                reader.MoveToElement();
                do
                {
                    if (!reader.Read())
                        return objects;

                    xomlSerializationManager.FoundDefTag += delegate(object sender, WorkflowMarkupElementEventArgs eventArgs)
                    {
                        if (eventArgs.XmlReader.LookupNamespace(eventArgs.XmlReader.Prefix) == StandardXomlKeys.Definitions_XmlNs &&
                            xomlSerializationManager.Context.Current is Activity
                            )
                            WorkflowMarkupSerializationHelpers.ProcessDefTag(xomlSerializationManager, eventArgs.XmlReader, xomlSerializationManager.Context.Current as Activity, true, string.Empty);
                    };

                    WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
                    object activityDecl = xomlSerializer.DeserializeObject(xomlSerializationManager, reader);
                    if (activityDecl == null)
                        throw new InvalidOperationException(DR.GetString(DR.InvalidOperationDeserializationReturnedNonActivity));
                    if (activityDecl is Activity)
                        (activityDecl as Activity).UserData.Remove(UserDataKeys.CustomActivity);
                    objects.Add(activityDecl);
                } while (true);
            }
        }
예제 #20
0
파일: Program.cs 프로젝트: ssickles/archive
        static void Main(string[] args)
        {

            Validator validator = (Validator)Activator.CreateInstance(typeof(Validator));
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            DesignerSerializationManager serializationManager = new DesignerSerializationManager();

            using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    Console.WriteLine("Workflow completed.");
                    waitHandle.Set();
                };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };

                //
                // Create queue workflow programmatically
                //
                Console.WriteLine("Creating workflow.");
                SequentialWorkflowActivity workflow = new SequentialWorkflowActivity();
                workflow.Name = "Programmatically created workflow";
                workflow.Description = "Programmatically created workflow for XAML activation";

                // Add Queue activity
                QueueActivity queueActivity = new QueueActivity();
                queueActivity.Name = "QueueActivity1";

                // Enqueue data
                queueActivity.NameQueue.Enqueue("Queue item 1");
                queueActivity.NameQueue.Enqueue("Queue item 2");
                queueActivity.NameQueue.Enqueue("Queue item 3");
                workflow.Activities.Add(queueActivity);

                // Add Stack activity
                StackActivity stackActivity = new StackActivity();
                stackActivity.Name = "StackActivity1";

                // Push data
                stackActivity.NameStack.Push("Stack item 1");
                stackActivity.NameStack.Push("Stack item 2");
                stackActivity.NameStack.Push("Stack item 3");
                workflow.Activities.Add(stackActivity);

                //
                // Serialize workflow to XAML file
                //
                Console.WriteLine("Serializing workflow to file.");
                using (XmlWriter writer = XmlWriter.Create(workflowFilename))
                {
                    using (serializationManager.CreateSession())
                    {
                        serializer.Serialize(serializationManager, writer, workflow);
                        if (serializationManager.Errors.Count > 0)
                        {
                            Console.WriteLine(String.Format("There were {0} errors during serialization", serializationManager.Errors.Count));
                            return;
                        }
                    }
                }

                //
                // Create workflow instance from file
                //
                Console.WriteLine("Deserializing workflow from file.");
                WorkflowInstance workflowInstance;
                using (XmlReader reader = XmlReader.Create(workflowFilename))
                {
                    try
                    {
                        workflowInstance = workflowRuntime.CreateWorkflow(reader);
                    }
                    catch (WorkflowValidationFailedException e)
                    {
                        Console.WriteLine("Validation errors found.  Exiting.");
                        foreach (ValidationError validationError in e.Errors)
                        {
                            Console.WriteLine(validationError.ErrorText);
                        }
                        return;
                    }
                }

                //
                // Execute workflow
                //
                Console.WriteLine("Starting workflow.");
                workflowInstance.Start();
                waitHandle.WaitOne();
                workflowRuntime.StopRuntime();
            }
        }
        private static ArrayList CloneWorkflowChangeActions(ArrayList workflowChanges, Activity rootActivity)
        {
            if (workflowChanges == null)
                throw new ArgumentNullException("workflowChanges");

            if (rootActivity == null)
                throw new ArgumentNullException("rootActivity");

            string dynamicUpdateHistory = null;
            TypeProvider typeProvider = CreateTypeProvider(rootActivity);
            ServiceContainer serviceContainer = new ServiceContainer();
            serviceContainer.AddService(typeof(ITypeProvider), typeProvider);
            DesignerSerializationManager manager = new DesignerSerializationManager(serviceContainer);
            WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();

            ArrayList clonedWorkflowChanges = null;
            // serialize dynamic updates
            using (manager.CreateSession())
            {
                using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
                {
                    using (XmlWriter xmlWriter = Helpers.CreateXmlWriter(sw))
                    {
                        WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                        xomlSerializer.Serialize(xomlSerializationManager, xmlWriter, workflowChanges);
                        dynamicUpdateHistory = sw.ToString();
                    }
                }

                // deserialize those
                using (StringReader sr = new StringReader(dynamicUpdateHistory))
                {
                    using (XmlReader xmlReader = XmlReader.Create(sr))
                    {
                        WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                        clonedWorkflowChanges = xomlSerializer.Deserialize(xomlSerializationManager, xmlReader) as ArrayList;
                    }
                }
            }
            return clonedWorkflowChanges;
        }
        protected internal override bool ApplyTo(Activity rootActivity)
        {
            if (rootActivity == null)
                throw new ArgumentNullException("rootActivity");
            if (!(rootActivity is CompositeActivity))
                throw new ArgumentException(SR.GetString(SR.Error_RootActivityTypeInvalid), "rootActivity");

            CompositeActivity ownerActivity = rootActivity.TraverseDottedPathFromRoot(this.OwnerActivityDottedPath) as CompositeActivity;
            if (ownerActivity == null)
                return false;

            // !!!work around: 
            ownerActivity.DynamicUpdateMode = true;
            CompositeActivity addedActivityOwner = this.addedActivity.Parent;
            try
            {
                this.addedActivity.SetParent(ownerActivity);
                Activity clonedAddedActivity = this.addedActivity;
                if (!this.addedActivity.DesignMode)
                    clonedAddedActivity = this.addedActivity.Clone();
                // We need to serialize and deserialize in order to clone during design mode
                else
                {
                    TypeProvider typeProvider = WorkflowChanges.CreateTypeProvider(rootActivity);
                    ServiceContainer serviceContainer = new ServiceContainer();
                    serviceContainer.AddService(typeof(ITypeProvider), typeProvider);
                    DesignerSerializationManager manager = new DesignerSerializationManager(serviceContainer);
                    WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
                    string addedActivityText = string.Empty;
                    // serialize dynamic updates
                    using (manager.CreateSession())
                    {
                        using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
                        {
                            using (XmlWriter xmlWriter = Helpers.CreateXmlWriter(sw))
                            {
                                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                                xomlSerializer.Serialize(xomlSerializationManager, xmlWriter, this.addedActivity);
                                addedActivityText = sw.ToString();
                            }
                        }

                        // deserialize those
                        using (StringReader sr = new StringReader(addedActivityText))
                        {
                            using (XmlReader xmlReader = XmlReader.Create(sr))
                            {
                                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                                clonedAddedActivity = xomlSerializer.Deserialize(xomlSerializationManager, xmlReader) as Activity;
                            }
                        }
                    }
                    if (clonedAddedActivity == null)
                        throw new InvalidOperationException(SR.GetString(SR.Error_ApplyDynamicChangeFailed));
                }
                if (ownerActivity.WorkflowCoreRuntime != null)
                    ((IDependencyObjectAccessor)clonedAddedActivity).InitializeInstanceForRuntime(ownerActivity.WorkflowCoreRuntime);

                clonedAddedActivity.SetParent(null);
                ownerActivity.Activities.Insert(this.index, clonedAddedActivity);
            }
            finally
            {
                this.addedActivity.SetParent(addedActivityOwner);
                ownerActivity.DynamicUpdateMode = false;
            }
            return true;
        }
예제 #23
0
        /// <summary>
        /// 克隆一个实例
        /// </summary>
        /// <param name="WfRuntimeClone"></param>
        /// <param name="instanceClone"></param>
        /// <param name="WfRuntime"></param>
        /// <returns></returns>
        public static WorkflowInstance CloneWorkflowInstance(WorkflowRuntime WfRuntimeClone, WorkflowInstance instanceClone, WorkflowRuntime WfRuntime)
        {
            try
            {
                if (!WfRuntimeClone.IsStarted)
                {
                    WfRuntimeClone.StartRuntime();
                }
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(WfRuntimeClone, instanceClone.InstanceId);

                System.Workflow.Activities.StateMachineWorkflowActivity smworkflow = new StateMachineWorkflowActivity();
                smworkflow = workflowinstance.StateMachineWorkflow;
                RuleDefinitions ruleDefinitions = smworkflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions;
                WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();

                StringBuilder xoml = new StringBuilder();
                StringBuilder rule = new StringBuilder();
                XmlWriter xmlWriter = XmlWriter.Create(xoml);
                XmlWriter ruleWriter = XmlWriter.Create(rule);
                markupSerializer.Serialize(xmlWriter, smworkflow);

                if (ruleDefinitions != null)
                    markupSerializer.Serialize(ruleWriter, ruleDefinitions);

                xmlWriter.Close();
                ruleWriter.Close();

                StringReader readxoml = new StringReader(xoml.ToString());
                XmlReader readerxoml = XmlReader.Create(readxoml);
                WorkflowInstance instance;
                if (ruleDefinitions == null)
                    instance = WfRuntime.CreateWorkflow(readerxoml);
                else
                {
                    StringReader readrule = new StringReader(rule.ToString());
                    XmlReader readerrule = XmlReader.Create(readrule);
                    instance = WfRuntime.CreateWorkflow(readerxoml, readerrule, null);
                }

                instance.Start();
                return instance;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("CloneWorkflowInstance异常信息 :" + ex.ToString());
                throw new Exception(ex.Message);
            }

        }
 internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath)
 {
     foreach (string str in parameters.LibraryPaths)
     {
         if (!CheckPathName(str))
         {
             int num5 = 0x160;
             WorkflowCompilerError error = new WorkflowCompilerError(string.Empty, 0, 0, num5.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString("LibraryPathIsInvalid"), new object[] { str })) {
                 IsWarning = true
             };
             results.Errors.Add(error);
         }
     }
     IList<AuthorizedType> authorizedTypes = null;
     if (parameters.CheckTypes)
     {
         authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes();
         if (authorizedTypes == null)
         {
             ValidationError error2 = new ValidationError(SR.GetString("Error_ConfigFileMissingOrInvalid"), 0x178);
             results.Errors.Add(CreateXomlCompilerError(error2, parameters));
             return;
         }
     }
     ITypeProvider service = WorkflowCompilationContext.Current.ServiceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
     ArrayList list2 = new ArrayList();
     using (PDBReader reader = new PDBReader(localAssemblyPath))
     {
         foreach (Type type in service.LocalAssembly.GetTypes())
         {
             if (TypeProvider.IsAssignable(typeof(Activity), type) && !type.IsAbstract)
             {
                 string fileLocation = string.Empty;
                 WorkflowMarkupSourceAttribute[] customAttributes = (WorkflowMarkupSourceAttribute[]) type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false);
                 if ((customAttributes != null) && (customAttributes.Length > 0))
                 {
                     fileLocation = customAttributes[0].FileName;
                 }
                 else
                 {
                     ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                     if (constructor != null)
                     {
                         try
                         {
                             uint line = 0;
                             uint column = 0;
                             reader.GetSourceLocationForOffset((uint) constructor.MetadataToken, 0, out fileLocation, out line, out column);
                         }
                         catch
                         {
                         }
                     }
                     if (string.IsNullOrEmpty(fileLocation))
                     {
                         MethodInfo info2 = type.GetMethod("InitializeComponent", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null);
                         if (info2 != null)
                         {
                             try
                             {
                                 uint num3 = 0;
                                 uint num4 = 0;
                                 reader.GetSourceLocationForOffset((uint) info2.MetadataToken, 0, out fileLocation, out num3, out num4);
                                 if (!string.IsNullOrEmpty(fileLocation))
                                 {
                                     if (fileLocation.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase))
                                     {
                                         fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.cs".Length) + ".cs";
                                     }
                                     else if (fileLocation.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase))
                                     {
                                         fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.vb".Length) + ".vb";
                                     }
                                 }
                             }
                             catch
                             {
                             }
                         }
                     }
                 }
                 Activity activity = null;
                 try
                 {
                     try
                     {
                         Activity.ActivityType = type;
                         activity = Activator.CreateInstance(type) as Activity;
                     }
                     finally
                     {
                         Activity.ActivityType = null;
                     }
                     activity.UserData[UserDataKeys.CustomActivity] = false;
                     if (activity is CompositeActivity)
                     {
                         CompositeActivity activity2 = activity as CompositeActivity;
                         if (activity2.CanModifyActivities)
                         {
                             results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_Missing_CanModifyProperties_False", new object[] { activity.GetType().FullName }), 0x117), parameters));
                         }
                     }
                     if (customAttributes.Length > 0)
                     {
                         DesignerSerializationManager manager = new DesignerSerializationManager(WorkflowCompilationContext.Current.ServiceProvider);
                         Activity activity3 = null;
                         using (manager.CreateSession())
                         {
                             WorkflowMarkupSerializationManager serializationManager = new WorkflowMarkupSerializationManager(manager) {
                                 LocalAssembly = parameters.LocalAssembly
                             };
                             using (XmlReader reader2 = XmlReader.Create(customAttributes[0].FileName))
                             {
                                 activity3 = new WorkflowMarkupSerializer().Deserialize(serializationManager, reader2) as Activity;
                             }
                         }
                         if (activity3 is CompositeActivity)
                         {
                             ActivityMarkupSerializer.ReplaceChildActivities(activity as CompositeActivity, activity3 as CompositeActivity);
                         }
                     }
                 }
                 catch (TargetInvocationException exception)
                 {
                     if ((exception.InnerException is TypeInitializationException) && (exception.InnerException.InnerException != null))
                     {
                         results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.InnerException.ToString() }), 0x117), parameters));
                     }
                     else if (exception.InnerException.InnerException != null)
                     {
                         results.Errors.Add(CreateXomlCompilerError(new ValidationError(exception.InnerException.InnerException.ToString(), 0x117), parameters));
                     }
                     else
                     {
                         results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.ToString() }), 0x117), parameters));
                     }
                     continue;
                 }
                 catch (Exception exception2)
                 {
                     results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception2.ToString() }), 0x117), parameters));
                     continue;
                 }
                 activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileLocation);
                 activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName);
                 ValidateActivity(activity, parameters, results);
                 list2.Add(activity);
             }
         }
     }
     foreach (KeyValuePair<object, Exception> pair in service.TypeLoadErrors)
     {
         int num7 = 0x161;
         WorkflowCompilerError error3 = new WorkflowCompilerError(string.Empty, 0, 0, num7.ToString(CultureInfo.InvariantCulture), pair.Value.Message) {
             IsWarning = true
         };
         results.Errors.Add(error3);
     }
     results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results);
     WorkflowCompilationContext current = WorkflowCompilationContext.Current;
     if (current == null)
     {
         throw new Exception(SR.GetString("Error_MissingCompilationContext"));
     }
     WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language));
     WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language));
     if (!results.Errors.HasErrors)
     {
         CodeGenerationManager manager3 = new CodeGenerationManager(WorkflowCompilationContext.Current.ServiceProvider);
         manager3.Context.Push(results.CompiledUnit.Namespaces);
         foreach (Activity activity4 in list2)
         {
             if (activity4.Parent == null)
             {
                 foreach (ActivityCodeGenerator generator in manager3.GetCodeGenerators(activity4.GetType()))
                 {
                     generator.GenerateCode(manager3, activity4);
                 }
             }
         }
         if (!parameters.GenerateCodeCompileUnitOnly || parameters.CheckTypes)
         {
             CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse), parameters.CompilerVersion);
             ArrayList list3 = new ArrayList((ICollection) parameters.UserCodeCompileUnits);
             list3.Add(results.CompiledUnit);
             ArrayList list4 = new ArrayList();
             list4.AddRange(codeFiles);
             list4.AddRange(GenerateFiles(codeDomProvider, parameters, (CodeCompileUnit[]) list3.ToArray(typeof(CodeCompileUnit))));
             CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters, (string[]) list4.ToArray(typeof(string)));
             results.AddCompilerErrorsFromCompilerResults(results2);
             results.PathToAssembly = results2.PathToAssembly;
             results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue;
             if (!results.Errors.HasErrors && parameters.CheckTypes)
             {
                 foreach (string str3 in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location))
                 {
                     bool flag = false;
                     foreach (AuthorizedType type2 in authorizedTypes)
                     {
                         if (type2.RegularExpression.IsMatch(str3))
                         {
                             flag = string.Compare(bool.TrueString, type2.Authorized, StringComparison.OrdinalIgnoreCase) == 0;
                             if (!flag)
                             {
                                 break;
                             }
                         }
                     }
                     if (!flag)
                     {
                         ValidationError error4 = new ValidationError(SR.GetString("Error_TypeNotAuthorized", new object[] { str3 }), 0x16b);
                         results.Errors.Add(CreateXomlCompilerError(error4, parameters));
                     }
                 }
             }
             if (((!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly) && parameters.GenerateInMemory) && (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign")))
             {
                 results.CompiledAssembly = results2.CompiledAssembly;
             }
         }
     }
 }
 public override void Close()
 {
     if (this.serializedXmlString == null)
     {
         DesignerSerializationManager manager = new LocalDesignerSerializationManager(this, this.serviceProvider);
         using (manager.CreateSession())
         {
             WorkflowMarkupSerializationManager serializationManager = new WorkflowMarkupSerializationManager(manager);
             StringWriter w = new StringWriter(CultureInfo.InvariantCulture);
             using (XmlTextWriter writer2 = new XmlTextWriter(w))
             {
                 if (this.memberList.Count == 0)
                 {
                     WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
                     foreach (Activity activity in this.activities)
                     {
                         serializer.SerializeObject(serializationManager, activity, writer2);
                     }
                 }
                 else
                 {
                     PropertySegmentSerializationProvider provider = new PropertySegmentSerializationProvider();
                     serializationManager.AddSerializationProvider(provider);
                     serializationManager.Context.Push(new StringWriter(CultureInfo.InvariantCulture));
                     IReferenceService service = this.serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;
                     if (service != null)
                     {
                         for (int i = 0; i < this.memberList.Count; i++)
                         {
                             object reference = service.GetReference(this.parentObjectNameList[i]);
                             PropertySegmentSerializer serializer2 = new PropertySegmentSerializer(null);
                             if (this.memberList[i] is PropertyDescriptor)
                             {
                                 PropertyInfo property = XomlComponentSerializationService.GetProperty(reference.GetType(), (this.memberList[i] as PropertyDescriptor).Name, BindingFlags.Public | BindingFlags.Instance);
                                 if (property != null)
                                 {
                                     serializer2.SerializeObject(serializationManager, new PropertySegment(this.serviceProvider, reference, property), writer2);
                                 }
                                 else
                                 {
                                     serializer2.SerializeObject(serializationManager, new PropertySegment(this.serviceProvider, reference, this.memberList[i] as PropertyDescriptor), writer2);
                                 }
                             }
                             else if (this.memberList[i] is EventDescriptor)
                             {
                                 IEventBindingService service2 = this.serviceProvider.GetService(typeof(IEventBindingService)) as IEventBindingService;
                                 if (service2 != null)
                                 {
                                     PropertySegment segment = new PropertySegment(this.serviceProvider, reference, service2.GetEventProperty(this.memberList[i] as EventDescriptor));
                                     serializer2.SerializeObject(serializationManager, segment, writer2);
                                 }
                             }
                         }
                     }
                     serializationManager.Context.Pop();
                     serializationManager.RemoveSerializationProvider(provider);
                 }
             }
             this.serializedXmlString = w.ToString();
             List<AssemblyName> list = new List<AssemblyName>();
             foreach (Activity activity2 in this.activities)
             {
                 Assembly assembly = activity2.GetType().Assembly;
                 list.Add(assembly.GetName(true));
             }
             this.assemblies = list.ToArray();
             this.activities.Clear();
             this.activities = null;
         }
     }
 }
        public void GetRuleDefinitions()
        {
            var serializer = new WorkflowMarkupSerializer();
            _ruleDefinitions = new RuleDefinitions();

            Parallel.For(0, _rulesStream.Count, streamCounter =>
                {
                    using (XmlReader reader = new XmlTextReader(_rulesStream[streamCounter]))
                    {
                        var temp = serializer.Deserialize(reader) as RuleDefinitions;

                        if (temp == null) return;

                        if (temp.RuleSets != null)
                        {
                            for (int i=0; i < temp.RuleSets.Count; i++)
                            {
                                _ruleDefinitions.RuleSets.Add(temp.RuleSets[i]);
                            }
                        }
                        if (temp.Conditions != null)
                        {
                            for (int i = 0; i < temp.Conditions.Count; i++)
                            {
                                _ruleDefinitions.Conditions.Add(temp.Conditions[i]);
                            }
                        }
                    }
                });
        }
예제 #27
0
        public void ShowDefaultWorkflow()
        {
            SequentialWorkflowActivity workflow = new SequentialWorkflowActivity();
            workflow.Name = "Workflow1";

            using (StringWriter stringWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
                {
                    WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
                    serializer.Serialize(xmlWriter, workflow);
                    this.Xaml = stringWriter.ToString();
                }
            }
        }
예제 #28
0
파일: Service2.cs 프로젝트: JuRogn/OA
        /// <summary>
        /// 启动与工作流程相同类型流程,查询对应节点用户
        /// </summary>
        /// <param name="CompanyID">公司ID</param>
        /// <param name="ModelCode">模块代码</param>
        /// <param name="FlowGUID">待审批流GUID,新增时为空或者为StartFlow</param>
        /// <returns></returns>
        public DataResult GetAppUser(OracleConnection con, string CompanyID, string ModelCode, string FlowGUID, string xml)
        {

            DataResult GetAppUserResult = new DataResult();
            try
            {
                string StateName = null;


                if (FlowGUID == "" || FlowGUID == "StartFlow")
                {
                    StateName = "StartFlow";
                }
                else
                {
                    //根据待审批流程GUID,检索待审批状态节点代码
                    List<FLOW_FLOWRECORDDETAIL_T> FlowRecord = FlowBLL2.GetFlowInfo(con, "", FlowGUID, "", "", "", "", "", null);
                    if (FlowRecord == null)
                    {
                        GetAppUserResult.Err = "没有待处理的审核";
                        GetAppUserResult.UserInfo = null;
                        return GetAppUserResult;
                    }
                    StateName = FlowRecord[0].STATECODE;
                }

                //根据公司ID,模块代码获取配置的流程
                WorkflowInstance instance = null;
                LogHelper.WriteLog("根据公司ID,模块代码获取配置的流程FlowBLL2.GetFlowByModelName:OgrType='0'");

                List<FLOW_MODELFLOWRELATION_T> MODELFLOWRELATION = FlowBLL2.GetFlowByModelName(con, CompanyID, "", ModelCode, "0");

                if (MODELFLOWRELATION == null || MODELFLOWRELATION.Count == 0)
                {
                    GetAppUserResult.Err = "没有可使用的流程";
                    GetAppUserResult.UserInfo = null;
                    return GetAppUserResult;
                }
                FLOW_FLOWDEFINE_T Xoml = MODELFLOWRELATION[0].FLOW_FLOWDEFINE_T;

                XmlReader readerxoml, readerule;
                StringReader strXoml = new StringReader(Xoml.XOML);
                StringReader strRules = new StringReader(Xoml.RULES == null ? "" : Xoml.RULES);

                readerxoml = XmlReader.Create(strXoml);
                readerule = XmlReader.Create(strRules);

                WorkflowRuntime workflowRuntime = new WorkflowRuntime();
                workflowRuntime.StartRuntime();

                FlowEvent ExternalEvent = new FlowEvent();
                ExternalDataExchangeService objService = new ExternalDataExchangeService();
                workflowRuntime.AddService(objService);
                objService.AddService(ExternalEvent);
                TypeProvider typeProvider = new TypeProvider(null);
                workflowRuntime.AddService(typeProvider);

                //XmlReader readerxoml = XmlReader.Create(HttpContext.Current.Server.MapPath ("TestFlow.xml"));
                // instance = workflowRuntime.CreateWorkflow(readerxoml);
                if (Xoml.RULES == null)
                    instance = workflowRuntime.CreateWorkflow(readerxoml);
                else
                    instance = workflowRuntime.CreateWorkflow(readerxoml, readerule, null);
                // instance = workflowRuntime.CreateWorkflow(typeof(TestFlow));
                instance.Start();
                StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId);

                //从实例中获取定义
                if (1 == 2)
                {
                    System.Workflow.Activities.StateMachineWorkflowActivity smworkflow = new StateMachineWorkflowActivity();
                    smworkflow = workflowinstance.StateMachineWorkflow;
                    RuleDefinitions ruleDefinitions = smworkflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions;
                    WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();

                    StringBuilder xoml = new StringBuilder();
                    StringBuilder rule = new StringBuilder();
                    XmlWriter xmlWriter = XmlWriter.Create(xoml);
                    XmlWriter ruleWriter = XmlWriter.Create(rule);
                    markupSerializer.Serialize(xmlWriter, smworkflow);
                    markupSerializer.Serialize(ruleWriter, ruleDefinitions);
                    xmlWriter.Close();
                    ruleWriter.Close();
                    StringReader readxoml = new StringReader(xoml.ToString());
                    StringReader readrule = new StringReader(rule.ToString());
                    XmlReader readerxoml2 = XmlReader.Create(readxoml);
                    XmlReader readerrule2 = XmlReader.Create(readrule);
                    WorkflowInstance instance1 = workflowRuntime.CreateWorkflow(readerxoml2, readerrule2, null);
                    instance1.Start();
                    StateMachineWorkflowInstance workflowinstance1 = new StateMachineWorkflowInstance(workflowRuntime, instance1.InstanceId);
                    workflowinstance1.SetState(StateName);
                }
                //从实例中获取定义并启动新实例

                //跳转到节点StateName
                workflowinstance.SetState(StateName);

                FlowDataType.FlowData FlowData = new FlowDataType.FlowData();
                FlowData.xml = xml;
                //  FlowData.Flow_FlowRecord_T = null;

                ExternalEvent.OnDoFlow(instance.InstanceId, FlowData);//激发流程引擎流转到下一状态
                System.Threading.Thread.Sleep(1000);
                PermissionServiceClient WcfPermissionService = new PermissionServiceClient();
                string CurrentStateName = workflowinstance.CurrentStateName == null ? "End" : workflowinstance.CurrentStateName; //取得当前状态
                List<UserInfo> listUser = new List<UserInfo>();
                if (CurrentStateName != "End")
                {
                    if (CurrentStateName.Substring(0, 5) == "State")
                    {
                        CurrentStateName = CurrentStateName.Substring(5);
                    }
                    string WFCurrentStateName = new Guid(CurrentStateName).ToString("D");
                    T_SYS_USER[]  User = WcfPermissionService.GetSysUserByRole(WFCurrentStateName); //检索本状态(角色)对应用户

                    if (User != null)
                        for (int i = 0; i < User.Length; i++)
                        {
                            UserInfo tmp = new UserInfo();
                            tmp.UserID = User[i].EMPLOYEEID;
                            tmp.UserName = User[i].EMPLOYEENAME;
                            listUser.Add(tmp);
                        }



                }
                else
                {
                    //已经到流程结束状态
                    UserInfo tmp = new UserInfo();
                    tmp.UserID = "End";
                    tmp.UserName = "******";

                    listUser.Add(tmp);
                }


                GetAppUserResult.UserInfo = listUser.Count > 0 ? listUser : null;

                if (GetAppUserResult.UserInfo == null)
                    GetAppUserResult.Err = "没有找到用户";

                return GetAppUserResult;
                // return listUser;


                //return workflowinstance.CurrentStateName == null ? "End" : workflowinstance.CurrentStateName;
            }
            catch (Exception ex)
            {
                GetAppUserResult.Err = ex.Message;
                GetAppUserResult.UserInfo = null;
                return GetAppUserResult;
            }
        }
        public override void Close()
        {
            if (this.serializedXmlString != null)
                return;

            DesignerSerializationManager serializationManager = new LocalDesignerSerializationManager(this, serviceProvider);
            using (serializationManager.CreateSession())
            {
                // serialize all objects 
                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(serializationManager);
                StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
                using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
                {
                    if (this.memberList.Count == 0)
                    {
                        WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
                        foreach (Activity activity in this.activities)
                            xomlSerializer.SerializeObject(xomlSerializationManager, activity, writer);
                    }
                    else
                    {
                        PropertySegmentSerializationProvider propertySegmentSerializationProvider = new PropertySegmentSerializationProvider();
                        xomlSerializationManager.AddSerializationProvider(propertySegmentSerializationProvider);

                        xomlSerializationManager.Context.Push(new StringWriter(CultureInfo.InvariantCulture));

                        IReferenceService referenceService = this.serviceProvider.GetService(typeof(IReferenceService)) as IReferenceService;
                        if (referenceService != null)
                        {
                            for (int loop = 0; loop < this.memberList.Count; loop++)
                            {
                                object obj = referenceService.GetReference(this.parentObjectNameList[loop]);
                                PropertySegmentSerializer serializer = new PropertySegmentSerializer(null);
                                if (this.memberList[loop] is PropertyDescriptor)
                                {
                                    PropertyInfo propertyInfo = XomlComponentSerializationService.GetProperty(obj.GetType(), (this.memberList[loop] as PropertyDescriptor).Name, BindingFlags.Public | BindingFlags.Instance);
                                    if (propertyInfo != null)
                                        serializer.SerializeObject(xomlSerializationManager, new PropertySegment(this.serviceProvider, obj, propertyInfo), writer);
                                    else
                                        serializer.SerializeObject(xomlSerializationManager, new PropertySegment(this.serviceProvider, obj, this.memberList[loop] as PropertyDescriptor), writer);
                                }
                                else if (this.memberList[loop] is EventDescriptor)
                                {
                                    // Events.
                                    IEventBindingService eventBindingService = this.serviceProvider.GetService(typeof(IEventBindingService)) as IEventBindingService;
                                    if (eventBindingService != null)
                                    {
                                        PropertySegment propertySegment = new PropertySegment(serviceProvider, obj, eventBindingService.GetEventProperty(this.memberList[loop] as EventDescriptor));
                                        serializer.SerializeObject(xomlSerializationManager, propertySegment, writer);
                                    }
                                }
                            }
                        }

                        xomlSerializationManager.Context.Pop();
                        xomlSerializationManager.RemoveSerializationProvider(propertySegmentSerializationProvider);
                    }
                }
                this.serializedXmlString = stringWriter.ToString();

                // store all the assembly names
                List<AssemblyName> assemblyList = new List<AssemblyName>();
                foreach (Activity activity in this.activities)
                {
                    Assembly a = activity.GetType().Assembly;
                    assemblyList.Add(a.GetName(true));
                }
                this.assemblies = assemblyList.ToArray();
                this.activities.Clear();
                this.activities = null;
            }
        }
 private static ArrayList CloneWorkflowChangeActions(ArrayList workflowChanges, Activity rootActivity)
 {
     if (workflowChanges == null)
     {
         throw new ArgumentNullException("workflowChanges");
     }
     if (rootActivity == null)
     {
         throw new ArgumentNullException("rootActivity");
     }
     string s = null;
     TypeProvider serviceInstance = CreateTypeProvider(rootActivity);
     ServiceContainer provider = new ServiceContainer();
     provider.AddService(typeof(ITypeProvider), serviceInstance);
     DesignerSerializationManager manager = new DesignerSerializationManager(provider);
     WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
     using (manager.CreateSession())
     {
         using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
         {
             using (XmlWriter writer2 = Helpers.CreateXmlWriter(writer))
             {
                 WorkflowMarkupSerializationManager serializationManager = new WorkflowMarkupSerializationManager(manager);
                 serializer.Serialize(serializationManager, writer2, workflowChanges);
                 s = writer.ToString();
             }
         }
         using (StringReader reader = new StringReader(s))
         {
             using (XmlReader reader2 = XmlReader.Create(reader))
             {
                 WorkflowMarkupSerializationManager manager3 = new WorkflowMarkupSerializationManager(manager);
                 return (serializer.Deserialize(manager3, reader2) as ArrayList);
             }
         }
     }
 }