// Save the workflow instance state at the point of persistence with option of locking the instance state if it is shared // across multiple runtimes or multiple phase instance updates protected override void SaveWorkflowInstanceState(Activity rootActivity, bool unlock) { // Save the workflow Guid contextGuid = (Guid)rootActivity.GetValue(Activity.ActivityContextGuidProperty); Console.WriteLine("Saving instance: {0}\n", contextGuid); SerializeToFile( WorkflowPersistenceService.GetDefaultSerializedForm(rootActivity), contextGuid); // See when the next timer (Delay activity) for this workflow will expire TimerEventSubscriptionCollection timers = (TimerEventSubscriptionCollection)rootActivity.GetValue(TimerEventSubscriptionCollection.TimerCollectionProperty); TimerEventSubscription subscription = timers.Peek(); if (subscription != null) { // Set a system timer to automatically reload this workflow when its next timer expires TimerCallback callback = new TimerCallback(ReloadWorkflow); TimeSpan timeDifference = subscription.ExpiresAt - DateTime.UtcNow; // check to make sure timeDifference is in legal range if (timeDifference > FilePersistenceService.MaxInterval) { timeDifference = FilePersistenceService.MaxInterval; } else if (timeDifference < TimeSpan.Zero) { timeDifference = TimeSpan.Zero; } this.instanceTimers.Add(contextGuid, new System.Threading.Timer( callback, subscription.WorkflowInstanceId, timeDifference, new TimeSpan(-1))); } }
protected override bool ApplyTo(Activity rootActivity) { if (rootActivity == null) { return false; } RuleDefinitions definitions = rootActivity.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; if ((definitions == null) || (definitions.RuleSets == null)) { return false; } if (definitions.RuleSets[this.RuleSetName] == null) { return false; } bool flag = false; if (definitions.Conditions.RuntimeMode) { definitions.Conditions.RuntimeMode = false; flag = true; } try { definitions.RuleSets.Remove(this.RuleSetName); definitions.RuleSets.Add(this.updated); } finally { if (flag) { definitions.RuleSets.RuntimeMode = true; } } return true; }
// Save the completed activity state. protected override void SaveCompletedContextActivity(Activity activity) { Guid contextGuid = (Guid)activity.GetValue(Activity.ActivityContextGuidProperty); Console.WriteLine("Saving completed activity context: {0}", contextGuid); SerializeToFile( WorkflowPersistenceService.GetDefaultSerializedForm(activity), contextGuid); }
protected override bool ApplyTo(Activity rootActivity) { bool flag2; if (rootActivity == null) { return false; } RuleDefinitions definitions = rootActivity.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; if ((definitions == null) || (definitions.RuleSets == null)) { return false; } bool flag = false; if (definitions.RuleSets.RuntimeMode) { definitions.RuleSets.RuntimeMode = false; flag = true; } try { flag2 = definitions.RuleSets.Remove(this.ruleset.Name); } finally { if (flag) { definitions.RuleSets.RuntimeMode = true; } } return flag2; }
protected override bool ApplyTo(Activity rootActivity) { if (rootActivity == null) { return false; } RuleDefinitions definitions = rootActivity.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; if (definitions == null) { definitions = new RuleDefinitions(); rootActivity.SetValue(RuleDefinitions.RuleDefinitionsProperty, definitions); } bool flag = false; if (definitions.Conditions.RuntimeMode) { definitions.Conditions.RuntimeMode = false; flag = true; } try { definitions.Conditions.Add(this.ConditionDefinition); } finally { if (flag) { definitions.Conditions.RuntimeMode = true; } } return true; }
static protected byte[] GetDefaultSerializedForm(Activity activity) { DateTime startTime = DateTime.Now; Byte[] result; Debug.Assert(activity != null, "Null activity"); using (MemoryStream stream = new MemoryStream(10240)) { stream.Position = 0; activity.Save(stream); using (MemoryStream compressedStream = new MemoryStream((int)stream.Length)) { using (GZipStream gzs = new GZipStream(compressedStream, CompressionMode.Compress, true)) { gzs.Write(stream.GetBuffer(), 0, (int)stream.Length); } ActivityExecutionContextInfo executionContextInfo = (ActivityExecutionContextInfo)activity.GetValue(Activity.ActivityExecutionContextInfoProperty); TimeSpan timeElapsed = DateTime.Now - startTime; WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "Serialized a {0} with id {1} to length {2}. Took {3}.", executionContextInfo, executionContextInfo.ContextGuid, compressedStream.Length, timeElapsed); result = compressedStream.GetBuffer(); Array.Resize<Byte>(ref result, Convert.ToInt32(compressedStream.Length)); } } return result; }
public void AddActivityToDesigner(Activity activity) { if (activity == null) { throw new ArgumentNullException("activity"); } IDesignerHost service = base.GetService(typeof(IDesignerHost)) as IDesignerHost; if (service == null) { throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IDesignerHost).FullName })); } if ((activity.Parent == null) && (service.RootComponent == null)) { string str = activity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string; string name = !string.IsNullOrEmpty(str) ? Helpers.GetClassName(str) : Helpers.GetClassName(activity.GetType().FullName); service.Container.Add(activity, name); this.AddTargetFrameworkProvider(activity); } else { service.Container.Add(activity, activity.QualifiedName); this.AddTargetFrameworkProvider(activity); } if (activity is CompositeActivity) { foreach (Activity activity2 in Helpers.GetNestedActivities(activity as CompositeActivity)) { service.Container.Add(activity2, activity2.QualifiedName); this.AddTargetFrameworkProvider(activity2); } } }
protected override void OnValidate(ValidationErrorCollection errors) { if (!string.IsNullOrEmpty(this.rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string)) { errors.Add(new ValidationError(SR2.XomlWorkflowHasClassName, ErrorNumbers.Error_XomlWorkflowHasClassName)); } Queue compositeActivities = new Queue(); compositeActivities.Enqueue(this.rootActivity); while (compositeActivities.Count > 0) { System.Workflow.ComponentModel.Activity activity = compositeActivities.Dequeue() as System.Workflow.ComponentModel.Activity; if (activity.GetValue(WorkflowMarkupSerializer.XCodeProperty) != null) { errors.Add(new ValidationError(SR2.XomlWorkflowHasCode, ErrorNumbers.Error_XomlWorkflowHasCode)); } CompositeActivity compositeActivity = activity as CompositeActivity; if (compositeActivity != null) { foreach (System.Workflow.ComponentModel.Activity childActivity in compositeActivity.EnabledActivities) { compositeActivities.Enqueue(childActivity); } } } }
internal static void Flush_Rules_DT(IServiceProvider serviceProvider, Activity activity) { RuleDefinitions definitions = (RuleDefinitions) activity.GetValue(RuleDefinitions.RuleDefinitionsProperty); if (definitions != null) { WorkflowDesignerLoader service = (WorkflowDesignerLoader) serviceProvider.GetService(typeof(WorkflowDesignerLoader)); if (service != null) { string filePath = string.Empty; if (!string.IsNullOrEmpty(service.FileName)) { filePath = Path.Combine(Path.GetDirectoryName(service.FileName), Path.GetFileNameWithoutExtension(service.FileName)); } filePath = filePath + ".rules"; using (TextWriter writer = service.GetFileWriter(filePath)) { if (writer != null) { using (XmlWriter writer2 = System.Workflow.Activities.Common.Helpers.CreateXmlWriter(writer)) { DesignerSerializationManager serializationManager = new DesignerSerializationManager(serviceProvider); using (serializationManager.CreateSession()) { new WorkflowMarkupSerializer().Serialize(serializationManager, writer2, definitions); } } } } } } }
public void PersistInstanceState(System.Workflow.ComponentModel.Activity activity) { this.lastExceptionThrown = null; this.abortTransaction = false; this.ScheduleDelayedItems(activity); if (this.currentAtomicActivity == null) { if ((activity == this.rootActivity) && !activity.PersistOnClose) { return; } this.ServiceProvider.Persist(); } else { TransactionalProperties transactionalProperties = null; transactionalProperties = (TransactionalProperties)activity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); if (this.CheckAndProcessTransactionAborted(transactionalProperties)) { return; } transactionalProperties.TransactionScope.Complete(); transactionalProperties.TransactionScope.Dispose(); transactionalProperties.TransactionScope = null; this.ServiceProvider.CommitTransaction(); transactionalProperties.Transaction = null; this.currentAtomicActivity = null; } this.internalCurrentActivity = activity; this.scheduler.Pause(); }
public ActivityCondition GetWhenCondition(Activity activity) { if (activity.Parent is ConditionedActivityGroup) { return (activity.GetValue(ConditionedActivityGroup.WhenConditionProperty) as ActivityCondition); } return null; }
private static System.Workflow.ComponentModel.Activity ContextActivity(System.Workflow.ComponentModel.Activity activity) { System.Workflow.ComponentModel.Activity parent = activity; while ((parent != null) && (parent.GetValue(System.Workflow.ComponentModel.Activity.ActivityExecutionContextInfoProperty) == null)) { parent = parent.Parent; } return(parent); }
internal static Type GetActivityType(IServiceProvider serviceProvider, Activity refActivity) { Type type = null; string str = refActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string; if ((refActivity.Site != null) && !string.IsNullOrEmpty(str)) { ITypeProvider service = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider; if ((service != null) && !string.IsNullOrEmpty(str)) { type = service.GetType(str, false); } return type; } return refActivity.GetType(); }
/// <summary> /// Indicates whether a workflow instance is XOML-based or /// compiled from a DLL. /// </summary> /// <param name="rootActivity"> /// Root <see cref="Activity" /> of the workflow instance. /// </param> /// <returns> /// <c>true</c> if the workflow is XOML-based, <c>false</c> otherwise. /// </returns> public static bool IsXomlWorkflow(Activity rootActivity) { //HACK // retrieve the 'WorkflowXamlMarkupProperty' dependency property // from the activity using reflection, must be a better way of doing this?! // this method of doing things is stolen from System.Workflow using // reflector... BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public; FieldInfo fieldInfo = typeof (Activity).GetField("WorkflowXamlMarkupProperty", bindingFlags); DependencyProperty dependencyProperty = (DependencyProperty)fieldInfo.GetValue(null); string workflowXaml = rootActivity.GetValue(dependencyProperty) as string; if (!string.IsNullOrEmpty(workflowXaml)) return true; return false; }
private static CorrelationToken GetCorrelationToken(Activity activity) { DependencyProperty dependencyProperty = DependencyProperty.FromName("CorrelationToken", activity.GetType()); if (dependencyProperty == null) { dependencyProperty = DependencyProperty.FromName("CorrelationToken", activity.GetType().BaseType); } CorrelationToken token = activity.GetValue(dependencyProperty) as CorrelationToken; if (token == null) { throw new InvalidOperationException(SR.GetString("Error_CorrelationTokenMissing", new object[] { activity.Name })); } CorrelationToken token2 = CorrelationTokenCollection.GetCorrelationToken(activity, token.Name, token.OwnerActivityName); if (token2 == null) { throw new InvalidOperationException(SR.GetString("Error_CorrelationTokenMissing", new object[] { activity.Name })); } return token2; }
private void AddItemToBeScheduledLater(System.Workflow.ComponentModel.Activity atomicActivity, SchedulableItem item) { if ((atomicActivity != null) && atomicActivity.SupportsTransaction) { TransactionalProperties properties = (TransactionalProperties)atomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); if (properties != null) { lock (properties) { List <SchedulableItem> itemsToBeScheduledAtCompletion = null; itemsToBeScheduledAtCompletion = properties.ItemsToBeScheduledAtCompletion; if (itemsToBeScheduledAtCompletion == null) { itemsToBeScheduledAtCompletion = new List <SchedulableItem>(); properties.ItemsToBeScheduledAtCompletion = itemsToBeScheduledAtCompletion; } itemsToBeScheduledAtCompletion.Add(item); } } } }
private void ScheduleDelayedItems(System.Workflow.ComponentModel.Activity atomicActivity) { List <SchedulableItem> itemsToBeScheduledAtCompletion = null; TransactionalProperties properties = (TransactionalProperties)atomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); if (properties != null) { lock (properties) { itemsToBeScheduledAtCompletion = properties.ItemsToBeScheduledAtCompletion; if (itemsToBeScheduledAtCompletion != null) { foreach (SchedulableItem item in itemsToBeScheduledAtCompletion) { this.scheduler.ScheduleItem(item, false); } itemsToBeScheduledAtCompletion.Clear(); properties.ItemsToBeScheduledAtCompletion = null; } } } }
public WorkflowChanges(Activity rootActivity) { if (rootActivity == null) { throw new ArgumentNullException("rootActivity"); } if (!(rootActivity is CompositeActivity) || (rootActivity.Parent != null)) { throw new ArgumentException(SR.GetString("Error_RootActivityTypeInvalid2"), "rootActivity"); } if (rootActivity.DesignMode) { throw new InvalidOperationException(SR.GetString("Error_NoRuntimeAvailable")); } this.originalRootActivity = (Activity) rootActivity.GetValue(Activity.WorkflowDefinitionProperty); if (this.originalRootActivity == null) { this.originalRootActivity = rootActivity; } this.clonedRootActivity = CloneRootActivity(this.originalRootActivity); this.ApplyDynamicUpdateMode(this.clonedRootActivity); }
protected static byte[] GetDefaultSerializedForm(Activity activity) { byte[] buffer; DateTime now = DateTime.Now; using (MemoryStream stream = new MemoryStream(0x2800)) { stream.Position = 0L; activity.Save(stream); using (MemoryStream stream2 = new MemoryStream((int) stream.Length)) { using (GZipStream stream3 = new GZipStream(stream2, CompressionMode.Compress, true)) { stream3.Write(stream.GetBuffer(), 0, (int) stream.Length); } ActivityExecutionContextInfo info = (ActivityExecutionContextInfo) activity.GetValue(Activity.ActivityExecutionContextInfoProperty); TimeSpan span = (TimeSpan) (DateTime.Now - now); WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "Serialized a {0} with id {1} to length {2}. Took {3}.", new object[] { info, info.ContextGuid, stream2.Length, span }); buffer = stream2.GetBuffer(); Array.Resize<byte>(ref buffer, Convert.ToInt32(stream2.Length)); } } return buffer; }
private Activity FindExecutorForActivityDown(Activity contextActivity, string activityQualifiedName) { Queue <Activity> queue = new Queue <Activity>(); queue.Enqueue(contextActivity); while (queue.Count > 0) { Activity activity = queue.Dequeue(); Activity activityByName = activity.GetActivityByName(activityQualifiedName, true); if ((activityByName != null) && (activityByName.ExecutionStatus != ActivityExecutionStatus.Initialized)) { return(activity); } IList <Activity> list = (IList <Activity>)activity.GetValue(Activity.ActiveExecutionContextsProperty); if (list != null) { foreach (Activity activity3 in list) { queue.Enqueue(activity3); } } } return(null); }
public bool WalkProperties(Activity activity, object obj) { Activity currentActivity = obj as Activity; PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { // !!Work around: no indexer property walking if (prop.GetIndexParameters() != null && prop.GetIndexParameters().Length > 0) { continue; } DesignerSerializationVisibility visibility = GetSerializationVisibility(prop); if (visibility == DesignerSerializationVisibility.Hidden) { continue; } //Try to see if we have dynamic property associated with the object on the same object //if so then we should compare if the dynamic property values match with the property type //if not we bail out object propValue = null; DependencyProperty dependencyProperty = DependencyProperty.FromName(prop.Name, obj.GetType()); if (dependencyProperty != null && currentActivity != null) { if (currentActivity.IsBindingSet(dependencyProperty)) { propValue = currentActivity.GetBinding(dependencyProperty); } else { propValue = currentActivity.GetValue(dependencyProperty); } } else { try { propValue = prop.CanRead ? prop.GetValue(obj, null) : null; } catch { // Eat exceptions that occur while invoking the getter. } } if (FoundProperty != null) { WalkerEventArgs args = new WalkerEventArgs(activity, propValue, prop, obj); FoundProperty(this, args); if (args.Action == WalkerAction.Skip) { continue; } else if (args.Action == WalkerAction.Abort) { return(false); } } if (propValue is IList) { //We do not need to reflect on the properties of the list foreach (object childObj in (IList)propValue) { if (FoundProperty != null) { WalkerEventArgs args = new WalkerEventArgs(activity, childObj, null, propValue); FoundProperty(this, args); if (args.Action == WalkerAction.Skip) { continue; } else if (args.Action == WalkerAction.Abort) { return(false); } } if (childObj != null && IsBrowsableType(childObj.GetType())) { if (!WalkProperties(activity, childObj)) { return(false); } } } } else if (propValue != null && IsBrowsableType(propValue.GetType())) { if (!WalkProperties(activity, propValue)) { return(false); } } } return(true); }
protected override bool ApplyTo(Activity rootActivity) { if (rootActivity == null) return false; RuleDefinitions rules = rootActivity.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; if (rules == null) { rules = new RuleDefinitions(); ((Activity)rootActivity).SetValue(RuleDefinitions.RuleDefinitionsProperty, rules); } // bool setRuntimeMode = false; if (rules.Conditions.RuntimeMode) { rules.Conditions.RuntimeMode = false; setRuntimeMode = true; } try { rules.Conditions.Add(this.ConditionDefinition); } finally { if (setRuntimeMode) rules.Conditions.RuntimeMode = true; } return true; }
protected override bool ApplyTo(Activity rootActivity) { if (rootActivity == null) return false; RuleDefinitions rules = rootActivity.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; if (rules == null || rules.RuleSets == null) return false; if (rules.RuleSets[RuleSetName] == null) return false; // bool setRuntimeMode = false; if (rules.Conditions.RuntimeMode) { rules.Conditions.RuntimeMode = false; setRuntimeMode = true; } try { rules.RuleSets.Remove(RuleSetName); rules.RuleSets.Add(updated); } finally { if (setRuntimeMode) rules.RuleSets.RuntimeMode = true; } return true; }
internal RTTrackingProfile GetProfile(TrackingService service, Activity schedule) { if (!this._init) { throw new ApplicationException(ExecutionStringManager.TrackingProfileManagerNotInitialized); } if ((service == null) || (schedule == null)) { WorkflowTrace.Tracking.TraceEvent(TraceEventType.Error, 0, ExecutionStringManager.NullParameters); return null; } Type workflowType = schedule.GetType(); RTTrackingProfile profile = null; if ((service is IProfileNotification) && this.TryGetFromCache(service.GetType(), workflowType, out profile)) { return profile; } TrackingProfile profile2 = null; if (!service.TryGetProfile(workflowType, out profile2)) { this.RemoveProfile(workflowType, service.GetType()); return null; } if (this.TryGetFromCache(service.GetType(), workflowType, profile2.Version, out profile)) { return profile; } string str = schedule.GetValue(Activity.WorkflowXamlMarkupProperty) as string; if ((str != null) && (str.Length > 0)) { return this.CreateProfile(profile2, schedule, service.GetType()); } profile = this.CreateProfile(profile2, workflowType, service.GetType()); lock (this._cacheLock) { RTTrackingProfile profile3 = null; if (this.TryGetFromCache(service.GetType(), workflowType, profile2.Version, out profile3)) { return profile3; } if (!this.AddToCache(profile, service.GetType())) { throw new ApplicationException(ExecutionStringManager.ProfileCacheInsertFailure); } return profile; } }
internal void ApplyTo(Activity activity) { if (activity == null) { throw new ArgumentNullException("activity"); } if (activity.Parent != null) { throw new ArgumentException(SR.GetString("Error_RootActivityTypeInvalid"), "activity"); } if (activity.RootActivity == null) { throw new InvalidOperationException(SR.GetString("Error_MissingRootActivity")); } if (activity.WorkflowCoreRuntime == null) { throw new InvalidOperationException(SR.GetString("Error_NoRuntimeAvailable")); } if (this.saved) { throw new InvalidOperationException(SR.GetString("Error_TransactionAlreadyApplied")); } if (!CompareWorkflowDefinition(this.originalRootActivity, (Activity)activity.RootActivity.GetValue(Activity.WorkflowDefinitionProperty))) { throw new ArgumentException(SR.GetString("Error_WorkflowDefinitionModified"), "activity"); } this.Save(); IWorkflowCoreRuntime workflowCoreRuntime = activity.WorkflowCoreRuntime; if (workflowCoreRuntime.CurrentAtomicActivity != null) { throw new InvalidOperationException(SR.GetString("Error_InsideAtomicScope")); } bool flag = workflowCoreRuntime.SuspendInstance(SR.GetString("SuspendReason_WorkflowChange")); try { List <Activity> list = new List <Activity>(); Queue <Activity> queue = new Queue <Activity>(); queue.Enqueue(workflowCoreRuntime.RootActivity); while (queue.Count > 0) { Activity item = queue.Dequeue(); list.Add(item); IList <Activity> list2 = (IList <Activity>)item.GetValue(Activity.ActiveExecutionContextsProperty); if (list2 != null) { foreach (Activity activity3 in list2) { queue.Enqueue(activity3); } } } ValidationErrorCollection errors = new ValidationErrorCollection(); foreach (WorkflowChangeAction action in this.modelChangeActions) { if (action is ActivityChangeAction) { foreach (Activity activity4 in list) { if ((action is RemovedActivityAction) && (activity4.DottedPath == ((RemovedActivityAction)action).OriginalRemovedActivity.DottedPath)) { errors.AddRange(action.ValidateChanges(activity4)); } if (activity4.TraverseDottedPathFromRoot(((ActivityChangeAction)action).OwnerActivityDottedPath) != null) { errors.AddRange(action.ValidateChanges(activity4)); } } } } if (errors.HasErrors) { throw new WorkflowValidationFailedException(SR.GetString("Error_RuntimeValidationFailed"), errors); } this.VerifyWorkflowCanBeChanged(workflowCoreRuntime); workflowCoreRuntime.OnBeforeDynamicChange(this.modelChangeActions); workflowCoreRuntime.RootActivity.SetValue(Activity.WorkflowDefinitionProperty, this.clonedRootActivity); foreach (Activity activity5 in list) { foreach (WorkflowChangeAction action2 in this.modelChangeActions) { if ((action2 is ActivityChangeAction) && (activity5.TraverseDottedPathFromRoot(((ActivityChangeAction)action2).OwnerActivityDottedPath) != null)) { action2.ApplyTo(activity5); } } Activity activityByName = this.clonedRootActivity.GetActivityByName(activity5.QualifiedName); if (activityByName != null) { activity5.FixUpMetaProperties(activityByName); } this.NotifyChangesToChildExecutors(workflowCoreRuntime, activity5, this.modelChangeActions); this.NotifyChangesCompletedToChildExecutors(workflowCoreRuntime, activity5); } workflowCoreRuntime.OnAfterDynamicChange(true, this.modelChangeActions); } catch { workflowCoreRuntime.OnAfterDynamicChange(false, this.modelChangeActions); throw; } finally { if (flag) { workflowCoreRuntime.Resume(); } } }
private static bool TryCompensateLastCompletedChildActivity(ActivityExecutionContext context, Activity targetActivity, IActivityEventListener <ActivityExecutionStatusChangedEventArgs> statusChangeHandler, bool isimmediateCompensation) { SortedDictionary <int, CompensationInfo> sortedListOfCompensatableTargets = new SortedDictionary <int, CompensationInfo>(); if (targetActivity is CompositeActivity) { if (CollectCompensatableTargetActivities(targetActivity as CompositeActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) { return(true); } if (CollectCompensatableActiveContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) { return(true); } CollectCompensatableCompletedContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation); if (sortedListOfCompensatableTargets.Count == 0) { CompleteRevokedExecutionContext(targetActivity, context); return(false); } int?nullable = targetActivity.GetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty) as int?; int num = -1; CompensationInfo info = null; foreach (int num2 in sortedListOfCompensatableTargets.Keys) { if (nullable.HasValue) { int?nullable2 = nullable; int num3 = num2; if ((nullable2.GetValueOrDefault() < num3) && nullable2.HasValue) { break; } } info = sortedListOfCompensatableTargets[num2]; num = num2; } if (info == null) { CompleteRevokedExecutionContext(targetActivity, context); return(false); } targetActivity.SetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty, num); if ((info.TargetActivity != null) && (info.TargetActivity is ICompensatableActivity)) { info.TargetActivity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context.CompensateActivity(info.TargetActivity); return(true); } if ((info.TargetExecutionInfo != null) && (info.TargetExecutionContextManager != null)) { ActivityExecutionContext context2 = info.TargetExecutionContextManager.DiscardPersistedExecutionContext(info.TargetExecutionInfo); if (context2.Activity is ICompensatableActivity) { context2.Activity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context2.CompensateActivity(context2.Activity); return(true); } if (context2.Activity is CompositeActivity) { Activity lastCompensatableChild = GetLastCompensatableChild(context2.Activity as CompositeActivity); if (lastCompensatableChild != null) { lastCompensatableChild.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context2.CompensateActivity(lastCompensatableChild); return(true); } return(TryCompensateLastCompletedChildActivity(context2, context2.Activity, statusChangeHandler, false)); } } else if ((info.TargetExecutionContext != null) && (info.TargetExecutionContext.Activity is CompositeActivity)) { Activity activity = GetLastCompensatableChild(info.TargetExecutionContext.Activity as CompositeActivity); if (activity != null) { activity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); info.TargetExecutionContext.CompensateActivity(activity); return(true); } return(TryCompensateLastCompletedChildActivity(info.TargetExecutionContext, info.TargetExecutionContext.Activity, statusChangeHandler, false)); } } return(false); }
protected internal override void SaveCompletedContextActivity(Activity completedScopeActivity) { PendingWorkItem workItem = new PendingWorkItem { Type = PendingWorkItem.ItemType.CompletedScope, SerializedActivity = WorkflowPersistenceService.GetDefaultSerializedForm(completedScopeActivity), InstanceId = WorkflowEnvironment.WorkflowInstanceId, StateId = ((ActivityExecutionContextInfo) completedScopeActivity.GetValue(Activity.ActivityExecutionContextInfoProperty)).ContextGuid }; WorkflowEnvironment.WorkBatch.Add(this, workItem); }
internal static WorkflowTransactionOptions GetTransactionOptions(Activity activity) { return(activity.GetValue((activity is TransactionScopeActivity) ? TransactionScopeActivity.TransactionOptionsProperty : CompensatableTransactionScopeActivity.TransactionOptionsProperty) as WorkflowTransactionOptions); }
/// <summary> /// Persist a workflow instance to the persistence store. /// </summary> /// <param name="rootActivity"> /// Root activity of the workflow instance. /// </param> /// <param name="unlock"> /// Indicates whether to unlock the instance when complete. /// </param> protected override void SaveWorkflowInstanceState(Activity rootActivity, bool unlock) { TraceHelper.Trace(); try { if (rootActivity == null) throw new ArgumentNullException("rootActivity"); PendingWorkItem workItem = new PendingWorkItem(); workItem.Status = GetWorkflowStatus(rootActivity); workItem.IsBlocked = GetIsBlocked(rootActivity); workItem.Info = GetSuspendOrTerminateInfo(rootActivity); workItem.StateId = (Guid) rootActivity.GetValue(Activity.ActivityContextGuidProperty); workItem.Type = PendingWorkItem.ItemType.Instance; workItem.InstanceId = WorkflowEnvironment.WorkflowInstanceId; workItem.Unlock = unlock; if (workItem.Status != WorkflowStatus.Completed && workItem.Status != WorkflowStatus.Terminated) workItem.SerialisedActivity = GetDefaultSerializedForm(rootActivity); else workItem.SerialisedActivity = new byte[0]; TimerEventSubscription timerEventSubscription = ((TimerEventSubscriptionCollection) rootActivity.GetValue( TimerEventSubscriptionCollection.TimerCollectionProperty)).Peek(); if (timerEventSubscription == null) workItem.NextTimer = null; else workItem.NextTimer = timerEventSubscription.ExpiresAt; WorkflowEnvironment.WorkBatch.Add(this, workItem); } catch (Exception e) { Tracer.Debug("�־û�SaveWorkflowInstanceState�����쳣:" + e.ToString()); string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString()); TraceHelper.Trace(errorMessage); PersistenceException persistenceException = new PersistenceException(errorMessage, e); base.RaiseServicesExceptionNotHandledEvent( persistenceException, WorkflowEnvironment.WorkflowInstanceId); throw persistenceException; } }
public void Reload(System.Workflow.ComponentModel.Activity definitionActivity, IList <PropertyInfo> outputProperties) { MemoryStream stream = new MemoryStream(this.persistedActivityData); System.Workflow.ComponentModel.Activity rootActivity = null; stream.Position = 0L; using (new ActivityDefinitionResolution(definitionActivity)) { rootActivity = System.Workflow.ComponentModel.Activity.Load(stream, null); } this.PrivateInitialize(rootActivity, this.instanceId, outputProperties, definitionActivity); Queue <System.Workflow.ComponentModel.Activity> queue = new Queue <System.Workflow.ComponentModel.Activity>(); queue.Enqueue(rootActivity); while (queue.Count > 0) { System.Workflow.ComponentModel.Activity activity = queue.Dequeue(); ((IDependencyObjectAccessor)activity).InitializeInstanceForRuntime(this); this.RegisterContextActivity(activity); IList <System.Workflow.ComponentModel.Activity> list = (IList <System.Workflow.ComponentModel.Activity>)activity.GetValue(System.Workflow.ComponentModel.Activity.ActiveExecutionContextsProperty); if (list != null) { foreach (System.Workflow.ComponentModel.Activity activity3 in list) { queue.Enqueue(activity3); } } } if (!string.IsNullOrEmpty(this.internalCurrentActivityName)) { this.internalCurrentActivity = this.GetContextActivityForId(this.internalCurrentActivityContextId).GetActivityByName(this.internalCurrentActivityName); } if (!string.IsNullOrEmpty(this.atomicActivityName)) { this.currentAtomicActivity = this.GetContextActivityForId(this.atomicActivityContextId).GetActivityByName(this.atomicActivityName); } this.TimerQueue.Executor = this; }
private bool AcquireLocks(Activity activity) { // If this activity doesn't have any handles, we have nothing to do. ICollection <string> handles = GetAllSynchronizationHandles(activity); if (handles == null || handles.Count == 0) { return(true); } Activity parent = activity.Parent; while (parent != null) { if (parent.SupportsSynchronization || parent.Parent == null) { Dictionary <string, GrantedLock> grantedLocks = (Dictionary <string, GrantedLock>)parent.GetValue(GrantedLocksProperty); if (grantedLocks == null) { grantedLocks = new Dictionary <string, GrantedLock>(); parent.SetValue(GrantedLocksProperty, grantedLocks); } foreach (string handle in handles) { bool acquiredLocks = true; if (!grantedLocks.ContainsKey(handle)) { grantedLocks[handle] = new GrantedLock(activity); } else if (grantedLocks[handle].Holder != activity) { grantedLocks[handle].WaitList.Add(activity); acquiredLocks = false; } if (!acquiredLocks) { return(false); } } } // If we reach a parent which has at least one handle, then we do not need to // go any further as the parent would already have acquired all our locks for // itself. Note that we still need to acquire our locks in the same parent if // the parent ProvidesSychronization, hence, this if check is *not* after // "parent = parent.Parent"! ICollection <string> synchronizationHandlesOnParent = (ICollection <string>)parent.GetValue(Activity.SynchronizationHandlesProperty); if (synchronizationHandlesOnParent != null && synchronizationHandlesOnParent.Count != 0) { break; } parent = parent.Parent; } return(true); }
private static bool TryCompensateLastCompletedChildActivity(ActivityExecutionContext context, Activity targetActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs> statusChangeHandler, bool isimmediateCompensation) { SortedDictionary<int, CompensationInfo> sortedListOfCompensatableTargets = new SortedDictionary<int, CompensationInfo>(); if (targetActivity is CompositeActivity) { if (CollectCompensatableTargetActivities(targetActivity as CompositeActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) { return true; } if (CollectCompensatableActiveContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) { return true; } CollectCompensatableCompletedContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation); if (sortedListOfCompensatableTargets.Count == 0) { CompleteRevokedExecutionContext(targetActivity, context); return false; } int? nullable = targetActivity.GetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty) as int?; int num = -1; CompensationInfo info = null; foreach (int num2 in sortedListOfCompensatableTargets.Keys) { if (nullable.HasValue) { int? nullable2 = nullable; int num3 = num2; if ((nullable2.GetValueOrDefault() < num3) && nullable2.HasValue) { break; } } info = sortedListOfCompensatableTargets[num2]; num = num2; } if (info == null) { CompleteRevokedExecutionContext(targetActivity, context); return false; } targetActivity.SetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty, num); if ((info.TargetActivity != null) && (info.TargetActivity is ICompensatableActivity)) { info.TargetActivity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context.CompensateActivity(info.TargetActivity); return true; } if ((info.TargetExecutionInfo != null) && (info.TargetExecutionContextManager != null)) { ActivityExecutionContext context2 = info.TargetExecutionContextManager.DiscardPersistedExecutionContext(info.TargetExecutionInfo); if (context2.Activity is ICompensatableActivity) { context2.Activity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context2.CompensateActivity(context2.Activity); return true; } if (context2.Activity is CompositeActivity) { Activity lastCompensatableChild = GetLastCompensatableChild(context2.Activity as CompositeActivity); if (lastCompensatableChild != null) { lastCompensatableChild.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context2.CompensateActivity(lastCompensatableChild); return true; } return TryCompensateLastCompletedChildActivity(context2, context2.Activity, statusChangeHandler, false); } } else if ((info.TargetExecutionContext != null) && (info.TargetExecutionContext.Activity is CompositeActivity)) { Activity activity = GetLastCompensatableChild(info.TargetExecutionContext.Activity as CompositeActivity); if (activity != null) { activity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); info.TargetExecutionContext.CompensateActivity(activity); return true; } return TryCompensateLastCompletedChildActivity(info.TargetExecutionContext, info.TargetExecutionContext.Activity, statusChangeHandler, false); } } return false; }
internal static RuleDefinitions Load_Rules_RT(Activity declaringActivity) { RuleDefinitions rules = declaringActivity.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; if (rules == null) { rules = ConditionHelper.GetRuleDefinitionsFromManifest(declaringActivity.GetType()); if (rules != null) declaringActivity.SetValue(RuleDefinitions.RuleDefinitionsProperty, rules); } return rules; }
private static Activity CloneRootActivity(Activity originalRootActivity) { string str = originalRootActivity.GetValue(Activity.WorkflowXamlMarkupProperty) as string; string rulesMarkup = null; Activity rootActivity = null; IServiceProvider serviceProvider = originalRootActivity.GetValue(Activity.WorkflowRuntimeProperty) as IServiceProvider; if (!string.IsNullOrEmpty(str)) { rulesMarkup = originalRootActivity.GetValue(Activity.WorkflowRulesMarkupProperty) as string; rootActivity = Activity.OnResolveActivityDefinition(null, str, rulesMarkup, true, false, serviceProvider); } else { rootActivity = Activity.OnResolveActivityDefinition(originalRootActivity.GetType(), null, null, true, false, serviceProvider); } if (rootActivity == null) { throw new NullReferenceException(SR.GetString("Error_InvalidRootForWorkflowChanges")); } ArrayList workflowChanges = (ArrayList) originalRootActivity.GetValue(WorkflowChangeActionsProperty); if (workflowChanges != null) { workflowChanges = CloneWorkflowChangeActions(workflowChanges, originalRootActivity); if (workflowChanges == null) { return rootActivity; } foreach (WorkflowChangeAction action in workflowChanges) { action.ApplyTo(rootActivity); } rootActivity.SetValue(WorkflowChangeActionsProperty, workflowChanges); } return rootActivity; }
protected internal override void SaveWorkflowInstanceState(Activity rootActivity, bool unlock) { if (rootActivity == null) { throw new ArgumentNullException("rootActivity"); } WorkflowStatus workflowStatus = WorkflowPersistenceService.GetWorkflowStatus(rootActivity); bool isBlocked = WorkflowPersistenceService.GetIsBlocked(rootActivity); string suspendOrTerminateInfo = WorkflowPersistenceService.GetSuspendOrTerminateInfo(rootActivity); Guid guid = (Guid) rootActivity.GetValue(Activity.ActivityContextGuidProperty); PendingWorkItem workItem = new PendingWorkItem { Type = PendingWorkItem.ItemType.Instance, InstanceId = WorkflowEnvironment.WorkflowInstanceId }; if ((workflowStatus != WorkflowStatus.Completed) && (workflowStatus != WorkflowStatus.Terminated)) { workItem.SerializedActivity = WorkflowPersistenceService.GetDefaultSerializedForm(rootActivity); } else { workItem.SerializedActivity = new byte[0]; } workItem.Status = (int) workflowStatus; workItem.Blocked = isBlocked ? 1 : 0; workItem.Info = suspendOrTerminateInfo; workItem.StateId = guid; workItem.Unlocked = unlock; TimerEventSubscription subscription = ((TimerEventSubscriptionCollection) rootActivity.GetValue(TimerEventSubscriptionCollection.TimerCollectionProperty)).Peek(); workItem.NextTimer = (subscription == null) ? SqlDateTime.MaxValue : subscription.ExpiresAt; if (workItem.Info == null) { workItem.Info = ""; } WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlWorkflowPersistenceService({4}):Committing instance {0}, Blocked={1}, Unlocked={2}, NextTimer={3}", new object[] { guid.ToString(), workItem.Blocked, workItem.Unlocked, workItem.NextTimer.Value.ToLocalTime(), this._serviceInstanceId.ToString() }); WorkflowEnvironment.WorkBatch.Add(this, workItem); }
private static bool CompareWorkflowDefinition(Activity originalWorkflowDefinition, Activity currentWorkflowDefinition) { if (originalWorkflowDefinition == currentWorkflowDefinition) { return true; } if (originalWorkflowDefinition.GetType() != currentWorkflowDefinition.GetType()) { return false; } Guid guid = (Guid) originalWorkflowDefinition.GetValue(WorkflowChangeVersionProperty); Guid guid2 = (Guid) currentWorkflowDefinition.GetValue(WorkflowChangeVersionProperty); return (guid == guid2); }
internal static void Flush_Rules_DT(IServiceProvider serviceProvider, Activity activity) { RuleDefinitions rules = (RuleDefinitions)activity.GetValue(RuleDefinitions.RuleDefinitionsProperty); if (rules != null) { WorkflowDesignerLoader loader = (WorkflowDesignerLoader)serviceProvider.GetService(typeof(WorkflowDesignerLoader)); if (loader != null) { string rulesFileName = string.Empty; if (!string.IsNullOrEmpty(loader.FileName)) rulesFileName = Path.Combine(Path.GetDirectoryName(loader.FileName), Path.GetFileNameWithoutExtension(loader.FileName)); rulesFileName += ".rules"; using (TextWriter ruleFileWriter = loader.GetFileWriter(rulesFileName)) { if (ruleFileWriter != null) { using (XmlWriter xmlWriter = Helpers.CreateXmlWriter(ruleFileWriter)) { DesignerSerializationManager designerSerializationManager = new DesignerSerializationManager(serviceProvider); using (designerSerializationManager.CreateSession()) { new WorkflowMarkupSerializer().Serialize(designerSerializationManager, xmlWriter, rules); } } } } } } }
/// <summary> /// Persist a completed scope to the persistence store. /// </summary> /// <param name="activity"> /// The completed scope to pesist. /// </param> protected override void SaveCompletedContextActivity(Activity activity) { TraceHelper.Trace(); try { PendingWorkItem workItem = new PendingWorkItem(); workItem.Type = PendingWorkItem.ItemType.CompletedScope; workItem.SerialisedActivity = GetDefaultSerializedForm(activity); workItem.InstanceId = WorkflowEnvironment.WorkflowInstanceId; workItem.StateId = (Guid)activity.GetValue( Activity.ActivityContextGuidProperty); WorkflowEnvironment.WorkBatch.Add(this, workItem); } catch (Exception e) { string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString()); TraceHelper.Trace(errorMessage); PersistenceException persistenceException = new PersistenceException(errorMessage, e); base.RaiseServicesExceptionNotHandledEvent( persistenceException, WorkflowEnvironment.WorkflowInstanceId); throw persistenceException; } }
internal void ReleaseLocks(bool transactional) { if (this.currentActivity == null) { throw new ObjectDisposedException("ActivityExecutionContext"); } // remove the callback. this.Activity.RemoveProperty(LockAcquiredCallbackProperty); // The assumption is that lock contentions will be few. Hence, we optimize serialization // size over performance, for ex. do not persist the list of locks that have already been // granted. ICollection <string> handles = GetAllSynchronizationHandles(this.Activity); if (handles == null || handles.Count == 0) { return; } List <Activity> waitingActivities = new List <Activity>(); Activity parent = Activity.Parent; while (parent != null) { if (parent.SupportsSynchronization || parent.Parent == null) { Dictionary <string, GrantedLock> grantedLocks = (Dictionary <string, GrantedLock>)parent.GetValue(GrantedLocksProperty); // if its an transactional release of locks, then release it and then keep it // cached, so that in case of rollback, we can reacuire locks if (transactional) { Dictionary <string, GrantedLock> cachedGrantedLocks = new Dictionary <string, GrantedLock>(); if (grantedLocks != null) { foreach (KeyValuePair <string, GrantedLock> grantedLockEntry in grantedLocks) { cachedGrantedLocks.Add(grantedLockEntry.Key, (GrantedLock)grantedLockEntry.Value.Clone()); } } parent.SetValue(CachedGrantedLocksProperty, cachedGrantedLocks); } if (grantedLocks != null) { foreach (string handle in handles) { if (!grantedLocks.ContainsKey(handle)) { continue; } else if (grantedLocks[handle].WaitList.Count == 0) { grantedLocks.Remove(handle); } else if (grantedLocks[handle].Holder != this.Activity) { grantedLocks[handle].WaitList.Remove(this.Activity); } else { // Grant the lock to the next waiting activity. Activity waitingActivity = grantedLocks[handle].WaitList[0]; grantedLocks[handle].WaitList.RemoveAt(0); grantedLocks[handle].Holder = waitingActivity; if (!waitingActivities.Contains(waitingActivity)) { waitingActivities.Add(waitingActivity); } } } if (grantedLocks.Count == 0) { parent.RemoveProperty(GrantedLocksProperty); } } } // If we reach a parent which has at least one handle, then we do not need to // go any further as the parent would already have acquired all our locks for // itself. Note that we still need to acquire our locks in the same parent if // the parent ProvidesSychronization, hence, this if check is *not* after // "parent = parent.Parent"! ICollection <string> synchronizationHandlesOnParent = (ICollection <string>)parent.GetValue(Activity.SynchronizationHandlesProperty); if (synchronizationHandlesOnParent != null && synchronizationHandlesOnParent.Count != 0) { break; } parent = parent.Parent; } // Try and acquire locks for all the waiting activities. foreach (Activity waitingActivity in waitingActivities) { if (AcquireLocks(waitingActivity)) { ActivityExecutorDelegateInfo <EventArgs> waitingActivityCallback = (ActivityExecutorDelegateInfo <EventArgs>)waitingActivity.GetValue(LockAcquiredCallbackProperty); waitingActivityCallback.InvokeDelegate(this.Activity.ContextActivity, EventArgs.Empty, false, transactional); } } }
internal RTTrackingProfile GetProfile(TrackingService service, Activity workflow, Version versionId) { if (service == null) { throw new ArgumentNullException("service"); } if (workflow == null) { throw new ArgumentNullException("workflow"); } if (!this._init) { throw new InvalidOperationException(ExecutionStringManager.TrackingProfileManagerNotInitialized); } Type workflowType = workflow.GetType(); RTTrackingProfile profile = null; if (this.TryGetFromCache(service.GetType(), workflowType, versionId, out profile)) { return profile; } TrackingProfile profile2 = service.GetProfile(workflowType, versionId); string str = workflow.GetValue(Activity.WorkflowXamlMarkupProperty) as string; if ((str != null) && (str.Length > 0)) { return this.CreateProfile(profile2, workflow, service.GetType()); } profile = this.CreateProfile(profile2, workflowType, service.GetType()); lock (this._cacheLock) { RTTrackingProfile profile3 = null; if (this.TryGetFromCache(service.GetType(), workflowType, versionId, out profile3)) { return profile3; } if (!this.AddToCache(profile, service.GetType())) { throw new ApplicationException(ExecutionStringManager.ProfileCacheInsertFailure); } return profile; } }
private static bool TryCompensateLastCompletedChildActivity(ActivityExecutionContext context, Activity targetActivity, IActivityEventListener <ActivityExecutionStatusChangedEventArgs> statusChangeHandler, bool isimmediateCompensation) { SortedDictionary <int, CompensationInfo> sortedListOfCompensatableTargets = new SortedDictionary <int, CompensationInfo>(); if (!(targetActivity is CompositeActivity)) { return(false); } //Walk through all of the direct children which are compensatable and add them in the sorted order of their completion //bail out if any of the compensatable children is currently compensating/faulting or canceling if (CollectCompensatableTargetActivities(targetActivity as CompositeActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) { return(true); } // walk through active contexts that contain compensatable child, add them in the sorted order of the completion // this also, walks through the completed contexts which are compensatable and are nested directly within the active contexts and adds them in the order of their completion // bail out if any activity is currently compensating/faulting or cancelling if (CollectCompensatableActiveContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation)) { return(true); } // walk through all completed execution contexts which are compensatable and are directly nested under the target activity, //and add them to our sorted list CollectCompensatableCompletedContexts(context, targetActivity, sortedListOfCompensatableTargets, isimmediateCompensation); //if there were no compensatable targets found, bail out if (sortedListOfCompensatableTargets.Count == 0) { CompleteRevokedExecutionContext(targetActivity, context); return(false); } int?lastCompletedOrderId = targetActivity.GetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty) as Nullable <int>; int nextLastCompletedOrderId = -1; //get the last compensatable target - this could be an activity, contextInfo or a Context CompensationInfo lastCompensatableTarget = null; foreach (int completedOrderId in sortedListOfCompensatableTargets.Keys) { if (lastCompletedOrderId.HasValue && lastCompletedOrderId < completedOrderId) { break; } lastCompensatableTarget = sortedListOfCompensatableTargets[completedOrderId]; nextLastCompletedOrderId = completedOrderId; } //We are done with compensation on entire branch, now complete execution contexts //recursilvely which we might have opened up. if (lastCompensatableTarget == null) { CompleteRevokedExecutionContext(targetActivity, context); return(false); } targetActivity.SetValue(CompensationHandlingFilter.LastCompensatedOrderIdProperty, nextLastCompletedOrderId); //the last compensatable target could be an activity if (lastCompensatableTarget.TargetActivity != null && lastCompensatableTarget.TargetActivity is ICompensatableActivity) { lastCompensatableTarget.TargetActivity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); context.CompensateActivity(lastCompensatableTarget.TargetActivity); return(true); } //or get the last compensatable "completed" context else if (lastCompensatableTarget.TargetExecutionInfo != null && lastCompensatableTarget.TargetExecutionContextManager != null) { ActivityExecutionContext revokedExecutionContext = lastCompensatableTarget.TargetExecutionContextManager.DiscardPersistedExecutionContext(lastCompensatableTarget.TargetExecutionInfo); //get the "first" compensatable child and compensate it if (revokedExecutionContext.Activity is ICompensatableActivity) { revokedExecutionContext.Activity.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); revokedExecutionContext.CompensateActivity(revokedExecutionContext.Activity); return(true); } else if (revokedExecutionContext.Activity is CompositeActivity) { //get the last compensatable child of the revoked context Activity compensatableChild = GetLastCompensatableChild(revokedExecutionContext.Activity as CompositeActivity); if (compensatableChild != null) { compensatableChild.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); revokedExecutionContext.CompensateActivity(compensatableChild); return(true); } else// recursively, walk the context tree and keep revoking the compensatable contexts { return(TryCompensateLastCompletedChildActivity(revokedExecutionContext, revokedExecutionContext.Activity, statusChangeHandler, false)); } } } else if (lastCompensatableTarget.TargetExecutionContext != null) //or get the last compensatable "active" context { if (lastCompensatableTarget.TargetExecutionContext.Activity is CompositeActivity) { //get the last compensatable child of the active context Activity compensatableChild = GetLastCompensatableChild(lastCompensatableTarget.TargetExecutionContext.Activity as CompositeActivity); if (compensatableChild != null) { compensatableChild.RegisterForStatusChange(Activity.StatusChangedEvent, statusChangeHandler); lastCompensatableTarget.TargetExecutionContext.CompensateActivity(compensatableChild); return(true); } else // recursively, walk the context tree and keep revoking the compensatable contexts { return(TryCompensateLastCompletedChildActivity(lastCompensatableTarget.TargetExecutionContext, lastCompensatableTarget.TargetExecutionContext.Activity, statusChangeHandler, false)); } } } return(false); }
private static bool CompareWorkflowDefinition(Activity originalWorkflowDefinition, Activity currentWorkflowDefinition) { if (originalWorkflowDefinition == currentWorkflowDefinition) return true; if (originalWorkflowDefinition.GetType() != currentWorkflowDefinition.GetType()) return false; Guid originalChangeVersion = (Guid)originalWorkflowDefinition.GetValue(WorkflowChanges.WorkflowChangeVersionProperty); Guid currentChangeVersion = (Guid)currentWorkflowDefinition.GetValue(WorkflowChanges.WorkflowChangeVersionProperty); return (originalChangeVersion == currentChangeVersion); }
public ActivityExecutionContext GetExecutionContext(Activity activity) { if (this.ownerContext == null) throw new ObjectDisposedException("ActivityExecutionContextManager"); if (activity == null) throw new ArgumentNullException("activity"); ActivityExecutionContextInfo contextInfo = activity.GetValue(Activity.ActivityExecutionContextInfoProperty) as ActivityExecutionContextInfo; // Returns the first context for an activity with the same qualified name. foreach (ActivityExecutionContext context in ExecutionContexts) { if (contextInfo == null) //Template being passed. { if (context.Activity.ContextActivity.QualifiedName == activity.QualifiedName) return context; } else //Context Sensitive Activity { if (context.ContextGuid.Equals(contextInfo.ContextGuid)) return context; } } return null; }
private static Activity CloneRootActivity(Activity originalRootActivity) { // create new definition root string xomlText = originalRootActivity.GetValue(Activity.WorkflowXamlMarkupProperty) as string; string rulesText = null; Activity clonedRootActivity = null; IServiceProvider serviceProvider = originalRootActivity.GetValue(Activity.WorkflowRuntimeProperty) as IServiceProvider; Debug.Assert(serviceProvider != null); if (!string.IsNullOrEmpty(xomlText)) { rulesText = originalRootActivity.GetValue(Activity.WorkflowRulesMarkupProperty) as string; clonedRootActivity = Activity.OnResolveActivityDefinition(null, xomlText, rulesText, true, false, serviceProvider); } else clonedRootActivity = Activity.OnResolveActivityDefinition(originalRootActivity.GetType(), null, null, true, false, serviceProvider); if (clonedRootActivity == null) throw new NullReferenceException(SR.GetString(SR.Error_InvalidRootForWorkflowChanges)); // deserialize change history and apply it to new definition tree ArrayList workflowChanges = (ArrayList)((Activity)originalRootActivity).GetValue(WorkflowChanges.WorkflowChangeActionsProperty); if (workflowChanges != null) { workflowChanges = CloneWorkflowChangeActions(workflowChanges, originalRootActivity); if (workflowChanges != null) { // apply changes to the shared schedule Defn to get the instance specific copy foreach (WorkflowChangeAction action in workflowChanges) { bool result = action.ApplyTo((Activity)clonedRootActivity); Debug.Assert(result, "ApplyTo Failed"); } ((Activity)clonedRootActivity).SetValue(WorkflowChanges.WorkflowChangeActionsProperty, workflowChanges); } } return clonedRootActivity; }
internal void ApplyTo(Activity activity) { if (activity == null) { throw new ArgumentNullException("activity"); } if (activity.Parent != null) { throw new ArgumentException(SR.GetString(SR.Error_RootActivityTypeInvalid), "activity"); } if (activity.RootActivity == null) { throw new InvalidOperationException(SR.GetString(SR.Error_MissingRootActivity)); } if (activity.WorkflowCoreRuntime == null) { throw new InvalidOperationException(SR.GetString(SR.Error_NoRuntimeAvailable)); } if (this.saved) { throw new InvalidOperationException(SR.GetString(SR.Error_TransactionAlreadyApplied)); } if (!CompareWorkflowDefinition((Activity)this.originalRootActivity, (Activity)activity.RootActivity.GetValue(Activity.WorkflowDefinitionProperty))) { throw new ArgumentException(SR.GetString(SR.Error_WorkflowDefinitionModified), "activity"); } this.Save(); // go up in the chain and then apply changes IWorkflowCoreRuntime workflowCoreRuntime = activity.WorkflowCoreRuntime; if (workflowCoreRuntime.CurrentAtomicActivity != null) { throw new InvalidOperationException(SR.GetString(SR.Error_InsideAtomicScope)); } bool suspended = workflowCoreRuntime.SuspendInstance(SR.GetString(SR.SuspendReason_WorkflowChange)); try { // collect all context Activities List <Activity> contextActivities = new List <Activity>(); Queue <Activity> contextActivitiesQueue = new Queue <Activity>(); contextActivitiesQueue.Enqueue(workflowCoreRuntime.RootActivity); while (contextActivitiesQueue.Count > 0) { Activity contextActivity = contextActivitiesQueue.Dequeue(); contextActivities.Add(contextActivity); // enqueue child context Activities IList <Activity> nestedContextActivities = (IList <Activity>)contextActivity.GetValue(Activity.ActiveExecutionContextsProperty); if (nestedContextActivities != null) { foreach (Activity nestedContextActivity in nestedContextActivities) { contextActivitiesQueue.Enqueue(nestedContextActivity); } } } // run instance level validations ValidationErrorCollection validationErrors = new ValidationErrorCollection(); foreach (WorkflowChangeAction changeAction in this.modelChangeActions) { if (changeAction is ActivityChangeAction) { foreach (Activity contextActivity in contextActivities) { // WinOE if (changeAction is RemovedActivityAction && contextActivity.DottedPath == ((RemovedActivityAction)changeAction).OriginalRemovedActivity.DottedPath) { validationErrors.AddRange(changeAction.ValidateChanges(contextActivity)); } // Ask the parent context activity whether or not this child activity can be added or removed. // The call to TraverseDottedPathFromRoot here should return the parent context activity for this change action. if (contextActivity.TraverseDottedPathFromRoot(((ActivityChangeAction)changeAction).OwnerActivityDottedPath) != null) { validationErrors.AddRange(changeAction.ValidateChanges(contextActivity)); } } } } // if errors then return if (validationErrors.HasErrors) { throw new WorkflowValidationFailedException(SR.GetString(SR.Error_RuntimeValidationFailed), validationErrors); } // verify if workflow can be changed VerifyWorkflowCanBeChanged(workflowCoreRuntime); // inform workflow runtime workflowCoreRuntime.OnBeforeDynamicChange(this.modelChangeActions); // set the new Workflow Definition workflowCoreRuntime.RootActivity.SetValue(Activity.WorkflowDefinitionProperty, this.clonedRootActivity); // apply changes to all context Activities foreach (Activity contextActivity in contextActivities) { // apply change to state reader foreach (WorkflowChangeAction changeAction in this.modelChangeActions) { if (changeAction is ActivityChangeAction) { if (contextActivity.TraverseDottedPathFromRoot(((ActivityChangeAction)changeAction).OwnerActivityDottedPath) != null) { bool result = changeAction.ApplyTo(contextActivity); Debug.Assert(result, "ApplyTo failed"); } } } // fixup meta properties and notify changes // if the context activity is the one that's being removed, we do not fixup the meta properties. Activity clonedActivity = ((Activity)this.clonedRootActivity).GetActivityByName(contextActivity.QualifiedName); if (clonedActivity != null) { contextActivity.FixUpMetaProperties(clonedActivity); } NotifyChangesToChildExecutors(workflowCoreRuntime, contextActivity, this.modelChangeActions); NotifyChangesCompletedToChildExecutors(workflowCoreRuntime, contextActivity); } // inform workflow runtime workflowCoreRuntime.OnAfterDynamicChange(true, this.modelChangeActions); } catch { workflowCoreRuntime.OnAfterDynamicChange(false, this.modelChangeActions); throw; } finally { if (suspended) { workflowCoreRuntime.Resume(); } } }
public bool WalkProperties(Activity activity, object obj) { Activity activity2 = obj as Activity; foreach (PropertyInfo info in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (((info.GetIndexParameters() == null) || (info.GetIndexParameters().Length <= 0)) && (GetSerializationVisibility(info) != DesignerSerializationVisibility.Hidden)) { object currentValue = null; DependencyProperty dependencyProperty = DependencyProperty.FromName(info.Name, obj.GetType()); if ((dependencyProperty != null) && (activity2 != null)) { if (activity2.IsBindingSet(dependencyProperty)) { currentValue = activity2.GetBinding(dependencyProperty); } else { currentValue = activity2.GetValue(dependencyProperty); } } else { try { currentValue = info.CanRead ? info.GetValue(obj, null) : null; } catch { } } if (this.FoundProperty != null) { WalkerEventArgs eventArgs = new WalkerEventArgs(activity, currentValue, info, obj); this.FoundProperty(this, eventArgs); if (eventArgs.Action == WalkerAction.Skip) { continue; } if (eventArgs.Action == WalkerAction.Abort) { return(false); } } if (currentValue is IList) { foreach (object obj3 in (IList)currentValue) { if (this.FoundProperty != null) { WalkerEventArgs args2 = new WalkerEventArgs(activity, obj3, null, currentValue); this.FoundProperty(this, args2); if (args2.Action == WalkerAction.Skip) { continue; } if (args2.Action == WalkerAction.Abort) { return(false); } } if (((obj3 != null) && IsBrowsableType(obj3.GetType())) && !this.WalkProperties(activity, obj3)) { return(false); } } } else if (((currentValue != null) && IsBrowsableType(currentValue.GetType())) && !this.WalkProperties(activity, currentValue)) { return(false); } } } return(true); }