Exemple #1
0
        public bool Execute()
        {
            ActivityImplementationContext activityImplementationContext = null;

            if (this.commandQueue != null)
            {
                bool flag = this.commandQueue.TryDequeue(out activityImplementationContext);
                lock (this.SyncRoot)
                {
                    while (flag)
                    {
                        RunCommandsArguments runCommandsArgument = new RunCommandsArguments(this.ActivityParams, this.Output, this.Input, this, this.WorkflowHost, this.RunInProc, this.ParameterDefaults, this.ActivityType, this.PrepareSession, this.ActivityObject, activityImplementationContext);
                        Interlocked.Increment(ref this.CommandsRunningCount);
                        PSActivity.BeginRunOneCommand(runCommandsArgument);
                        flag = this.commandQueue.TryDequeue(out activityImplementationContext);
                    }
                    this.AllCommandsStarted = true;
                }
                return(true);
            }
            else
            {
                throw new InvalidOperationException("commandQueue");
            }
        }
 internal RunCommandsArguments(ActivityParameters activityParameters, PSDataCollection <PSObject> output, PSDataCollection <PSObject> input, PSActivityContext psActivityContext, PSWorkflowHost workflowHost, bool runInProc, Dictionary <string, object> parameterDefaults, Type activityType, PrepareSessionDelegate prepareSession, object activityObject, ActivityImplementationContext implementationContext)
 {
     this.ActivityParameters = activityParameters;
     this.Output             = output;
     this.Input                 = input;
     this.PSActivityContext     = psActivityContext;
     this.ParameterDefaults     = parameterDefaults;
     this.ActivityType          = activityType;
     this.Delegate              = prepareSession;
     this.ActivityObject        = activityObject;
     this.WorkflowHost          = workflowHost;
     this.ImplementationContext = implementationContext;
     this.CommandExecutionType  = RunCommandsArguments.DetermineCommandExecutionType(implementationContext.ConnectionInfo, runInProc, activityType, psActivityContext);
 }
		internal override void DoCleanup(RunCommandsArguments args, WaitCallback callback)
		{
			PSWorkflowHost workflowHost = args.WorkflowHost;
			WSManConnectionInfo connectionInfo = args.ImplementationContext.PowerShellInstance.Runspace.ConnectionInfo as WSManConnectionInfo;
			args.CleanupTimeout = this.timeout;
			if (connectionInfo != null)
			{
				workflowHost.RemoteRunspaceProvider.RequestCleanup(connectionInfo, callback, args);
			}
			else
			{
				if (callback != null)
				{
					callback(args);
					return;
				}
			}
		}
Exemple #4
0
        internal override void DoCleanup(RunCommandsArguments args, WaitCallback callback)
        {
            PSWorkflowHost      workflowHost   = args.WorkflowHost;
            WSManConnectionInfo connectionInfo = args.ImplementationContext.PowerShellInstance.Runspace.ConnectionInfo as WSManConnectionInfo;

            args.CleanupTimeout = this.timeout;
            if (connectionInfo != null)
            {
                workflowHost.RemoteRunspaceProvider.RequestCleanup(connectionInfo, callback, args);
            }
            else
            {
                if (callback != null)
                {
                    callback(args);
                    return;
                }
            }
        }
 /// <summary>
 /// Method that needs to be overridden to perform the actual
 /// cleanup action
 /// </summary>
 /// <param name="args">RunCommandsArguments</param>
 /// <param name="callback">callback to call when cleanup 
 /// is done</param>
 /// <remarks>The signature forces this method to be internal</remarks>
 internal virtual void DoCleanup(RunCommandsArguments args, WaitCallback callback)
 {
     throw new NotImplementedException();
 }
Exemple #6
0
		private static bool HandleRunOneCommandException(RunCommandsArguments args, Exception e)
		{
			bool flag = false;
			PSActivityContext pSActivityContext = args.PSActivityContext;
			ActivityImplementationContext implementationContext = args.ImplementationContext;
			ActivityParameters activityParameters = args.ActivityParameters;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				PowerShell powerShellInstance = implementationContext.PowerShellInstance;
				object[] objArray = new object[1];
				objArray[0] = powerShellInstance;
				traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "Exception handling for command {0}.", objArray));
				object[] message = new object[1];
				message[0] = e.Message;
				traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "Got exception running command: {0}.", message));
				int actionAttempts = 0x7fffffff;
				if (!pSActivityContext.IsCanceled)
				{
					if (pSActivityContext.runningCommands.ContainsKey(powerShellInstance))
					{
						actionAttempts = pSActivityContext.runningCommands[powerShellInstance].ActionAttempts;
					}
					flag = PSActivity.HandleFailure(actionAttempts, activityParameters.ActionRetryCount, activityParameters.ActionRetryInterval, implementationContext, "ActivityActionFailed", e, pSActivityContext);
				}
			}
			return flag;
		}
Exemple #7
0
		private static void BeginSetVariablesInRemoteRunspace(RunCommandsArguments args)
		{
			Runspace runspace = args.ImplementationContext.PowerShellInstance.Runspace;
			PSActivityEnvironment pSActivityEnvironment = args.ImplementationContext.PSActivityEnvironment;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				traceSource.WriteMessage("BEGIN BeginSetVariablesInRemoteRunspace");
				PowerShell powerShell = PowerShell.Create();
				powerShell.Runspace = runspace;
				powerShell.AddScript("\r\n            Get-Variable -Exclude input | Remove-Variable 2> $Null;$error.Clear();$input | Foreach-Object {$nvp=$_}; foreach($k in $nvp.keys){set-variable -name $k -value $nvp[$k]}\r\n        ");
				Dictionary<string, object> variablesToSetInRunspace = PSActivity.GetVariablesToSetInRunspace(pSActivityEnvironment);
				PSDataCollection<object> objs = new PSDataCollection<object>();
				objs.Add(variablesToSetInRunspace);
				PSDataCollection<object> objs1 = objs;
				objs1.Complete();
				args.HelperCommand = powerShell;
				args.HelperCommandInput = objs1;
				PSActivity.BeginInvokeOnPowershellCommand(powerShell, objs1, null, new AsyncCallback(PSActivity.SetVariablesCallback), args);
				traceSource.WriteMessage("END BeginSetVariablesInRemoteRunspace");
			}
		}
Exemple #8
0
		private static void InitializeOneCommand(RunCommandsArguments args)
		{
			ActivityParameters activityParameters = args.ActivityParameters;
			PSActivityContext pSActivityContext = args.PSActivityContext;
			PSWorkflowHost workflowHost = args.WorkflowHost;
			//TODO: REIVEW: args.ParameterDefaults;
			Type activityType = args.ActivityType;
			PrepareSessionDelegate @delegate = args.Delegate;
			object activityObject = args.ActivityObject;
			ActivityImplementationContext implementationContext = args.ImplementationContext;
			int commandExecutionType = args.CommandExecutionType;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				PowerShell powerShellInstance = implementationContext.PowerShellInstance;
				object[] objArray = new object[1];
				objArray[0] = powerShellInstance;
				traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "Beginning initialization for command '{0}'.", objArray));
				lock (pSActivityContext.runningCommands)
				{
					if (!PSActivity.CheckForCancel(pSActivityContext))
					{
						if (!pSActivityContext.runningCommands.ContainsKey(powerShellInstance))
						{
							pSActivityContext.runningCommands[powerShellInstance] = new RetryCount();
						}
					}
					else
					{
						return;
					}
				}
				if (!PSActivity.CheckForCancel(pSActivityContext))
				{
					RetryCount item = pSActivityContext.runningCommands[powerShellInstance];
					item.ActionAttempts = item.ActionAttempts + 1;
					if (commandExecutionType != 5)
					{
						PSActivity.UpdatePowerShell(implementationContext, pSActivityContext, activityType, @delegate, activityObject);
					}
					int num = commandExecutionType;
					switch (num)
					{
						case 0:
						{
							PSActivity.InitializeActivityEnvironmentAndAddRequiredModules(implementationContext, activityParameters);
							workflowHost.LocalRunspaceProvider.BeginGetRunspace(null, 0, 0, new AsyncCallback(PSActivity.LocalRunspaceProviderCallback), args);
							goto Label1;
						}
						case 1:
						case 5:
						{
						Label1:
							break;
						}
						case 2:
						{
							PSActivity.InitializeActivityEnvironmentAndAddRequiredModules(implementationContext, activityParameters);
							goto Label1;
						}
						case 3:
						{
							PSActivity.DisposeRunspaceInPowerShell(powerShellInstance, false);
							PSActivity.InitializeActivityEnvironmentAndAddRequiredModules(implementationContext, activityParameters);
							WSManConnectionInfo connectionInfo = powerShellInstance.Runspace.ConnectionInfo as WSManConnectionInfo;
							uint? connectionRetryCount = activityParameters.ConnectionRetryCount;
							uint? connectionRetryInterval = activityParameters.ConnectionRetryInterval;
							workflowHost.RemoteRunspaceProvider.BeginGetRunspace(connectionInfo, connectionRetryCount.GetValueOrDefault(0), connectionRetryInterval.GetValueOrDefault(0), new AsyncCallback(PSActivity.ConnectionManagerCallback), args);
							goto Label1;
						}
						case 4:
						{
							workflowHost.LocalRunspaceProvider.BeginGetRunspace(null, 0, 0, new AsyncCallback(PSActivity.LocalRunspaceProviderCallback), args);
							goto Label1;
						}
						default:
						{
							goto Label1;
						}
					}
				}
			}
		}
