1.宿主程序中,首先我們在workflowRuntime的WorkflowCreated事件中執行動態更新.代 碼如下:
static void workflowRuntime_WorkflowCreated(object sender, WorkflowEventArgs e)
{
WorkflowChanges wc = new WorkflowChanges (e.WorkflowInstance.GetWorkflowDefinition());
CompositeActivity sequenceContainer = wc.TransIEntWorkflow.GetActivityByName
("sequenceActivityContainer") as CompositeActivity;
if (sequenceContainer != null)
{
PrintActivity print = new PrintActivity();
sequenceContainer.ActivitIEs.Add(print);
ValidationErrorCollection errors = wc.Validate();
if (errors.Count == 0)
{
try { e.WorkflowInstance.ApplyWorkflowChanges(wc); }
catch (Exception ex)
{
Console.WriteLine(" 引用動態更新異常:{0}", ex.Message);
}
}
else
{
foreach (ValidationError error in errors)
{
Console.WriteLine("驗證錯誤:" + error.ToString ());
}
}
}
}
2.運行程序後得到如下 圖結果:
3.從上圖可以看出我們自定義的PrintActivity活動在運行時添加到了工作流實例當中,以上 我們是在宿主程序中執行動態更新的,我們也可以在工作流內部來完成,例如我們將動態更新的代碼放 到我們重寫的Initialize方法中,我們只要將如下代碼做更改即可:
WorkflowChanges wc = new WorkflowChanges(e.WorkflowInstance.GetWorkflowDefinition());
try { e.WorkflowInstance.ApplyWorkflowChanges(wc); }
改為:
WorkflowChanges wc = new WorkflowChanges(this);
try { this.ApplyWorkflowChanges(wc); }
運行程序你 可以得到和上面一樣的結果。4.如果你將工作流的DynamicUpdateCondition屬性設為false,此時做動態 更新時會拋出異常,如下圖: