protected override void Execute(NativeActivityContext context) { CustomTrackingRecord record = new CustomTrackingRecord("MyCustomTrackingRecord"); record.Data.Add("CustomTrackKey", "CustomTrackValue"); context.Track(record); }
/// <summary> /// Invoked when the body completes. /// </summary> /// <param name="context"></param> /// <param name="instance"></param> void OnBodyCompleted(NativeActivityContext context, ActivityInstance instance) { var state = this.state.Get(context); state.SuppressCancel = true; // we caught an exception var e = state.CaughtException; if (e != null) { // forget caught exception state.CaughtException = null; // discover if exception is handled var c = FindCatch(e); if (c != null) { // record exception state.Attempts.Add(e); // signal that we have handled an exception, cancel child context.Track(new RetryExceptionCaughtTrackingRecord(e, state.Attempts.Count())); // dispatch to exception handler, which will handle, and then retry the body c.ScheduleAction(context, e, state.Attempts.Count(), OnCatchComplete, OnCatchFault); } } else { BeforeExit(context); } }
private void Track(NativeActivityContext context, Object data) { string source = this.Source.Get(context), target = this.Target.Get(context); context.Track(new CustomTrackingRecord("FileCopy", System.Diagnostics.TraceLevel.Info) { Data = { { "Source", source }, { "Target", target }, { "Progress", data } } }); }
protected override void Execute(NativeActivityContext context) { context.Track(CreateLookupTreeTrackingRecord(RootWorkItem.Get(context).CreateLookupTree())); context.CreateBookmark(CancellationBookmark, OnCancellationRequested, BookmarkOptions.MultipleResume); context.CreateBookmark(WorkItemCancellationBookmark, OnWorkItemCancellationRequested, BookmarkOptions.MultipleResume); context.ScheduleActivity(ProgressTrackingScope, OnProgressActivityCompleted); }
private void SetTaskCompletionSourceResult(ReceiveRequestSendResponseScopeExecutionProperty <object> executionProperty, NativeActivityContext context) { executionProperty.SetTaskCompletionSourceResult(null, ThrowIfReloaded); if (context.GetActivityContext().TrackingEnabled) { context.Track(new SendResponseRecord()); } }
NativeActivityContext CreateTrackingRecord(DocumentState stepParametr, NativeActivityContext context) { var customRecord = new CustomTrackingRecord("RespondActivityRecord"); customRecord.Data.Add("outputStep", context.GetValue <DocumentState>(inputStep)); context.Track(customRecord); return(context); }
protected override void Execute(NativeActivityContext context) { context.Track(new CustomTrackingRecord("cancelation scope !")); /* * var model = context.GetExtension<IWorkflowRunner>(); * if (model.Canceled != null) * model.Canceled(); */ }
protected override void Execute(NativeActivityContext context) { var customRecord = new CustomTrackingRecord("CurrentUserRecord"); customRecord.Data.Add("CurrentUser", CurrentUser.Get(context)); customRecord.Data.Add("Drafter", WorkFlowInParameters.Get(context).drafter); customRecord.Data.Add("OpinionField", OpinionField.Get(context) == null ? "" : OpinionField.Get(context)); context.Track(customRecord); context.CreateBookmark(BookmarkName.Get(context), new BookmarkCallback(OnResumeBookmark)); //创建书签 }
private void EvaluatorCompletionCallback(NativeActivityContext context, ActivityInstance completedInstance) { // The receiving delegate completed. if (completedInstance.State == ActivityInstanceState.Closed) { if (context.GetActivityContext().TrackingEnabled) { context.Track(new ReceiveRequestRecord(this.OperationName)); } } }
private void EvaluatorCompletionCallback(NativeActivityContext context, ActivityInstance completedInstance) { // The request's result delegate completed. if (completedInstance.State == ActivityInstanceState.Closed) { if (context.GetActivityContext().TrackingEnabled) { context.Track(new ReceiveResponseRecord()); } } }
/// <summary> /// The execute. /// </summary> /// <param name="context"> /// The context. /// </param> protected override void Execute(NativeActivityContext context) { this.hostContext = context.GetExtension <IHttpWorkflowHostContext>(); // Typically there is only one base address but there could be more than one. foreach (var bookmarkName in this.hostContext.BaseAddresses.Select(this.GetBookmarkName)) { context.CreateBookmark(bookmarkName, this.ReceiveCallback); context.Track(new HttpReceiveMessageRecord(bookmarkName)); } }
// This will start/schedule the OnOperationAsync task, but won't wait for it, the task will be an implicit (single threaded reentrant) parallel activity. // The Scope is responsible to handle the outstanding task in case of Abort, Cancellation or Termination. protected override void Execute(NativeActivityContext context) { SendRequestReceiveResponseScopeExecutionProperty executionProperty = context.GetSendRequestReceiveResponseScopeExecutionProperty(); IActivityContext activityContext = context.GetActivityContext(); executionProperty.StartOnOperationAsync(activityContext, OperationName); if (activityContext.TrackingEnabled) { context.Track(new SendRequestRecord(OperationName)); } }
/// <summary> /// Log an error message to the build tracking participant. /// </summary> /// <param name="context">The current activity context.</param> /// <param name="message">The message to log.</param> private void LogBuildError(NativeActivityContext context, string message) { var record = new BuildInformationRecord <BuildError> { ParentToBuildDetail = false, Value = new BuildError { Message = message } }; context.Track(record); }
/// <summary> /// Log a message to the build tracking participant. /// </summary> /// <param name="context">The current activity context.</param> /// <param name="message">The message to log.</param> /// <param name="importance">The importance level of the message.</param> private void LogBuildMessage(NativeActivityContext context, string message, BuildMessageImportance importance) { var record = new BuildInformationRecord <BuildMessage> { ParentToBuildDetail = false, Value = new BuildMessage { Importance = importance, Message = message } }; context.Track(record); }
private void ProcessReceiveMessageTrace(NativeActivityContext executionContext, ReceiveMessageInstanceData instance) { if (TraceUtility.MessageFlowTracing) { try { if (TraceUtility.ActivityTracing) { instance.AmbientActivityId = Trace.CorrelationManager.ActivityId; } Guid empty = Guid.Empty; if (instance.CorrelationRequestContext != null) { empty = TraceUtility.GetReceivedActivityId(instance.CorrelationRequestContext.OperationContext); } else if (instance.CorrelationResponseContext != null) { empty = instance.CorrelationResponseContext.WorkflowOperationContext.E2EActivityId; } ReceiveMessageRecord record = new ReceiveMessageRecord("MessageCorrelationReceiveRecord") { E2EActivityId = empty }; executionContext.Track(record); if ((empty != Guid.Empty) && (DiagnosticTrace.ActivityId != empty)) { DiagnosticTrace.ActivityId = empty; } System.ServiceModel.Activities.FxTrace.Trace.SetAndTraceTransfer(executionContext.WorkflowInstanceId, true); if (TraceUtility.ActivityTracing && System.ServiceModel.Activities.TD.StartSignpostEventIsEnabled()) { Dictionary <string, string> dictionary = new Dictionary <string, string>(3); dictionary.Add("ActivityName", base.DisplayName); dictionary.Add("ActivityType", "MessagingActivityExecution"); dictionary.Add("ActivityInstanceId", executionContext.ActivityInstanceId); System.ServiceModel.Activities.TD.StartSignpostEvent(new DictionaryTraceRecord(dictionary)); } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } System.ServiceModel.Activities.FxTrace.Exception.AsInformation(exception); } } }
private void ScheduleEntry(NativeActivityContext context) { StateMachineStateRecord record = new StateMachineStateRecord { StateMachineName = this.StateMachineName, StateName = base.DisplayName }; context.Track(record); if (this.Entry != null) { context.ScheduleActivity(this.Entry, this.onEntryComplete); } else { this.onEntryComplete(context, null); } }
//private static bool ValidateDUInConditionTransition(NativeActivityUpdateMapMetadata metadata, InternalTransition updatedTransition, InternalTransition originalTransition, out string errorMessage) //{ // Fx.Assert(!originalTransition.IsUnconditional, "Transition should be conditional in the original definition."); // errorMessage = string.Empty; // foreach (TransitionData updatedTData in updatedTransition.TransitionDataList) // { // if (metadata.IsReferenceToImportedChild(updatedTData.Condition)) // { // // if the trigger is referenced, it might have another save values already. // errorMessage = SR.TriggerOrConditionIsReferenced; // return false; // } // Fx.Assert(null != updatedTData.Condition, "Must be a condition transition."); // Activity conditionMatch = metadata.GetMatch(updatedTData.Condition); // if (null == conditionMatch && null != metadata.GetMatch(updatedTData.Action)) // { // // new Transition.Condition with an Transition.Action moved from within the InternalState. // errorMessage = SR.MovingActivitiesInStateBlockDU; // return false; // } // else if (null != conditionMatch) // { // bool foundMatchingOriginalCondition = false; // for (int transitionIndex = 0; transitionIndex < originalTransition.TransitionDataList.Count; transitionIndex++) // { // if (object.ReferenceEquals(originalTransition.TransitionDataList[transitionIndex].Condition, conditionMatch)) // { // foundMatchingOriginalCondition = true; // // found the original matching condition in updated transition definition. // TransitionData originalTData = originalTransition.TransitionDataList[transitionIndex]; // Activity originalAction = originalTData.Action; // // NOTE: Transition.Action is allowed to be removed, because it doesn't change the execution semantics of SM // // if this removed activity was executing, WF runtime would disallow the update. // Activity actionMatch = metadata.GetMatch(updatedTData.Action); // if (null != actionMatch && !object.ReferenceEquals(originalAction, actionMatch)) // { // // Transition.Action is an activity moved from elsewhere within the InternalState // errorMessage = SR.MovingActivitiesInStateBlockDU; // return false; // } // metadata.SaveOriginalValue(updatedTransition.Trigger, originalTransition.InternalTransitionIndex); // metadata.SaveOriginalValue(updatedTData.Condition, transitionIndex); // } // } // if (!foundMatchingOriginalCondition) // { // // another child activity is move to the Transition.Condition. // errorMessage = SR.DUDisallowIfCannotFindingMatchingCondition; // return false; // } // } // } // return true; //} //private static bool ValidateDUInUnconditionalTransition(NativeActivityUpdateMapMetadata metadata, InternalTransition updatedTransition, InternalTransition originalTransition, out string errorMessage) //{ // Fx.Assert(originalTransition.IsUnconditional, "Transition should be unconditional in the original definition."); // Activity originalAction = originalTransition.TransitionDataList[0].Action; // foreach (TransitionData transitionData in updatedTransition.TransitionDataList) // { // Activity updatedAction = transitionData.Action; // Activity actionMatch = metadata.GetMatch(updatedAction); // Activity conditionMatch = metadata.GetMatch(transitionData.Condition); // if ((null == originalAction && null != actionMatch) || // (null != originalAction && null != actionMatch && !object.ReferenceEquals(originalAction, actionMatch))) // { // // Transition.Action is an activity moved from elsewhere within the InternalState // errorMessage = SR.MovingActivitiesInStateBlockDU; // return false; // } // } // errorMessage = string.Empty; // metadata.SaveOriginalValue(updatedTransition.Trigger, originalTransition.InternalTransitionIndex); // return true; //} //private void RescheduleNewlyAddedTriggers(NativeActivityUpdateContext updateContext) //{ // // NOTE: triggers are scheduled already, so the state has completed executing State.Entry // Fx.Assert(this.internalTransitions.Count == this.triggerInternalTransitionMapping.Count, "Triggers mappings are correct."); // List<Activity> newTriggers = new List<Activity>(); // foreach (InternalTransition transition in this.internalTransitions) // { // if (updateContext.IsNewlyAdded(transition.Trigger)) // { // newTriggers.Add(transition.Trigger); // } // // NOTE: all Triggers in triggerInternalTransitionMapping are either new or was previously scheduled // } // foreach (Activity newTrigger in newTriggers) // { // updateContext.ScheduleActivity(newTrigger, this.onTriggerComplete); // } // updateContext.SetValue<int>(this.currentRunningTriggers, updateContext.GetValue(this.currentRunningTriggers) + newTriggers.Count); //} /// <summary> /// Used for Dynamic Update: after the instance is updated, if the statemachine is already transitioning, the index of the to-be-scheduled state /// would need to be updated. /// </summary> /// <param name="updateContext">Dynamic Update context</param> /// <param name="eventManager">Internal StateMachineEventManager</param> /// <returns>True, 1. if update is successful and the instanced is updated with the new indexes, and 2 all the trigger ID in the queue are updated; /// false otherwise and the update should fail.</returns> //private bool UpdateEventManager( // NativeActivityUpdateContext updateContext, // StateMachineEventManager eventManager) //{ // Fx.Assert(null != eventManager.CurrentBeingProcessedEvent, "The eventManager must have some info that needs to be updated during transition."); // int updatedEventsInQueue = 0; // int originalTriggerId = int.MinValue; // int originalConditionIndex = int.MinValue; // bool updateCurrentEventSucceed = null == eventManager.CurrentBeingProcessedEvent ? true : false; // foreach (InternalTransition transition in this.internalTransitions) // { // object savedTriggerIndex = updateContext.GetSavedOriginalValue(transition.Trigger); // if (savedTriggerIndex != null) // { // Fx.Assert(!updateContext.IsNewlyAdded(transition.Trigger), "the trigger in transition already exist."); // if (null != eventManager.CurrentBeingProcessedEvent && // eventManager.CurrentBeingProcessedEvent.TriggedId == (int)savedTriggerIndex) // { // // found a match of the running trigger update the current processed event // // Don't match the trigger ID, match only when the Condition is also matched. // if (eventManager.CurrentConditionIndex == -1) // { // if (transition.IsUnconditional) // { // // executing transition before persist is unconditional // originalTriggerId = eventManager.CurrentBeingProcessedEvent.TriggedId; // originalConditionIndex = 0; // eventManager.CurrentBeingProcessedEvent.TriggedId = transition.InternalTransitionIndex; // if (updateContext.GetValue(this.isExiting)) // { // Fx.Assert(eventManager.OnTransition, "The state is transitioning."); // updateContext.SetValue(this.Result, GetTo(transition.InternalTransitionIndex)); // } // updateCurrentEventSucceed = true; // } // else // { // updateContext.DisallowUpdate(SR.ChangeTransitionTypeDuringTransitioningBlockDU); // return false; // } // } // else if (eventManager.CurrentConditionIndex >= 0) // { // Fx.Assert(!transition.IsUnconditional, "Cannot update a running conditional transition with a unconditional one."); // if (!transition.IsUnconditional) // { // // executing transition before and after are conditional // for (int updatedIndex = 0; updatedIndex < transition.TransitionDataList.Count; updatedIndex++) // { // Activity condition = transition.TransitionDataList[updatedIndex].Condition; // Fx.Assert(null != condition, "Conditional transition must have Condition activity."); // int? savedCondIndex = updateContext.GetSavedOriginalValue(condition) as int?; // if (eventManager.CurrentConditionIndex == savedCondIndex) // { // originalTriggerId = eventManager.CurrentBeingProcessedEvent.TriggedId; // originalConditionIndex = eventManager.CurrentConditionIndex; // eventManager.CurrentBeingProcessedEvent.TriggedId = transition.InternalTransitionIndex; // eventManager.CurrentConditionIndex = updatedIndex; // if (updateContext.GetValue(this.isExiting)) // { // Fx.Assert(eventManager.OnTransition, "The state is transitioning."); // updateContext.SetValue(this.Result, this.GetTo(transition.InternalTransitionIndex, (int)updatedIndex)); // } // updateCurrentEventSucceed = true; // break; // } // } // } // } // } // foreach (TriggerCompletedEvent completedEvent in eventManager.Queue) // { // if ((int)savedTriggerIndex == completedEvent.TriggedId) // { // completedEvent.TriggedId = transition.InternalTransitionIndex; // updatedEventsInQueue++; // } // } // } // } // return eventManager.Queue.Count() == updatedEventsInQueue ? updateCurrentEventSucceed : false; //} private void ScheduleEntry(NativeActivityContext context) { context.Track(new StateMachineStateRecord { StateMachineName = this.StateMachineName, StateName = this.DisplayName, }); if (this.Entry != null) { context.ScheduleActivity(this.Entry, _onEntryComplete); } else { _onEntryComplete(context, null); } }
private void Track(NativeActivityContext context, FileChangeEvent data) { var record = new CustomTrackingRecord("FileChangeEvent", System.Diagnostics.TraceLevel.Info) { Data = { { "ChangeType", data.ChangeType }, { "ChangeTime", data.ChangeTime }, { "FullPath", data.FullPath } } }; if (!String.IsNullOrEmpty(data.OldPath)) { record.Data.Add("PrevPath", data.OldPath); } context.Track(record); }
private static void PostTrackingRecord(NativeActivityContext context, IWorkItemWithChildren target, string status, string message = null) { CustomTrackingRecord customTrackingRecord = new CustomTrackingRecord(status) { Data = { { CustomProgressTrackingDataKey.Target, target }, } }; if (!String.IsNullOrEmpty(message)) { customTrackingRecord.Data.Add(CustomProgressTrackingDataKey.Message, message); } context.Track(customTrackingRecord); }
/// <summary> /// The on body completed. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="completedinstance"> /// The completed instance. /// </param> /// <param name="result"> /// The result. /// </param> private void OnBodyCompleted(NativeActivityContext context, ActivityInstance completedinstance, object result) { this.noPersistHandle.Get(context).Exit(context); // The body activities can create a response message or response may be data // Create the response message var response = result as HttpResponseMessage ?? new HttpResponseMessage(); // If the result was data, add it to the content if (!(result is HttpResponseMessage) && result != null) { object content; Type contentType; if (result is IQueryable) { var listType = typeof(List <>).MakeGenericType(((IQueryable)result).ElementType); content = (IList)Activator.CreateInstance(listType, result); contentType = listType; } else { content = result; contentType = result.GetType(); } response.Content = new ObjectContent( contentType, content, GetNegotiatedMediaType(this.receiveContext.Request)); } WorkflowCookieCorrelation.AddCookie(response, context.WorkflowInstanceId); this.receiveContext.Response = response; context.Track(new HttpReceiveResponseRecord(result)); if (this.PersistBeforeSend) { context.ScheduleActivity(this.persist); } }
protected override void Execute(NativeActivityContext context) { string bookmarkName = Guid.NewGuid().ToString(); _resumeBookmark.Set(context, bookmarkName); context.CreateBookmark(bookmarkName, OnResumeBody, BookmarkOptions.None); bool resumeImmediately = context.GetExtension <CriticalSectionQueueExtension>() .Enter(bookmarkName, QueueName.Get(context), PriorityTicket.Get(context)); if (!resumeImmediately && WorkItem.Get(context) != null) { context.Track( new CustomTrackingRecord(WorkItemStatus.Waiting) { Data = { { CustomProgressTrackingDataKey.Target, WorkItem.Get(context) }, { CustomProgressTrackingDataKey.Message, String.Format(Resources.WaitingInTheQueue, QueueName.Get(context)) } } }); } }
private string GetWorkflowXaml(NativeActivityContext context) { var workflowCode = WorkflowCode.Get(context); if (ActivityHelpers.UseActivityStackTrace(context)) { var tracking = new CustomTrackingRecord(DisplayName); tracking.Data.Add("WorkflowCode", string.Format("Workflow='{0}'", workflowCode)); context.Track(tracking); } if (string.IsNullOrEmpty(workflowCode)) { throw new OperationException("WorkflowCode is null."); } if (_wfCache.ContainsKey(workflowCode)) { return(_wfCache[workflowCode]); } _wfCache[workflowCode] = ActivityHelpers.GetWorkflowXaml(workflowCode); return(_wfCache[workflowCode]); }
void ProcessReceiveMessageTrace(NativeActivityContext executionContext, Guid receivedActivityId) { if (TraceUtility.MessageFlowTracing) { try { // ReceiveMessageRecord messageFlowTrackingRecord = new ReceiveMessageRecord(MessagingActivityHelper.MessageCorrelationReceiveRecord) { E2EActivityId = receivedActivityId }; executionContext.Track(messageFlowTrackingRecord); if (receivedActivityId != Guid.Empty && DiagnosticTraceBase.ActivityId != receivedActivityId) { DiagnosticTraceBase.ActivityId = receivedActivityId; } FxTrace.Trace.SetAndTraceTransfer(executionContext.WorkflowInstanceId, true); if (TraceUtility.ActivityTracing) { if (TD.StartSignpostEventIsEnabled()) { TD.StartSignpostEvent(new DictionaryTraceRecord(new Dictionary<string, string>(3) { { MessagingActivityHelper.ActivityName, this.DisplayName }, { MessagingActivityHelper.ActivityType, MessagingActivityHelper.MessagingActivityTypeActivityExecution }, { MessagingActivityHelper.ActivityInstanceId, executionContext.ActivityInstanceId } })); } } else if (TD.WfMessageReceivedIsEnabled()) { TD.WfMessageReceived(new EventTraceActivity(receivedActivityId), executionContext.WorkflowInstanceId); } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } FxTrace.Exception.AsInformation(ex); } } }
void TrackRecord(NativeActivityContext context, String msg) { var ctr = new CustomTrackingRecord(msg, TraceLevel.Info); context.Track(ctr); }
/// <summary> /// The execute. /// </summary> /// <param name="context"> /// The context. /// </param> protected override void Execute(NativeActivityContext context) { this.hostContext = context.GetExtension<IHttpWorkflowHostContext>(); // Typically there is only one base address but there could be more than one. foreach (var bookmarkName in this.hostContext.BaseAddresses.Select(this.GetBookmarkName)) { context.CreateBookmark(bookmarkName, this.ReceiveCallback); context.Track(new HttpReceiveMessageRecord(bookmarkName)); } }
/// <summary> /// The on body completed. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="completedinstance"> /// The completed instance. /// </param> /// <param name="result"> /// The result. /// </param> private void OnBodyCompleted(NativeActivityContext context, ActivityInstance completedinstance, object result) { this.noPersistHandle.Get(context).Exit(context); // The body activities can create a response message or response may be data // Create the response message var response = result as HttpResponseMessage ?? new HttpResponseMessage(); // If the result was data, add it to the content if (!(result is HttpResponseMessage) && result != null) { object content; Type contentType; if (result is IQueryable) { var listType = typeof(List<>).MakeGenericType(((IQueryable)result).ElementType); content = (IList)Activator.CreateInstance(listType, result); contentType = listType; } else { content = result; contentType = result.GetType(); } response.Content = new ObjectContent( contentType, content, GetNegotiatedMediaType(this.receiveContext.Request)); } WorkflowCookieCorrelation.AddCookie(response, context.WorkflowInstanceId); this.receiveContext.Response = response; context.Track(new HttpReceiveResponseRecord(result)); if (this.PersistBeforeSend) { context.ScheduleActivity(this.persist); } }
private void Track(NativeActivityContext context, Object data) { string source = this.Source.Get(context), target = this.Target.Get(context); context.Track(new CustomTrackingRecord("FileCopy", System.Diagnostics.TraceLevel.Info) { Data = { { "Source", source }, { "Target", target }, { "Progress", data } } }); }
/// <summary> /// Execution of PowerShell value activity. /// PowerShell expression will be evaluated using PowerShell runspace and the value of Type T will be returned. /// </summary> /// <param name="context"></param> protected override void Execute(NativeActivityContext context) { Token[] tokens; ParseError[] errors; ScriptBlockAst exprAst = Parser.ParseInput(Expression, out tokens, out errors); bool hasErrorActionPreference = false; bool hasWarningPreference = false; bool hasInformationPreference = false; // Custom activity participant tracker for updating debugger with current variables and sequence stop points. // Regex looks for debugger sequence points like: Expression="'3:5:WFFunc1'". // We specifically disallow TimeSpan values that look like sequence points: Expression="'00:00:01'". bool isDebugSequencePoint = (!string.IsNullOrEmpty(Expression) && (System.Text.RegularExpressions.Regex.IsMatch(Expression, @"^'\d+:\d+:\S+'$")) && (typeof(T) != typeof(System.TimeSpan))); var dataProperties = context.DataContext.GetProperties(); if (isDebugSequencePoint || (dataProperties.Count > 0)) { System.Activities.Tracking.CustomTrackingRecord customRecord = new System.Activities.Tracking.CustomTrackingRecord("PSWorkflowCustomUpdateDebugVariablesTrackingRecord"); foreach (System.ComponentModel.PropertyDescriptor property in dataProperties) { if (String.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase)) { continue; } Object value = property.GetValue(context.DataContext); if (value != null) { object tempValue = value; PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>; if (collectionObject != null && collectionObject.Count == 1) { tempValue = collectionObject[0]; } customRecord.Data.Add(property.Name, tempValue); } } if (isDebugSequencePoint) { customRecord.Data.Add("DebugSequencePoint", Expression); } context.Track(customRecord); } if (tokens != null) { foreach (Token token in tokens) { VariableToken variable = token as VariableToken; if (variable != null) { if (variable.Name.Equals("ErrorActionPreference", StringComparison.OrdinalIgnoreCase)) { hasErrorActionPreference = true; } else if (variable.Name.Equals("WarningPreference", StringComparison.OrdinalIgnoreCase)) { hasWarningPreference = true; } else if (variable.Name.Equals("InformationPreference", StringComparison.OrdinalIgnoreCase)) { hasInformationPreference = true; } } } } if (string.IsNullOrEmpty(Expression)) { throw new ArgumentException(ActivityResources.NullArgumentExpression); } if (_ci == null) { lock (syncroot) { // Invoke using the CommandInfo for Invoke-Command directly, rather than going through // command discovery (which is very slow). if (_ci == null) { _ci = new CmdletInfo("Invoke-Command", typeof(Microsoft.PowerShell.Commands.InvokeCommandCommand)); } } } Collection <PSObject> returnedvalue; Runspace runspace = null; bool borrowedRunspace = false; PSWorkflowHost workflowHost = null; if (typeof(ScriptBlock).IsAssignableFrom(typeof(T))) { Result.Set(context, ScriptBlock.Create(Expression)); return; } else if (typeof(ScriptBlock[]).IsAssignableFrom(typeof(T))) { Result.Set(context, new ScriptBlock[] { ScriptBlock.Create(Expression) }); return; } PropertyDescriptorCollection col = context.DataContext.GetProperties(); HostParameterDefaults hostValues = context.GetExtension <HostParameterDefaults>(); // Borrow a runspace from the host if we're not trying to create a ScriptBlock. // If we are trying to create one, we need to keep it around so that it can be // invoked multiple times. if (hostValues != null) { workflowHost = hostValues.Runtime; try { runspace = workflowHost.UnboundedLocalRunspaceProvider.GetRunspace(null, 0, 0); borrowedRunspace = true; } catch (Exception) { // it is fine to catch generic exception here // if the local runspace provider does not give us // a runspace we will create one locally (fallback) } } if (runspace == null) { // Not running with the PowerShell workflow host so directly create the runspace... runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); runspace.Open(); } using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { try { ps.Runspace = runspace; // Subscribe to DataAdding on the error stream so that we can add position tracking information if (hostValues != null) { HostSettingCommandMetadata sourceCommandMetadata = hostValues.HostCommandMetadata; CommandMetadataTable.TryAdd(ps.InstanceId, sourceCommandMetadata); ps.Streams.Error.DataAdding += HandleErrorDataAdding; } // First, set the variables from the host defaults if ((hostValues != null) && (hostValues.Parameters != null)) { if (hostValues.Parameters.ContainsKey("PSCurrentDirectory")) { string path = hostValues.Parameters["PSCurrentDirectory"] as string; if (path != null) { ps.Runspace.SessionStateProxy.Path.SetLocation(path); } } foreach (string hostDefault in hostValues.Parameters.Keys) { string mappedHostDefault = hostDefault; if (hostDefault.Equals("ErrorAction", StringComparison.OrdinalIgnoreCase)) { if (hasErrorActionPreference) { mappedHostDefault = "ErrorActionPreference"; } else { continue; } } else if (hostDefault.Equals("WarningAction", StringComparison.OrdinalIgnoreCase)) { if (hasWarningPreference) { mappedHostDefault = "WarningPreference"; } else { continue; } } else if (hostDefault.Equals("InformationAction", StringComparison.OrdinalIgnoreCase)) { if (hasInformationPreference) { mappedHostDefault = "InformationPreference"; } else { continue; } } object propertyValue = hostValues.Parameters[hostDefault]; if (propertyValue != null) { ps.Runspace.SessionStateProxy.PSVariable.Set(mappedHostDefault, propertyValue); } } } // Then, set the variables from the workflow foreach (PropertyDescriptor p in col) { string name = p.Name; object value = p.GetValue(context.DataContext); if (value != null) { object tempValue = value; PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>; if (collectionObject != null && collectionObject.Count == 1) { tempValue = collectionObject[0]; } ps.Runspace.SessionStateProxy.PSVariable.Set(name, tempValue); } } ps.AddCommand(_ci).AddParameter("NoNewScope").AddParameter("ScriptBlock", ExpressionScriptBlock); // If this needs to consume input, take it from the host stream. PSDataCollection <PSObject> inputStream = null; if (UseDefaultInput) { // Retrieve our host overrides hostValues = context.GetExtension <HostParameterDefaults>(); if (hostValues != null) { Dictionary <string, object> incomingArguments = hostValues.Parameters; if (incomingArguments.ContainsKey("Input")) { inputStream = incomingArguments["Input"] as PSDataCollection <PSObject>; } } } // Now invoke the pipeline try { if (inputStream != null) { returnedvalue = ps.Invoke(inputStream); inputStream.Clear(); } else { returnedvalue = ps.Invoke(); } } catch (CmdletInvocationException cie) { if (cie.ErrorRecord != null && cie.ErrorRecord.Exception != null) { throw cie.InnerException; } else { throw; } } } finally { if (hostValues != null) { ps.Streams.Error.DataAdding -= HandleErrorDataAdding; HostSettingCommandMetadata removedValue; CommandMetadataTable.TryRemove(ps.InstanceId, out removedValue); } if (borrowedRunspace) { workflowHost.UnboundedLocalRunspaceProvider.ReleaseRunspace(runspace); } else { // This will be disposed when the command is done with it. runspace.Dispose(); runspace = null; } } if (ps.Streams.Error != null && ps.Streams.Error.Count > 0) { PSDataCollection <ErrorRecord> errorStream = null; // Retrieve our host overrides hostValues = context.GetExtension <HostParameterDefaults>(); if (hostValues != null) { Dictionary <string, object> incomingArguments = hostValues.Parameters; if (incomingArguments.ContainsKey("PSError")) { errorStream = incomingArguments["PSError"] as PSDataCollection <ErrorRecord>; } } if (errorStream != null && errorStream.IsOpen) { foreach (ErrorRecord record in ps.Streams.Error) { errorStream.Add(record); } } } T valueToReturn = default(T); if (returnedvalue != null && returnedvalue.Count > 0) { try { if (returnedvalue.Count == 1) { if (returnedvalue[0] != null) { Object result = returnedvalue[0]; Object baseObject = ((PSObject)result).BaseObject; if (!(baseObject is PSCustomObject)) { result = baseObject; } // Try regular PowerShell conversion valueToReturn = LanguagePrimitives.ConvertTo <T>(result); } } else { valueToReturn = LanguagePrimitives.ConvertTo <T>(returnedvalue); } } catch (PSInvalidCastException) { // Handle the special case of emitting a PSDataCollection - use its array constructor. // This special case is why we aren't using PowerShell.Invoke<T> if (typeof(T) == typeof(PSDataCollection <PSObject>)) { Object tempValueToReturn = new PSDataCollection <PSObject>( new List <PSObject> { LanguagePrimitives.ConvertTo <PSObject>(returnedvalue[0]) }); valueToReturn = (T)tempValueToReturn; } else { throw; } } Result.Set(context, valueToReturn); } } }
protected override void Execute(NativeActivityContext context) { var methodName = Value.Get(context); if (ActivityHelpers.UseActivityStackTrace(context)) { var tracking = new CustomTrackingRecord(DisplayName); tracking.Data.Add("Value", string.Format("Method='{0}'", methodName)); context.Track(tracking); } IUnitOfWork uow = null; var isNeedDisposeUoW = false; try { // определяем был ли объявлен UoW uow = BeginTransactionActivity.GetUnitOfWork(context); int?timeOut = TimeOut.Get(context); // если не создали - делаем сами if (uow == null) { uow = UnitOfWorkHelper.GetUnit(true); isNeedDisposeUoW = true; } if (timeOut.HasValue) { uow.TimeOut = timeOut; } var mgr = IoC.Instance.Resolve <T>(); if (uow != null) { mgr.SetUnitOfWork(uow); } // вызываем нужный метод var isResultParamExists = Parameters.ContainsKey(ResultParamName); var argsCount = Parameters.Count - (isResultParamExists ? 1 : 0); var args = new object[argsCount]; var methodInfo = mgr.GetType().GetMethod(methodName); var methodParams = methodInfo.GetParameters(); for (var i = 0; i < argsCount; i++) { args[i] = Parameters[methodParams[i].Name].Get(context); } var isNeedResult = methodInfo.ReturnType != typeof(void); if (!isNeedResult && isResultParamExists) { throw new DeveloperException( "Метод {0} не возвращает результат, однако найден параметр с именем {1}", methodName, ResultParamName); } // запускаем метод var resultValue = methodInfo.Invoke(mgr, args); // получаем результаты if (isNeedResult) { Parameters[ResultParamName].Set(context, resultValue); } for (int i = 0; i < args.Length; i++) { var element = Parameters.ElementAt(i); var argument = Parameters.ElementAt(i).Value; if ((argument.Direction == ArgumentDirection.Out || argument.Direction == ArgumentDirection.InOut) & !element.Key.EqIgnoreCase(ResultParamName)) { argument.Set(context, args[i]); } } Result.Set(context, true); } catch (Exception ex) { Result.Set(context, false); Exception.Set(context, ex); _log.Warn("Ошибка запуска метода. Причина: " + ExceptionHelper.GetErrorMessage(ex), ex); } finally { if (isNeedDisposeUoW && uow != null) { try { uow.Dispose(); } catch (Exception ex) { _log.Warn("Не удалось закрыть сессию UoW. Причина: " + ExceptionHelper.GetErrorMessage(ex), ex); } } } }
/// <summary> /// Log a message to the build tracking participant. /// </summary> /// <param name="context">The current activity context.</param> /// <param name="message">The message to log.</param> /// <param name="importance">The importance level of the message.</param> private static void LogBuildMessage(NativeActivityContext context, string message, BuildMessageImportance importance) { var record = new BuildInformationRecord<BuildMessage> { ParentToBuildDetail = false, Value = new BuildMessage { Importance = importance, Message = message } }; context.Track(record); }
/// <summary> /// Log an error message to the build tracking participant. /// </summary> /// <param name="context">The current activity context.</param> /// <param name="message">The message to log.</param> private static void LogBuildError(NativeActivityContext context, string message) { var record = new BuildInformationRecord<BuildError> { ParentToBuildDetail = false, Value = new BuildError { Message = message } }; context.Track(record); }
protected override void Cancel(NativeActivityContext context) { context.Track(new CustomTrackingRecord("cancel invoked !")); base.Cancel(context); }