Exemple #9
0
		private static void ReleaseResourcesAndCheckForEnd(System.Management.Automation.PowerShell ps, RunCommandsArguments args, bool removeHandlersFromStreams, bool attemptRetry)
		{
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				PSActivityContext pSActivityContext = args.PSActivityContext;
				if (removeHandlersFromStreams)
				{
					PSActivity.RemoveHandlersFromStreams(ps, args);
				}
				PSActivity.RunOneCommandFinally(args, attemptRetry);
				traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "PowerShell activity: Finished running command.", new object[0]));
				PSActivity.DecrementRunningCountAndCheckForEnd(pSActivityContext);
			}
		}
Exemple #10
0
		private static void BeginRunspaceInitializeSetup(RunCommandsArguments args)
		{
			PSActivityEnvironment pSActivityEnvironment = args.ImplementationContext.PSActivityEnvironment;
			Runspace runspace = args.ImplementationContext.PowerShellInstance.Runspace;
			string[] pSRequiredModules = args.ActivityParameters.PSRequiredModules;
			PSActivityContext pSActivityContext = args.PSActivityContext;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				traceSource.WriteMessage("BEGIN BeginRunspaceInitializeSetup");
				if (args.CommandExecutionType != 4)
				{
					if (runspace.ConnectionInfo == null)
					{
						try
						{
							PSActivity.SetVariablesInRunspaceUsingProxy(pSActivityEnvironment, runspace);
						}
						catch (Exception exception1)
						{
							Exception exception = exception1;
							bool flag = PSActivity.HandleRunOneCommandException(args, exception);
							if (!flag)
							{
								traceSource.WriteMessage("Setting variables for command failed, returning");
								PSActivity.RunOneCommandFinally(args, false);
							}
							else
							{
								traceSource.WriteMessage("Setting variables for command failed, attempting retry");
								PSActivity.CloseRunspace(args.ImplementationContext.PowerShellInstance.Runspace, args.CommandExecutionType, args.WorkflowHost, pSActivityContext);
								PSActivity.BeginActionRetry(args);
							}
							PSActivity.DecrementRunningCountAndCheckForEnd(pSActivityContext);
							return;
						}
					}
					else
					{
						PSActivity.BeginSetVariablesInRemoteRunspace(args);
						return;
					}
				}
				if ((int)pSRequiredModules.Length <= 0)
				{
					PSActivity.BeginPowerShellInvocation(args);
				}
				else
				{
					PSActivity.BeginImportRequiredModules(args);
				}
				traceSource.WriteMessage("END BeginRunspaceInitializeSetup");
			}
		}
