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(); }
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); } } } }
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; }
public static void CreateDynamicRule(string fileNameWithPath, TPromotionRule promotionRuleObj) { Rule minTktFareRule = null; Rule validityStartDateRule = null; Rule validityEndDateRule = null; Rule validDayRule = null; Rule validRouteRule = null; Rule validBulkBookingRule = null; Rule validAdvanceBookingRule = null; Rule validLastMinuteBookingRule = null; Rule discountRule = null; Rule offerCodeRule = null; Rule maxDiscountLimitRule = null; RuleSet ruleSet = new RuleSet(promotionRuleObj.OfferCode + "RuleSet"); if(promotionRuleObj.MinTicketFare != decimal.Zero) { minTktFareRule = CreateMinTicketFareRule(promotionRuleObj); ruleSet.Rules.Add(minTktFareRule); } if (promotionRuleObj.ValidityStartDate != null) { validityStartDateRule = CreateValidityStartDateRule(promotionRuleObj); ruleSet.Rules.Add(validityStartDateRule); } if (promotionRuleObj.ValidityEndDate != null) { validityEndDateRule = CreateValidityEndDateRule(promotionRuleObj); ruleSet.Rules.Add(validityEndDateRule); } if(promotionRuleObj.DaysCSV != null) { validDayRule = CreateValidDayRule(promotionRuleObj); ruleSet.Rules.Add(validDayRule); } if (promotionRuleObj.RouteIDCSV != null) { validRouteRule = CreateValidRouteRule(promotionRuleObj); ruleSet.Rules.Add(validRouteRule); } if (promotionRuleObj.MinNumOfSeats != null) { validBulkBookingRule = CreateValidBulkBookingRule(promotionRuleObj); ruleSet.Rules.Add(validBulkBookingRule); } if (promotionRuleObj.MinNumOfAdvanceBookingDays != null) { validAdvanceBookingRule = CreateValidAdvanceBookingRule(promotionRuleObj); ruleSet.Rules.Add(validAdvanceBookingRule); } if (promotionRuleObj.LastMinuteCountBeforeDept != null) { validLastMinuteBookingRule = CreateValidLastMinBookingRule(promotionRuleObj); ruleSet.Rules.Add(validLastMinuteBookingRule); } if (promotionRuleObj.DiscountUnit != decimal.Zero) { discountRule = CreateDiscountUnitRule(promotionRuleObj); } else if(promotionRuleObj.DiscountPercent != decimal.Zero) { discountRule = CreateDiscountPercentRule(promotionRuleObj); } ruleSet.Rules.Add(discountRule); offerCodeRule = CreateOfferCodeRule(promotionRuleObj); ruleSet.Rules.Add(offerCodeRule); if(promotionRuleObj.MaxDiscountAmount != decimal.Zero) { maxDiscountLimitRule = CreateMaxDiscountLimitRule(promotionRuleObj); ruleSet.Rules.Add(maxDiscountLimitRule); } using (XmlWriter xmlWriter = XmlWriter.Create(fileNameWithPath)) { WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer(); markupSerializer.Serialize(xmlWriter, ruleSet); } }
public static string Serialize(RuleSet rules) { StringBuilder sbXOML = new StringBuilder(); using ( StringWriter wtr = new StringWriter(sbXOML, System.Globalization.CultureInfo.InvariantCulture) ) { using ( XmlTextWriter xwtr = new XmlTextWriter(wtr) ) { WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); serializer.Serialize(xwtr, rules); } } return sbXOML.ToString(); }
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(); } }
private void saveRuleSet(string filename, RuleSet ruleSet) { using (XmlTextWriter writer = new XmlTextWriter(filename, null)) { RuleDefinitions ruleDef = new RuleDefinitions(); ruleDef.RuleSets.Add(ruleSet); WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); serializer.Serialize(writer, ruleDef); } }
static void Main(string[] args) { const string workflowFilename = "workflow.xoml"; // // Create and configure workflow runtime // 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 workflow programmatically // Console.WriteLine("Creating workflow."); SequentialWorkflowActivity workflow = new SequentialWorkflowActivity(); workflow.Name = "Programmatically created workflow"; workflow.Description = "Programmatically created workflow for XAML activation"; ConsoleActivity activity = new ConsoleActivity(); activity.Name = "ConsoleActivity1"; activity.StringToWrite = "Sample String"; workflow.Activities.Add(activity); // // Serialize workflow to XAML file // Console.WriteLine("Serializing workflow to file."); WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); using (XmlWriter writer = XmlWriter.Create(workflowFilename)) { DesignerSerializationManager serializationManager = new DesignerSerializationManager(); 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; } } } // // Deserialize workflow from file // WorkflowInstance deserializedWorkflow = null; Console.WriteLine("Deserializing workflow from file."); try { using (XmlReader reader = XmlReader.Create(workflowFilename)) { deserializedWorkflow = workflowRuntime.CreateWorkflow(reader); } } catch (WorkflowValidationFailedException exp) { ValidationErrorCollection list = exp.Errors; foreach (ValidationError err in list) { Console.WriteLine(err.ErrorText); } return; } // // Start workflow // Console.WriteLine("Starting workflow."); deserializedWorkflow.Start(); waitHandle.WaitOne(); workflowRuntime.StopRuntime(); } }
/// <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); } }
protected override void PerformFlush(IDesignerSerializationManager manager) { IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); if (host != null && host.RootComponent != null) { Activity rootActivity = host.RootComponent as Activity; if (rootActivity != null) { StringWriter writer = new StringWriter(); try { using (XmlWriter xmlWriter = XmlWriter.Create(writer)) { WorkflowMarkupSerializer xamlSerializer = new WorkflowMarkupSerializer(); xamlSerializer.Serialize(xmlWriter, rootActivity); } } finally { writer.Close(); } Xaml = writer.ToString(); } } }
protected internal override bool ApplyTo(Activity rootActivity) { if (rootActivity == null) { throw new ArgumentNullException("rootActivity"); } if (!(rootActivity is CompositeActivity)) { throw new ArgumentException(SR.GetString("Error_RootActivityTypeInvalid"), "rootActivity"); } CompositeActivity compositeActivity = rootActivity.TraverseDottedPathFromRoot(base.OwnerActivityDottedPath) as CompositeActivity; if (compositeActivity == null) { return false; } compositeActivity.DynamicUpdateMode = true; CompositeActivity parent = this.addedActivity.Parent; try { this.addedActivity.SetParent(compositeActivity); Activity addedActivity = this.addedActivity; if (!this.addedActivity.DesignMode) { addedActivity = this.addedActivity.Clone(); } else { TypeProvider serviceInstance = WorkflowChanges.CreateTypeProvider(rootActivity); ServiceContainer provider = new ServiceContainer(); provider.AddService(typeof(ITypeProvider), serviceInstance); DesignerSerializationManager manager = new DesignerSerializationManager(provider); WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); string s = string.Empty; 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, this.addedActivity); s = writer.ToString(); } } using (StringReader reader = new StringReader(s)) { using (XmlReader reader2 = XmlReader.Create(reader)) { WorkflowMarkupSerializationManager manager3 = new WorkflowMarkupSerializationManager(manager); addedActivity = serializer.Deserialize(manager3, reader2) as Activity; } } } if (addedActivity == null) { throw new InvalidOperationException(SR.GetString("Error_ApplyDynamicChangeFailed")); } } if (compositeActivity.WorkflowCoreRuntime != null) { ((IDependencyObjectAccessor) addedActivity).InitializeInstanceForRuntime(compositeActivity.WorkflowCoreRuntime); } addedActivity.SetParent(null); compositeActivity.Activities.Insert(this.index, addedActivity); } finally { this.addedActivity.SetParent(parent); compositeActivity.DynamicUpdateMode = false; } return true; }
private void SerializeToMarkup(Activity workflow, string fileName) { workflow.SetValue(WorkflowMarkupSerializer.XClassProperty, null); using (XmlWriter xmlWriter = XmlWriter.Create(fileName)) { WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer(); markupSerializer.Serialize(xmlWriter, workflow); } RuleDefinitions ruleDefinitions = workflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; if (ruleDefinitions != null) { if (ruleDefinitions.Conditions.Count > 0 || ruleDefinitions.RuleSets.Count > 0) { String rulesFileName = GetRulesFileName(fileName); using (XmlWriter xmlWriter = XmlWriter.Create(rulesFileName)) { WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer(); markupSerializer.Serialize(xmlWriter, ruleDefinitions); } } } }
void viewRuleSetButton_Click(object sender, RoutedEventArgs e) { // get the rulesFilePath property object rulesFilePath = ModelItem.Properties["RulesFilePath"].Value; rulesFilePath = ((ModelItem)rulesFilePath).GetCurrentValue(); // correct the rules file path (in case is a relative path) string correctedRulesFilePath = GetRulesFilePath((string)rulesFilePath); // verify that RulesFilePath property has been configured if (rulesFilePath == null || !(rulesFilePath is string)) { System.Windows.MessageBox.Show("Rules File Path needs to be configured before viewing or editing the rules"); return; } else if (!File.Exists(correctedRulesFilePath)) { System.Windows.MessageBox.Show(string.Format("Rules File Path provided not found ({0})", correctedRulesFilePath)); return; } // verify that RuleSetName property has been configured object ruleSetName = ModelItem.Properties["RuleSetName"].Value; ruleSetName = ((ModelItem)ruleSetName).GetCurrentValue(); if (ruleSetName == null) { System.Windows.MessageBox.Show("RuleSet Name needs to be configured before viewing or editing the rules"); return; } // verify that TargetObject property has been configured object targetObject = ModelItem.Properties["TargetObject"].Value; targetObject = ((ModelItem)targetObject).GetCurrentValue(); if (targetObject == null) { System.Windows.MessageBox.Show("TargetObject needs to be configured before viewing or editing the rules"); return; } // verify that target object is correctly configured InArgument targetObjArg = targetObject as InArgument; if (targetObjArg == null) { System.Windows.MessageBox.Show("Invalid target object"); return; } // open the ruleset editor Type targetObjectType = targetObjArg.ArgumentType; WorkflowMarkupSerializer ser = new WorkflowMarkupSerializer(); RuleDefinitions ruleDefs = ser.Deserialize(new System.Xml.XmlTextReader((string)correctedRulesFilePath)) as RuleDefinitions; RuleSet ruleSet = ruleDefs.RuleSets[(string)ruleSetName]; // popup the dialog for viewing the rules RuleSetDialog ruleSetDialog = new RuleSetDialog(targetObjectType, null, ruleSet); DialogResult result = ruleSetDialog.ShowDialog(); // update if they changed the Rules if (result == DialogResult.OK) //If OK was pressed { for (int index = 0; index < ruleDefs.RuleSets.Count; index++) { if (ruleDefs.RuleSets[index].Name == (string)ruleSetName) { ruleDefs.RuleSets[index] = ruleSetDialog.RuleSet; break; } } try { ser.Serialize(new System.Xml.XmlTextWriter(correctedRulesFilePath, null), ruleDefs); } catch (UnauthorizedAccessException) { // File does not have write access. Make a local copy so user changes are not lost FileInfo fileInfo = new FileInfo(correctedRulesFilePath); // create local file by adding a random suffix to original filename string localFileCopy = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('.')) + new Random().Next() + fileInfo.Extension; ser.Serialize(new System.Xml.XmlTextWriter((string)localFileCopy, null), ruleDefs); System.Windows.MessageBox.Show("Rules file is not writeable. Created copy of your changes in " + localFileCopy); } } }
private void saveRuleDef(string filename, RuleDefinitions ruleDef) { using (XmlTextWriter writer = new XmlTextWriter(filename, null)) { WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); serializer.Serialize(writer, ruleDef); } }
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); } } } }
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 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("ルールを反映しました"); }
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()); } } }
private void OpenXamlInNotepad(object sender, EventArgs e) { ToolStripMenuItem item = (ToolStripMenuItem)sender; WorkflowNode node = (WorkflowNode)item.Tag; object workflowInstance = null; try { workflowInstance = node.WorkflowType.InvokeMember(string.Empty, BindingFlags.CreateInstance, null, null, null, CultureInfo.InvariantCulture); } catch (Exception exc) { MessageBox.Show("The workflow type could not be created: " + exc.ToString()); return; } WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); string tempFileName = Path.GetTempFileName(); using (XmlWriter xmlWriter = XmlWriter.Create(tempFileName)) { serializer.Serialize( xmlWriter, workflowInstance); } ProcessStartInfo psi = new ProcessStartInfo(); psi.Arguments = tempFileName; psi.FileName = Path.Combine(Environment.GetEnvironmentVariable("windir"), "notepad.exe"); Process.Start(psi); }
public void saveRuleDef(string site, string station, string name, RuleDefinitions ruleDef) { StringWriter sw = new StringWriter(); using (XmlTextWriter writer = new XmlTextWriter(sw)) { WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); serializer.Serialize(writer, ruleDef); } string content = sw.ToString(); RouteManager.WriteRuleSet(site, station, name, content); }
/// <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; } }
private string SerializeRuleSet(RuleSet ruleset) { WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); StringBuilder ruleDefinition = new StringBuilder(); if (ruleset != null) { try { StringWriter stringWriter = new StringWriter(ruleDefinition); XmlTextWriter writer = new XmlTextWriter(stringWriter); serializer.Serialize(writer, ruleset); writer.Flush(); writer.Close(); stringWriter.Flush(); stringWriter.Close(); } catch (Exception ex) { } } return ruleDefinition.ToString(); }
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(); } } }
private void Step_CreateXoml() { // Root アクティビティ RootWorkflowActivityWithData rootActivity = new RootWorkflowActivityWithData(); rootActivity.Name = "ROOT"; rootActivity.WorkflowFields.Add(new WorkflowDataField("__list", "System.String")); rootActivity.WorkflowFields.Add(new WorkflowDataField("__item", "System.Int32")); rootActivity.WorkflowFields.Add(new WorkflowDataField("__context", "Microsoft.SharePoint.WorkflowActions.WorkflowContext")); rootActivity.WorkflowFields.Add(new WorkflowDataField("__initParams", "Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties")); rootActivity.WorkflowFields.Add(new WorkflowDataField("__workflowId", "System.Guid")); // OnWorkflowActivated アクティビティ OnWorkflowActivated onWorkflowActivatedActivity = new OnWorkflowActivated(); CorrelationToken onWorkflowActivatedColToken = new CorrelationToken("refObject"); onWorkflowActivatedColToken.OwnerActivityName = "ROOT"; onWorkflowActivatedActivity.CorrelationToken = onWorkflowActivatedColToken; ActivityBind onWorkflowActivatedBind = new ActivityBind(); onWorkflowActivatedBind.Name = "ROOT"; onWorkflowActivatedBind.Path = "__initParams"; onWorkflowActivatedActivity.SetBinding(OnWorkflowActivated.WorkflowPropertiesProperty, onWorkflowActivatedBind); rootActivity.Activities.Add(onWorkflowActivatedActivity); // ApplyActivation アクティビティ ApplyActivation applyActivationActivity = new ApplyActivation(); ActivityBind applyActivationBindContextProp = new ActivityBind(); applyActivationBindContextProp.Name = "ROOT"; applyActivationBindContextProp.Path = "__context"; applyActivationActivity.SetBinding(ApplyActivation.__ContextProperty, applyActivationBindContextProp); ActivityBind applyActivationBindWorkflowProp = new ActivityBind(); applyActivationBindWorkflowProp.Name = "ROOT"; applyActivationBindWorkflowProp.Path = "__initParams"; applyActivationActivity.SetBinding(ApplyActivation.__WorkflowPropertiesProperty, applyActivationBindWorkflowProp); rootActivity.Activities.Add(applyActivationActivity); // Sequence アクティビティ (ステップ 1) SequenceActivity step1Activity = new SequenceActivity(); step1Activity.Description = "ステップ 1"; for (int i = 0; i < 3; i++) { // SetField アクティビティ if (Tasks[i].SelectedItem == "Field Update") { SetFieldActivity setFieldActivity = new SetFieldActivity(); string docListGUID = GetListGUIDFromName(SiteLoc.Text, AssocDocLib.Text); setFieldActivity.FieldName = GetFieldInternalName(SiteLoc.Text, docListGUID, FieldNames[i].Text); setFieldActivity.Value = FieldValues[i].Text; ActivityBind contextPropertyBind = new ActivityBind(); contextPropertyBind.Name = "ROOT"; contextPropertyBind.Path = "__context"; setFieldActivity.SetBinding(SetFieldActivity.__ContextProperty, contextPropertyBind); ActivityBind listIdBind = new ActivityBind(); listIdBind.Name = "ROOT"; listIdBind.Path = "__list"; setFieldActivity.SetBinding(SetFieldActivity.__ListIdProperty, listIdBind); ActivityBind listItemBind = new ActivityBind(); listItemBind.Name = "ROOT"; listItemBind.Path = "__item"; setFieldActivity.SetBinding(SetFieldActivity.__ListItemProperty, listItemBind); step1Activity.Activities.Add(setFieldActivity); } // EMail アクティビティ else if (Tasks[i].SelectedItem == "Send Mail") { EmailActivity eMailActivity = new EmailActivity(); ArrayList toArray = new ArrayList(); toArray.Add(MailAddresses[i].Text); eMailActivity.To = toArray; eMailActivity.CC = null; eMailActivity.BCC = null; eMailActivity.Subject = "Custom Workflow Test"; eMailActivity.Body = "Hello, SharePoint !"; ActivityBind contextPropertyBind = new ActivityBind(); contextPropertyBind.Name = "ROOT"; contextPropertyBind.Path = "__context"; eMailActivity.SetBinding(EmailActivity.__ContextProperty, contextPropertyBind); step1Activity.Activities.Add(eMailActivity); } } rootActivity.Activities.Add(step1Activity); // XmlDocument に保存 MemoryStream xomlMem = new MemoryStream(); XmlTextWriter xomlWriter = new XmlTextWriter(xomlMem, Encoding.UTF8); WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer(); xomlSerializer.Serialize(xomlWriter, rootActivity); xomlDoc = new XmlDocument(); xomlMem.Position = 3; // Attention! : 先頭の BOM (Byte Order Mark) は SharePoint でおかしな動きになる ! xomlDoc.Load(xomlMem); xomlWriter.Close(); xomlMem.Close(); // コードも含めたコンパイル (サーバ側) に備え x:Class を追加 XmlAttribute classAttr = xomlDoc.CreateAttribute("Class", @"http://schemas.microsoft.com/winfx/2006/xaml"); classAttr.Value = "Microsoft.SharePoint.Workflow.ROOT"; xomlDoc.ChildNodes[0].Attributes.Append(classAttr); // if you use Microsoft.SharePoint.WorkflowActions.dll, // this code is needed. (Above notation) // xomlDoc.ChildNodes[0].Attributes["xmlns:ns0"].Value = @"clr-namespace:Microsoft.SharePoint.WorkflowActions;Assembly=Microsoft.SharePoint.WorkflowActions, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null"; }