Exemple #11
0
		private static void ExecuteCleanupActivity(RunCommandsArguments args)
		{
			PSCleanupActivity activityObject = args.ActivityObject as PSCleanupActivity;
			if (activityObject != null)
			{
				activityObject.DoCleanup(args, new WaitCallback(PSActivity.CleanupActivityCallback));
				return;
			}
			else
			{
				throw new ArgumentNullException("args");
			}
		}
Exemple #12
0
        public void Cancel()
        {
            ActivityImplementationContext activityImplementationContext = null;
            IAsyncResult asyncResult = null;

            if (this.WorkflowHost != null)
            {
                if (this.commandQueue != null)
                {
                    while (!this.commandQueue.IsEmpty)
                    {
                        bool flag = this.commandQueue.TryDequeue(out activityImplementationContext);
                        if (!flag)
                        {
                            continue;
                        }
                        PowerShell powerShellInstance = activityImplementationContext.PowerShellInstance;
                        object[]   objArray           = new object[1];
                        objArray[0] = powerShellInstance;
                        this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "PowerShell activity: Cancelling pending command {0}.", objArray));
                        powerShellInstance.Dispose();
                    }
                }
                PSResumableActivityHostController pSActivityHostController = this.WorkflowHost.PSActivityHostController as PSResumableActivityHostController;
                if (pSActivityHostController == null)
                {
                    PSOutOfProcessActivityController pSOutOfProcessActivityController = this.WorkflowHost.PSActivityHostController as PSOutOfProcessActivityController;
                    if (pSOutOfProcessActivityController != null)
                    {
                        while (this.AsyncResults.Count > 0)
                        {
                            this.AsyncResults.TryDequeue(out asyncResult);
                            pSOutOfProcessActivityController.CancelInvokePowerShell(asyncResult);
                        }
                    }
                }
                else
                {
                    pSActivityHostController.StopAllResumablePSCommands(this.JobInstanceId);
                }
                while (this.runningCommands.Count > 0)
                {
                    PowerShell powerShell = null;
                    lock (this.runningCommands)
                    {
                        Dictionary <PowerShell, RetryCount> .KeyCollection.Enumerator enumerator = this.runningCommands.Keys.GetEnumerator();
                        try
                        {
                            if (enumerator.MoveNext())
                            {
                                PowerShell current = enumerator.Current;
                                powerShell = current;
                            }
                        }
                        finally
                        {
                            enumerator.Dispose();
                        }
                        if (powerShell == null)
                        {
                            break;
                        }
                    }
                    if (powerShell.InvocationStateInfo.State == PSInvocationState.Running)
                    {
                        object[] objArray1 = new object[1];
                        objArray1[0] = powerShell;
                        this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "PowerShell activity: Stopping command {0}.", objArray1));
                        try
                        {
                            powerShell.Stop();
                        }
                        catch (NullReferenceException nullReferenceException)
                        {
                        }
                        catch (InvalidOperationException invalidOperationException)
                        {
                        }
                    }
                    if (powerShell.InvocationStateInfo.State != PSInvocationState.Completed || powerShell.HadErrors)
                    {
                        this.Failed = true;
                    }
                    int num = RunCommandsArguments.DetermineCommandExecutionType(powerShell.Runspace.ConnectionInfo as WSManConnectionInfo, this.RunInProc, this.ActivityType, this);
                    if (num != 1)
                    {
                        PSActivity.CloseRunspaceAndDisposeCommand(powerShell, this.WorkflowHost, this, num);
                    }
                    this.runningCommands.Remove(powerShell);
                }
                return;
            }
            else
            {
                throw new InvalidOperationException("WorkflowHost");
            }
        }
Exemple #13
0
		private static void BeginActionRetry(RunCommandsArguments args)
		{
			PSActivityContext pSActivityContext = args.PSActivityContext;
			Interlocked.Increment(ref pSActivityContext.CommandsRunningCount);
			PSActivity.BeginRunOneCommand(args);
		}
Exemple #14
0
		private static void BeginExecuteOneCommand(RunCommandsArguments args)
		{
			PSActivityContext pSActivityContext = args.PSActivityContext;
			PSWorkflowHost workflowHost = args.WorkflowHost;
			ActivityImplementationContext implementationContext = args.ImplementationContext;
			PSDataCollection<PSObject> input = args.Input;
			PSDataCollection<PSObject> output = args.Output;
			int commandExecutionType = args.CommandExecutionType;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				PowerShell powerShellInstance = implementationContext.PowerShellInstance;
				object[] objArray = new object[1];
				objArray[0] = powerShellInstance;
				traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "BEGIN BeginExecuteOneCommand {0}.", objArray));
				int num = commandExecutionType;
				switch (num)
				{
					case 0:
					{
						powerShellInstance.Runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
						ThreadPool.QueueUserWorkItem(new WaitCallback(PSActivity.InitializeRunspaceAndExecuteCommandWorker), args);
						break;
					}
					case 1:
					{
						ThreadPool.QueueUserWorkItem(new WaitCallback(PSActivity.ExecuteOneRunspaceFreeCommandWorker), args);
						break;
					}
					case 2:
					{
						if (!PSActivity.CheckForCancel(pSActivityContext))
						{
							PSResumableActivityHostController pSActivityHostController = workflowHost.PSActivityHostController as PSResumableActivityHostController;
							if (pSActivityHostController == null)
							{
								PSOutOfProcessActivityController pSOutOfProcessActivityController = workflowHost.PSActivityHostController as PSOutOfProcessActivityController;
								if (pSOutOfProcessActivityController == null)
								{
									break;
								}
								PSActivity.AddHandlersToStreams(powerShellInstance, args);
								IAsyncResult asyncResult = pSOutOfProcessActivityController.BeginInvokePowerShell(powerShellInstance, input, output, implementationContext.PSActivityEnvironment, new AsyncCallback(PSActivity.ActivityHostManagerCallback), args);
								pSActivityContext.AsyncResults.Enqueue(asyncResult);
								break;
							}
							else
							{
								PowerShellStreams<PSObject, PSObject> powerShellStream = new PowerShellStreams<PSObject, PSObject>();
								if (!pSActivityHostController.SupportDisconnectedPSStreams)
								{
									powerShellStream.InputStream = input;
									powerShellStream.OutputStream = output;
									powerShellStream.DebugStream = powerShellInstance.Streams.Debug;
									powerShellStream.ErrorStream = powerShellInstance.Streams.Error;
									powerShellStream.ProgressStream = powerShellInstance.Streams.Progress;
									powerShellStream.VerboseStream = powerShellInstance.Streams.Verbose;
									powerShellStream.WarningStream = powerShellInstance.Streams.Warning;
								}
								else
								{
									powerShellStream.InputStream = input;
									powerShellStream.OutputStream = new PSDataCollection<PSObject>();
									powerShellStream.ErrorStream = new PSDataCollection<ErrorRecord>();
									powerShellStream.DebugStream = new PSDataCollection<DebugRecord>();
									powerShellStream.ProgressStream = new PSDataCollection<ProgressRecord>();
									powerShellStream.VerboseStream = new PSDataCollection<VerboseRecord>();
									powerShellStream.WarningStream = new PSDataCollection<WarningRecord>();
								}
								pSActivityHostController.StartResumablePSCommand(args.PSActivityContext.JobInstanceId, (Bookmark)args.PSActivityContext.AsyncState, powerShellInstance, powerShellStream, implementationContext.PSActivityEnvironment, (PSActivity)pSActivityContext.ActivityObject);
								break;
							}
						}
						else
						{
							return;
						}
					}
					case 3:
					{
						PSActivity.ArgsTableForRunspaces.TryAdd(powerShellInstance.Runspace.InstanceId, args);
						PSActivity.InitializeRunspaceAndExecuteCommandWorker(args);
						break;
					}
					case 4:
					{
						ThreadPool.QueueUserWorkItem(new WaitCallback(PSActivity.InitializeRunspaceAndExecuteCommandWorker), args);
						break;
					}
					case 5:
					{
						PSActivity.ExecuteCleanupActivity(args);
						break;
					}
				}
				traceSource.WriteMessage("END BeginExecuteOneCommand");
			}
		}
Exemple #15
0
		private static void AddHandlersToStreams(System.Management.Automation.PowerShell commandToRun, RunCommandsArguments args)
		{
			if (commandToRun == null || args == null)
			{
				return;
			}
			else
			{
				bool mergeErrorToOutput = args.PSActivityContext.MergeErrorToOutput;
				if (mergeErrorToOutput)
				{
					commandToRun.Streams.Error.DataAdded += new EventHandler<DataAddedEventArgs>(PSActivity.HandleErrorDataAdded);
				}
				if (args.PSActivityContext.Output != null)
				{
					args.PSActivityContext.Output.DataAdding += new EventHandler<DataAddingEventArgs>(PSActivity.HandleOutputDataAdding);
				}
				commandToRun.Streams.Error.DataAdding += new EventHandler<DataAddingEventArgs>(PSActivity.HandleErrorDataAdding);
				commandToRun.Streams.Progress.DataAdding += new EventHandler<DataAddingEventArgs>(PSActivity.HandleProgressDataAdding);
				commandToRun.Streams.Verbose.DataAdding += new EventHandler<DataAddingEventArgs>(PSActivity.HandleInformationalRecordDataAdding);
				commandToRun.Streams.Warning.DataAdding += new EventHandler<DataAddingEventArgs>(PSActivity.HandleInformationalRecordDataAdding);
				commandToRun.Streams.Debug.DataAdding += new EventHandler<DataAddingEventArgs>(PSActivity.HandleInformationalRecordDataAdding);
				PSActivity.ArgsTable.TryAdd(commandToRun.InstanceId, args);
				return;
			}
		}
Exemple #16
0
		private static void RunspaceDisconnectedCallback(RunCommandsArguments args, Exception runspaceDisconnectedException)
		{
			PSActivityContext pSActivityContext = args.PSActivityContext;
			ActivityImplementationContext implementationContext = args.ImplementationContext;
			PowerShell powerShellInstance = implementationContext.PowerShellInstance;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				traceSource.WriteMessage("Executing callback when remote runspace got disconnected");
				bool flag = false;
				try
				{
					try
					{
						if (!PSActivity.CheckForCancel(pSActivityContext))
						{
							implementationContext.CleanUp();
							if (args.HelperCommand != null)
							{
								args.HelperCommand.Dispose();
								args.HelperCommand = null;
							}
							traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "Runspace disconnected is treated as an errors in executing the command.", new object[0]));
							pSActivityContext.Failed = true;
							throw runspaceDisconnectedException;
						}
						else
						{
							return;
						}
					}
					catch (Exception exception1)
					{
						Exception exception = exception1;
						flag = PSActivity.HandleRunOneCommandException(args, exception);
						if (flag)
						{
							PSActivity.BeginActionRetry(args);
						}
					}
				}
				finally
				{
					PSActivity.RemoveHandlersFromStreams(powerShellInstance, args);
					PSActivity.RunOneCommandFinally(args, flag);
					traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "PowerShell activity: Finished running command.", new object[0]));
					PSActivity.DecrementRunningCountAndCheckForEnd(pSActivityContext);
				}
			}
		}
Exemple #17
0
		private static void RunOneCommandFinally(RunCommandsArguments args, bool attemptRetry)
		{
			if (!attemptRetry)
			{
				PSActivityContext pSActivityContext = args.PSActivityContext;
				ActivityImplementationContext implementationContext = args.ImplementationContext;
				PSWorkflowHost workflowHost = args.WorkflowHost;
				PowerShell powerShellInstance = implementationContext.PowerShellInstance;
				lock (pSActivityContext.runningCommands)
				{
					pSActivityContext.runningCommands.Remove(powerShellInstance);
				}
				if (!pSActivityContext.IsCanceled && args.CommandExecutionType != 1)
				{
					PSActivity.CloseRunspaceAndDisposeCommand(powerShellInstance, workflowHost, pSActivityContext, args.CommandExecutionType);
				}
				return;
			}
			else
			{
				return;
			}
		}
Exemple #18
0
		public bool Execute()
		{
			ActivityImplementationContext activityImplementationContext = null;
			if (this.commandQueue != null)
			{
				bool flag = this.commandQueue.TryDequeue(out activityImplementationContext);
				lock (this.SyncRoot)
				{
					while (flag)
					{
						RunCommandsArguments runCommandsArgument = new RunCommandsArguments(this.ActivityParams, this.Output, this.Input, this, this.WorkflowHost, this.RunInProc, this.ParameterDefaults, this.ActivityType, this.PrepareSession, this.ActivityObject, activityImplementationContext);
						Interlocked.Increment(ref this.CommandsRunningCount);
						PSActivity.BeginRunOneCommand(runCommandsArgument);
						flag = this.commandQueue.TryDequeue(out activityImplementationContext);
					}
					this.AllCommandsStarted = true;
				}
				return true;
			}
			else
			{
				throw new InvalidOperationException("commandQueue");
			}
		}
Exemple #19
0
		private static void BeginInvokeOnPowershellCommand(System.Management.Automation.PowerShell ps, PSDataCollection<object> varsInput, PSInvocationSettings settings, AsyncCallback callback, RunCommandsArguments args)
		{
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				try
				{
					ps.BeginInvoke<object>(varsInput, settings, callback, args);
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					bool flag = PSActivity.ProcessException(args, exception);
					if (!flag)
					{
						PSActivity.ReleaseResourcesAndCheckForEnd(ps, args, false, false);
					}
					else
					{
						PSActivity.BeginActionRetry(args);
					}
					traceSource.TraceException(exception);
				}
			}
		}
 /// <summary>
 /// Method that needs to be overridden to perform the actual
 /// cleanup action
 /// </summary>
 /// <param name="args">RunCommandsArguments</param>
 /// <param name="callback">callback to call when cleanup
 /// is done</param>
 /// <remarks>The signature forces this method to be internal</remarks>
 internal virtual void DoCleanup(RunCommandsArguments args, WaitCallback callback)
 {
     throw new NotImplementedException();
 }
Exemple #21
0
		internal static void BeginRunOneCommand(RunCommandsArguments args)
		{
			PSActivityContext pSActivityContext = args.PSActivityContext;
			ActivityImplementationContext implementationContext = args.ImplementationContext;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				PowerShell powerShellInstance = implementationContext.PowerShellInstance;
				object[] objArray = new object[1];
				objArray[0] = powerShellInstance;
				traceSource.WriteMessage(string.Format(CultureInfo.InvariantCulture, "Begining action to run command {0}.", objArray));
				if (!PSActivity.CheckForCancel(pSActivityContext))
				{
					PSActivity.InitializeOneCommand(args);
					if (args.CommandExecutionType != 3 && args.CommandExecutionType != 0 && args.CommandExecutionType != 4)
					{
						PSActivity.BeginExecuteOneCommand(args);
					}
				}
			}
		}
Exemple #22
0
		private static void BeginImportRequiredModules(RunCommandsArguments args)
		{
			Runspace runspace = args.ImplementationContext.PowerShellInstance.Runspace;
			PSActivityEnvironment pSActivityEnvironment = args.ImplementationContext.PSActivityEnvironment;
			System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create();
			if (pSActivityEnvironment == null)
			{
				powerShell.AddCommand("Import-Module").AddParameter("Name", args.ActivityParameters.PSRequiredModules).AddParameter("ErrorAction", ActionPreference.Stop);
			}
			else
			{
				powerShell.AddCommand("Import-Module").AddParameter("Name", pSActivityEnvironment.Modules).AddParameter("ErrorAction", ActionPreference.Stop);
			}
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				traceSource.WriteMessage("Importing modules in runspace ", runspace.InstanceId);
				powerShell.Runspace = runspace;
				args.HelperCommand = powerShell;
				PSActivity.BeginInvokeOnPowershellCommand(powerShell, null, null, new AsyncCallback(PSActivity.ImportRequiredModulesCallback), args);
			}
		}
Exemple #23
0
		private static bool ProcessException(RunCommandsArguments args, Exception e)
		{
			string str = null;
			Guid guid;
			IContainsErrorRecord containsErrorRecord;
			ErrorRecord errorRecord;
			string str1 = null;
			Guid guid1;
			bool flag = false;
			PSActivityContext pSActivityContext = args.PSActivityContext;
			ActivityImplementationContext implementationContext = args.ImplementationContext;
			PowerShell powerShellInstance = implementationContext.PowerShellInstance;
			uint? connectionRetryCount = args.ActivityParameters.ConnectionRetryCount;
			if (!connectionRetryCount.HasValue)
			{
				uint? connectionRetryInterval = args.ActivityParameters.ConnectionRetryInterval;
				if (!connectionRetryInterval.HasValue)
				{
					containsErrorRecord = e as IContainsErrorRecord;
					if (containsErrorRecord != null)
					{
						errorRecord = containsErrorRecord.ErrorRecord;
						if (PSActivity.GetComputerNameAndJobIdForCommand(powerShellInstance.InstanceId, out str1, out guid1))
						{
							PSActivity.AddIdentifierInfoToErrorRecord(errorRecord, str1, guid1);
						}
					}
					flag = PSActivity.HandleRunOneCommandException(args, e);
					return flag;
				}
			}
			if (e.InnerException != null && e.InnerException as IContainsErrorRecord != null)
			{
				IContainsErrorRecord containsErrorRecord1 = e as IContainsErrorRecord;
				if (containsErrorRecord1.ErrorRecord.FullyQualifiedErrorId.StartsWith("CimJob_BrokenCimSession", StringComparison.OrdinalIgnoreCase))
				{
					int actionAttempts = 0x7fffffff;
					if (!pSActivityContext.IsCanceled)
					{
						if (pSActivityContext.runningCommands.ContainsKey(powerShellInstance))
						{
							actionAttempts = pSActivityContext.runningCommands[powerShellInstance].ActionAttempts;
						}
						flag = PSActivity.HandleFailure(actionAttempts, args.ActivityParameters.ConnectionRetryCount, args.ActivityParameters.ConnectionRetryInterval, implementationContext, "ActivityActionFailed", null, pSActivityContext);
					}
					if (!flag)
					{
						ErrorRecord errorRecord1 = containsErrorRecord1.ErrorRecord;
						if (PSActivity.GetComputerNameAndJobIdForCommand(powerShellInstance.InstanceId, out str, out guid))
						{
							PSActivity.AddIdentifierInfoToErrorRecord(errorRecord1, str, guid);
						}
						if (implementationContext.PSComputerName == null || (int)implementationContext.PSComputerName.Length <= 1)
						{
							lock (pSActivityContext.exceptions)
							{
								pSActivityContext.exceptions.Add(e);
							}
						}
						else
						{
							PSActivity.WriteError(e, "ActivityActionFailed", ErrorCategory.InvalidResult, implementationContext.PowerShellInstance.Runspace.ConnectionInfo, pSActivityContext);
						}
					}
					return flag;
				}
			}
			containsErrorRecord = e as IContainsErrorRecord;
			if (containsErrorRecord != null)
			{
				errorRecord = containsErrorRecord.ErrorRecord;
				if (PSActivity.GetComputerNameAndJobIdForCommand(powerShellInstance.InstanceId, out str1, out guid1))
				{
					PSActivity.AddIdentifierInfoToErrorRecord(errorRecord, str1, guid1);
				}
			}
			flag = PSActivity.HandleRunOneCommandException(args, e);
			return flag;
		}