Beispiel #1
0
        /// <summary>
        /// Execute the logic for this activity...
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            // Retrieve our host overrides
            HostParameterDefaults hostValues = context.GetExtension <HostParameterDefaults>();

            SetHostValuesByVariableName(context, hostValues);
            SetHostValuesByProperty(context, hostValues);
        }
Beispiel #2
0
        private void SetHostValuesByVariableName(NativeActivityContext context, HostParameterDefaults hostValues)
        {
            // Set the Command / host metadata
            string variableName = null;

            if (OtherVariableName.Get(context) != null)
            {
                if (OtherVariableName.Expression != null)
                {
                    string value = OtherVariableName.Get(context);

                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        variableName = value;
                    }
                }

                if (String.Equals(variableName, "Position", StringComparison.OrdinalIgnoreCase))
                {
                    HostSettingCommandMetadata metadata = hostValues.HostCommandMetadata;

                    // The position should come in as line:column:command
                    string   positionMessage  = (string)Value.Get(context);
                    string[] positionElements = positionMessage.Split(new char[] { ':' }, 3);

                    string line        = positionElements[0].Trim();
                    string column      = positionElements[1].Trim();
                    string commandName = positionElements[2].Trim();

                    if (!String.IsNullOrEmpty(line))
                    {
                        metadata.StartLineNumber = Int32.Parse(line, CultureInfo.InvariantCulture);
                    }

                    if (!String.IsNullOrEmpty(column))
                    {
                        metadata.StartColumnNumber = Int32.Parse(line, CultureInfo.InvariantCulture);
                    }

                    if (!String.IsNullOrEmpty(commandName))
                    {
                        metadata.CommandName = commandName;
                    }
                }
                else
                {
                    if (Value.Get(context) == null)
                    {
                        hostValues.Parameters.Remove(variableName);
                    }
                    else
                    {
                        hostValues.Parameters[variableName] = Value.Get(context);
                    }
                }
            }
        }
Beispiel #3
0
        private void SetHostValuesByProperty(NativeActivityContext context, HostParameterDefaults hostValues)
        {
            Type currentType = this.GetType();

            // Populate any of our parameters into the host defaults.
            foreach (PropertyInfo field in currentType.GetProperties())
            {
                // See if it's an argument
                if (typeof(Argument).IsAssignableFrom(field.PropertyType))
                {
                    // Skip the ones that are specific to this activity
                    if (String.Equals("VariableToSet", field.Name, StringComparison.OrdinalIgnoreCase) ||
                        String.Equals("OtherVariableName", field.Name, StringComparison.OrdinalIgnoreCase) ||
                        String.Equals("Value", field.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    // Handle Bookmark timeouts, but don't set them as a host default.
                    if (String.Equals("PSBookmarkTimeoutSec", field.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        // See if this is trying to change the bookmark timeout
                        if (PSBookmarkTimeoutSec.Get(context).HasValue)
                        {
                            SafelySetResumeBookmarkTimeout(TimeSpan.FromSeconds(PSBookmarkTimeoutSec.Get(context).Value));
                        }
                        else
                        {
                            SafelySetResumeBookmarkTimeout(TimeSpan.FromSeconds(0));
                        }

                        continue;
                    }

                    // Get the argument
                    Argument currentArgument = (Argument)field.GetValue(this, null);
                    if (currentArgument.Expression != null)
                    {
                        if (currentArgument.Get(context) == null)
                        {
                            hostValues.Parameters.Remove(field.Name);
                        }
                        else
                        {
                            hostValues.Parameters[field.Name] = currentArgument.Get(context);
                        }
                    }
                }
            }
        }
Beispiel #4
0
        private void ConfigureAllExtensions()
        {
            // declaring instance store
            this.workflowApplication.InstanceStore = _stores.CreateInstanceStore();

            var IOParticipant = _stores.CreatePersistenceIOParticipant();
            if (IOParticipant != null)
                this.workflowApplication.Extensions.Add(IOParticipant);

            // adding the tracking participants
            this.workflowApplication.Extensions.Add(this.GetTrackingParticipant());

            // adding the custom extensions
            IEnumerable<object> extensions = this.Runtime.Configuration.CreateWorkflowExtensions();
            if (extensions != null)
            {
                foreach (object extension in extensions)
                {
                    this.workflowApplication.Extensions.Add(extension);
                }
            }

            // adding the custom extension creation functions
            IEnumerable<Func<object>> extensionFunctions = this.Runtime.Configuration.CreateWorkflowExtensionCreationFunctions<object>();
            if (extensionFunctions != null)
            {
                foreach(Func<object> extensionFunc in extensionFunctions)
                {
                    this.workflowApplication.Extensions.Add<object>(extensionFunc);
                }
            }
            
            _paramDefaults = new HostParameterDefaults();

            if (this.PSWorkflowContext.PSWorkflowCommonParameters != null)
            {
                foreach (KeyValuePair<string, object> param in this.PSWorkflowContext.PSWorkflowCommonParameters)
                {
                    if (param.Key != Constants.PSRunningTime && param.Key != Constants.PSElapsedTime)
                    {
                        _paramDefaults.Parameters.Add(param.Key, param.Value);
                    }
                }
            }

            if (this.PSWorkflowContext.PrivateMetadata != null)
            {
                _paramDefaults.Parameters[Constants.PrivateMetadata] = this.PSWorkflowContext.PrivateMetadata;
            }

            // Job related parameters
            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataName))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataName)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataName];
            }

            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataInstanceId))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataInstanceId)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataInstanceId];
            }

            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataSessionId))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataSessionId)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataSessionId];
            }

            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataCommand))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataCommand)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataCommand];
            }

            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataParentName))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataParentName)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataParentName];
            }

            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataParentInstanceId))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataParentInstanceId)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataParentInstanceId];
            }

            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataParentSessionId))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataParentSessionId)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataParentSessionId];
            }

            if (this.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataParentCommand))
            {
                _paramDefaults.Parameters[TranslateMetaDataName(Constants.JobMetadataParentCommand)] = 
                    this.PSWorkflowContext.JobMetadata[Constants.JobMetadataParentCommand];
            }

            _paramDefaults.Parameters["WorkflowInstanceId"] = this.InstanceId;
          
            _paramDefaults.Parameters["Input"] = this.Streams.InputStream;
            _paramDefaults.Parameters["Result"] = this.Streams.OutputStream;
            _paramDefaults.Parameters["PSError"] = this.Streams.ErrorStream;
            _paramDefaults.Parameters["PSWarning"] = this.Streams.WarningStream;
            _paramDefaults.Parameters["PSProgress"] = this.Streams.ProgressStream;
            _paramDefaults.Parameters["PSVerbose"] = this.Streams.VerboseStream;
            _paramDefaults.Parameters["PSDebug"] = this.Streams.DebugStream;
            _paramDefaults.Parameters["PSInformation"] = this.Streams.InformationStream;

            // Assign PSActivityHost here
            _paramDefaults.Runtime = Runtime;

            _paramDefaults.JobInstanceId = _job.InstanceId;

            // Assign PSHostPersistDelegate here
            Func<bool> hostDelegate = this.CheckForPersistenceAfterPSActivity;
            _paramDefaults.HostPersistenceDelegate = hostDelegate;

            Action<object> activateDelegate = this.ReactivateWorkflow;
            _paramDefaults.ActivateDelegate = activateDelegate;

            _paramDefaults.AsyncExecutionCollection = this.asyncExecutionCollection;
            _paramDefaults.RemoteActivityState = this.RemoteActivityState;

            System.Activities.Hosting.SymbolResolver resolver = new System.Activities.Hosting.SymbolResolver();
            resolver.Add("ParameterDefaults", _paramDefaults);

            this.workflowApplication.Extensions.Add(resolver);
            this.workflowApplication.Extensions.Add(_paramDefaults);
        }
Beispiel #5
0
        /// <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 Dispose(bool disposing)
		{
			if (!disposing || base.Disposed)
			{
				return;
			}
			else
			{
				lock (base.SyncLock)
				{
					if (!base.Disposed)
					{
						base.Disposed = true;
						lock (this.ReactivateSync)
						{
							this.IsTerminalStateAction = true;
							this.PersistIdleTimerInProgressOrTriggered = false;
							this.InternalUnloaded = false;
						}
						this.ConfigureTimerOnUnload();
						WorkflowApplication workflowApplication = this.workflowApplication;
						this.DisposeWorkflowApplication();
						if (this._job.JobStateInfo.State == JobState.Running && workflowApplication != null)
						{
							try
							{
								workflowApplication.Abort("Disposing the job");
							}
							catch (Exception exception)
							{
							}
						}
						if (this._paramDefaults != null)
						{
							this._paramDefaults.Dispose();
							this._paramDefaults = null;
						}
						if (this._streams != null)
						{
							this.UnregisterHandlersForDataAdding(this._streams);
							this._streams.Dispose();
						}
						if (this._timers != null)
						{
							this._timers.Dispose();
						}
						this.DisposePersistUnloadTimer();
						base.Dispose(disposing);
					}
				}
				return;
			}
		}
Beispiel #7
0
        private void SetHostValuesByVariableName(NativeActivityContext context, HostParameterDefaults hostValues)
        {
            // Set the Command / host metadata
            string variableName = null;

            if (OtherVariableName.Get(context) != null)
            {
                if (OtherVariableName.Expression != null)
                {
                    string value = OtherVariableName.Get(context);

                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        variableName = value;
                    }
                }

                if (String.Equals(variableName, "Position", StringComparison.OrdinalIgnoreCase))
                {
                    HostSettingCommandMetadata metadata = hostValues.HostCommandMetadata;

                    // The position should come in as line:column:command
                    string positionMessage = (string)Value.Get(context);
                    string[] positionElements = positionMessage.Split(new char[] { ':' }, 3);

                    string line = positionElements[0].Trim();
                    string column = positionElements[1].Trim();
                    string commandName = positionElements[2].Trim();

                    if (!String.IsNullOrEmpty(line))
                    {
                        metadata.StartLineNumber = Int32.Parse(line, CultureInfo.InvariantCulture);
                    }

                    if (!String.IsNullOrEmpty(column))
                    {
                        metadata.StartColumnNumber = Int32.Parse(line, CultureInfo.InvariantCulture);
                    }

                    if (!String.IsNullOrEmpty(commandName))
                    {
                        metadata.CommandName = commandName;
                    }
                }
                else
                {
                    if (Value.Get(context) == null)
                    {
                        hostValues.Parameters.Remove(variableName);
                    }
                    else
                    {
                        hostValues.Parameters[variableName] = Value.Get(context);
                    }
                }
            }
        }
		private void ConfigureAllExtensions()
		{
			this.workflowApplication.InstanceStore = this._stores.CreateInstanceStore();
			PersistenceIOParticipant persistenceIOParticipant = this._stores.CreatePersistenceIOParticipant();
			if (persistenceIOParticipant != null)
			{
				this.workflowApplication.Extensions.Add(persistenceIOParticipant);
			}
			this.workflowApplication.Extensions.Add(this.GetTrackingParticipant());
			IEnumerable<object> objs = base.Runtime.Configuration.CreateWorkflowExtensions();
			if (objs != null)
			{
				foreach (object obj in objs)
				{
					this.workflowApplication.Extensions.Add(obj);
				}
			}
			IEnumerable<Func<object>> funcs = base.Runtime.Configuration.CreateWorkflowExtensionCreationFunctions<object>();
			if (funcs != null)
			{
				foreach (Func<object> func in funcs)
				{
					this.workflowApplication.Extensions.Add<object>(func);
				}
			}
			this._paramDefaults = new HostParameterDefaults();
			if (this.PSWorkflowContext.PSWorkflowCommonParameters != null)
			{
				foreach (KeyValuePair<string, object> pSWorkflowCommonParameter in this.PSWorkflowContext.PSWorkflowCommonParameters)
				{
					if (!(pSWorkflowCommonParameter.Key != "PSRunningTimeoutSec") || !(pSWorkflowCommonParameter.Key != "PSElapsedTimeoutSec"))
					{
						continue;
					}
					this._paramDefaults.Parameters.Add(pSWorkflowCommonParameter.Key, pSWorkflowCommonParameter.Value);
				}
			}
			if (this.PSWorkflowContext.PrivateMetadata != null)
			{
				this._paramDefaults.Parameters["PSPrivateMetadata"] = this.PSWorkflowContext.PrivateMetadata;
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("Name"))
			{
				this._paramDefaults.Parameters["JobName"] = this.PSWorkflowContext.JobMetadata["Name"];
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("InstanceId"))
			{
				this._paramDefaults.Parameters["JobInstanceId"] = this.PSWorkflowContext.JobMetadata["InstanceId"];
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("Id"))
			{
				this._paramDefaults.Parameters["JobId"] = this.PSWorkflowContext.JobMetadata["Id"];
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("Command"))
			{
				this._paramDefaults.Parameters["JobCommandName"] = this.PSWorkflowContext.JobMetadata["Command"];
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("ParentName"))
			{
				this._paramDefaults.Parameters["ParentJobName"] = this.PSWorkflowContext.JobMetadata["ParentName"];
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("ParentInstanceId"))
			{
				this._paramDefaults.Parameters["ParentJobInstanceId"] = this.PSWorkflowContext.JobMetadata["ParentInstanceId"];
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("ParentSessionId"))
			{
				this._paramDefaults.Parameters["ParentJobId"] = this.PSWorkflowContext.JobMetadata["ParentSessionId"];
			}
			if (this.PSWorkflowContext.JobMetadata.ContainsKey("ParentCommand"))
			{
				this._paramDefaults.Parameters["ParentCommandName"] = this.PSWorkflowContext.JobMetadata["ParentCommand"];
			}
			this._paramDefaults.Parameters["WorkflowInstanceId"] = this.InstanceId;
			this._paramDefaults.Parameters["Input"] = this.Streams.InputStream;
			this._paramDefaults.Parameters["Result"] = this.Streams.OutputStream;
			this._paramDefaults.Parameters["PSError"] = this.Streams.ErrorStream;
			this._paramDefaults.Parameters["PSWarning"] = this.Streams.WarningStream;
			this._paramDefaults.Parameters["PSProgress"] = this.Streams.ProgressStream;
			this._paramDefaults.Parameters["PSVerbose"] = this.Streams.VerboseStream;
			this._paramDefaults.Parameters["PSDebug"] = this.Streams.DebugStream;
			this._paramDefaults.Runtime = base.Runtime;
			this._paramDefaults.JobInstanceId = this._job.InstanceId;
			Func<bool> func1 = new Func<bool>(this.CheckForPersistenceAfterPSActivity);
			this._paramDefaults.HostPersistenceDelegate = func1;
			Action<object> action = new Action<object>(this.ReactivateWorkflow);
			this._paramDefaults.ActivateDelegate = action;
			this._paramDefaults.AsyncExecutionCollection = this.asyncExecutionCollection;
			SymbolResolver symbolResolvers = new SymbolResolver();
			symbolResolvers.Add("ParameterDefaults", this._paramDefaults);
			this.workflowApplication.Extensions.Add(symbolResolvers);
			this.workflowApplication.Extensions.Add(this._paramDefaults);
		}
Beispiel #9
0
        private void SetHostValuesByProperty(NativeActivityContext context, HostParameterDefaults hostValues)
        {
            Type currentType = this.GetType();

            // Populate any of our parameters into the host defaults.
            foreach (PropertyInfo field in currentType.GetProperties())
            {
                // See if it's an argument
                if (typeof(Argument).IsAssignableFrom(field.PropertyType))
                {
                    // Skip the ones that are specific to this activity
                    if (String.Equals("VariableToSet", field.Name, StringComparison.OrdinalIgnoreCase) ||
                        String.Equals("OtherVariableName", field.Name, StringComparison.OrdinalIgnoreCase) ||
                        String.Equals("Value", field.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    // Handle Bookmark timeouts, but don't set them as a host default.
                    if (String.Equals("PSBookmarkTimeoutSec", field.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        // See if this is trying to change the bookmark timeout
                        if (PSBookmarkTimeoutSec.Get(context).HasValue)
                        {
                            SafelySetResumeBookmarkTimeout(TimeSpan.FromSeconds(PSBookmarkTimeoutSec.Get(context).Value));
                        }
                        else
                        {
                            SafelySetResumeBookmarkTimeout(TimeSpan.FromSeconds(0));
                        }

                        continue;
                    }

                    // Get the argument
                    Argument currentArgument = (Argument)field.GetValue(this, null);
                    if (currentArgument.Expression != null)
                    {
                        if (currentArgument.Get(context) == null)
                        {
                            hostValues.Parameters.Remove(field.Name);
                        }
                        else
                        {
                            hostValues.Parameters[field.Name] = currentArgument.Get(context);
                        }
                    }
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Execute the logic for this activity...
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            // Retrieve our host overrides
            HostParameterDefaults hostValues = context.GetExtension <HostParameterDefaults>();

            PropertyDescriptorCollection col = context.DataContext.GetProperties();
            string variableName = null;

            if (VariableToRetrieve != PSWorkflowRuntimeVariable.Other)
            {
                // Get the symbolic name for the enum
                variableName = LanguagePrimitives.ConvertTo <string>(VariableToRetrieve);
            }
            else
            {
                if (OtherVariableName.Expression != null)
                {
                    string value = OtherVariableName.Get(context);

                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        variableName = value;
                    }
                }
            }

            //BUGBUG need a better exception here, could also do this as a custom validator
            // Make sure we have a variable here...
            if (string.IsNullOrWhiteSpace(variableName))
            {
                throw new InvalidOperationException("OtherVariable");
            }

            object valueToReturn = null;
            PSDataCollection <PSObject> outputStream = null;

            foreach (System.ComponentModel.PropertyDescriptor property in context.DataContext.GetProperties())
            {
                if (string.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    foreach (var parameter in ((Microsoft.PowerShell.Activities.HostParameterDefaults)property.GetValue(context.DataContext)).Parameters)
                    {
                        if (parameter.Key.Equals(variableName, StringComparison.OrdinalIgnoreCase))
                        {
                            valueToReturn = parameter.Value;
                        }
                        else if (parameter.Key.Equals("Result"))
                        {
                            outputStream = parameter.Value as PSDataCollection <PSObject>;
                        }
                    }

                    //
                    // If the property to return was all, then just return the entire collection as a hashtable.
                    // (We still needed to loop to find the output stream to write into.)
                    //
                    if (VariableToRetrieve == PSWorkflowRuntimeVariable.All)
                    {
                        System.Collections.Hashtable workflowRuntimeVariables = new System.Collections.Hashtable(StringComparer.OrdinalIgnoreCase);

                        string[] enumNames = VariableToRetrieve.GetType().GetEnumNames();

                        // Skipping last two enum names, Other and All, as they are not actual variable names
                        //
                        for (int i = 0; i < (enumNames.Length - 2); i++)
                        {
                            workflowRuntimeVariables.Add(enumNames[i], null);
                        }

                        Dictionary <String, Object> dictionaryParam = ((Microsoft.PowerShell.Activities.HostParameterDefaults)property.GetValue(context.DataContext)).Parameters;

                        foreach (string varKey in dictionaryParam.Keys)
                        {
                            // We need to get the values of required runtime variables only, not evrything from DataContext parameters
                            //
                            if (workflowRuntimeVariables.ContainsKey(varKey))
                            {
                                Object value = null;
                                dictionaryParam.TryGetValue(varKey, out value);
                                workflowRuntimeVariables[varKey] = value;
                            }
                        }

                        valueToReturn = workflowRuntimeVariables;
                    }
                    break;
                }
            }

            if (this.Result.Expression != null)
            {
                this.Result.Set(context, valueToReturn);
            }
            else if (outputStream != null)
            {
                if (valueToReturn != null)
                {
                    outputStream.Add(PSObject.AsPSObject(valueToReturn));
                }
            }
            else
            {
                //BUGBUG need a better exception here...
                throw new InvalidOperationException("Result");
            }
        }
        /// <summary>
        /// Adds the PSActivity variable to the active runspace, which is of type InlineScriptContext.
        /// </summary>
        /// <param name="implementationContext">The ActivityImplementationContext returned by the call to GetCommand.</param>
        protected override void PrepareSession(ActivityImplementationContext implementationContext)
        {
            if (implementationContext.PSActivityEnvironment == null)
            {
                implementationContext.PSActivityEnvironment = new PSActivityEnvironment();
            }

            // Update the preference variables
            UpdatePreferenceVariables(implementationContext);
            System.Management.Automation.PowerShell session = implementationContext.PowerShellInstance;

            implementationContext.PSActivityEnvironment.Variables["UserName"] = System.Environment.UserName;

            string computerName = null;

            if (implementationContext.ConnectionInfo != null)
            {
                computerName = implementationContext.ConnectionInfo.ComputerName;
            }
            if (string.IsNullOrEmpty(computerName))
            {
                computerName = "localhost";
            }

            implementationContext.PSActivityEnvironment.Variables["ComputerName"]   = computerName;
            implementationContext.PSActivityEnvironment.Variables["PSComputerName"] = computerName;

            string workflowCommandName = null;

            Dictionary <string, object> activityVariables = (Dictionary <string, object>)implementationContext.WorkflowContext;

            if (activityVariables != null && activityVariables.ContainsKey("ParameterDefaults"))
            {
                HostParameterDefaults defaults = activityVariables["ParameterDefaults"] as HostParameterDefaults;
                if (defaults != null)
                {
                    workflowCommandName = defaults.Parameters["WorkflowCommandName"] as string;
                }
            }

            if (string.IsNullOrEmpty(workflowCommandName))
            {
                workflowCommandName = "unknown";
            }

            implementationContext.PSActivityEnvironment.Variables["CommandName"] = workflowCommandName;

            // Populate the default variables
            InlineScriptContext inlineScriptContext = new InlineScriptContext(this);

            // Populate the activity variables
            foreach (KeyValuePair <string, object> entry in activityVariables)
            {
                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    System.Diagnostics.Debug.Assert(entry.Value is HostParameterDefaults, "ParameterDefaults does not contain a HostParameterDefaults object");
                    inlineScriptContext.Variables[entry.Key] = ((HostParameterDefaults)entry.Value).Parameters;
                    continue;
                }
                inlineScriptContext.Variables[entry.Key] = entry.Value;
            }

            // Set the PowerShell session variables...
            foreach (KeyValuePair <string, object> entry in activityVariables)
            {
                var value = entry.Value;

                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                implementationContext.PSActivityEnvironment.Variables[entry.Key] = value;
            }
        }
Beispiel #12
0
		private void PopulateSteamsData(PSResumableActivityContext arguments, NativeActivityContext context, HostParameterDefaults hostValues)
		{
			if (arguments.Streams.OutputStream != null)
			{
				if (base.Result.Expression == null)
				{
					if (hostValues.Parameters["Result"] != null && hostValues.Parameters["Result"].GetType() == typeof(PSDataCollection<PSObject>))
					{
						PSDataCollection<PSObject> item = hostValues.Parameters["Result"] as PSDataCollection<PSObject>;
						if (item != arguments.Streams.OutputStream && item != null && item.IsOpen)
						{
							foreach (PSObject outputStream in arguments.Streams.OutputStream)
							{
								item.Add(outputStream);
							}
						}
					}
				}
				else
				{
					base.Result.Set(context, arguments.Streams.OutputStream);
				}
			}
			if (arguments.Streams.InputStream != null)
			{
				if (base.Input.Expression == null)
				{
					if (hostValues.Parameters["Input"] != null && hostValues.Parameters["Input"].GetType() == typeof(PSDataCollection<PSObject>))
					{
						hostValues.Parameters["Input"] = arguments.Streams.InputStream;
					}
				}
				else
				{
					base.Input.Set(context, arguments.Streams.InputStream);
				}
			}
			if (arguments.Streams.ErrorStream != null)
			{
				if (this.PSError.Expression == null)
				{
					if (hostValues.Parameters["PSError"] != null && hostValues.Parameters["PSError"].GetType() == typeof(PSDataCollection<ErrorRecord>))
					{
						PSDataCollection<ErrorRecord> errorRecords = hostValues.Parameters["PSError"] as PSDataCollection<ErrorRecord>;
						if (errorRecords != arguments.Streams.ErrorStream && errorRecords != null && errorRecords.IsOpen)
						{
							foreach (ErrorRecord errorStream in arguments.Streams.ErrorStream)
							{
								errorRecords.Add(errorStream);
							}
						}
					}
				}
				else
				{
					this.PSError.Set(context, arguments.Streams.ErrorStream);
				}
			}
			if (arguments.Streams.WarningStream != null)
			{
				if (this.PSWarning.Expression == null)
				{
					if (hostValues.Parameters["PSWarning"] != null && hostValues.Parameters["PSWarning"].GetType() == typeof(PSDataCollection<WarningRecord>))
					{
						PSDataCollection<WarningRecord> warningRecords = hostValues.Parameters["PSWarning"] as PSDataCollection<WarningRecord>;
						if (warningRecords != arguments.Streams.WarningStream && warningRecords != null && warningRecords.IsOpen)
						{
							foreach (WarningRecord warningStream in arguments.Streams.WarningStream)
							{
								warningRecords.Add(warningStream);
							}
						}
					}
				}
				else
				{
					this.PSWarning.Set(context, arguments.Streams.WarningStream);
				}
			}
			if (arguments.Streams.ProgressStream != null)
			{
				if (this.PSProgress.Expression == null)
				{
					if (hostValues.Parameters["PSProgress"] != null && hostValues.Parameters["PSProgress"].GetType() == typeof(PSDataCollection<ProgressRecord>))
					{
						PSDataCollection<ProgressRecord> progressRecords = hostValues.Parameters["PSProgress"] as PSDataCollection<ProgressRecord>;
						if (progressRecords != arguments.Streams.ProgressStream && progressRecords != null && progressRecords.IsOpen)
						{
							foreach (ProgressRecord progressStream in arguments.Streams.ProgressStream)
							{
								progressRecords.Add(progressStream);
							}
						}
					}
				}
				else
				{
					this.PSProgress.Set(context, arguments.Streams.ProgressStream);
				}
			}
			if (arguments.Streams.VerboseStream != null)
			{
				if (this.PSVerbose.Expression == null)
				{
					if (hostValues.Parameters["PSVerbose"] != null && hostValues.Parameters["PSVerbose"].GetType() == typeof(PSDataCollection<VerboseRecord>))
					{
						PSDataCollection<VerboseRecord> verboseRecords = hostValues.Parameters["PSVerbose"] as PSDataCollection<VerboseRecord>;
						if (verboseRecords != arguments.Streams.VerboseStream && verboseRecords != null && verboseRecords.IsOpen)
						{
							foreach (VerboseRecord verboseStream in arguments.Streams.VerboseStream)
							{
								verboseRecords.Add(verboseStream);
							}
						}
					}
				}
				else
				{
					this.PSVerbose.Set(context, arguments.Streams.VerboseStream);
				}
			}
			if (arguments.Streams.DebugStream != null)
			{
				if (this.PSDebug.Expression == null)
				{
					if (hostValues.Parameters["PSDebug"] != null && hostValues.Parameters["PSDebug"].GetType() == typeof(PSDataCollection<DebugRecord>))
					{
						PSDataCollection<DebugRecord> debugRecords = hostValues.Parameters["PSDebug"] as PSDataCollection<DebugRecord>;
						if (debugRecords != arguments.Streams.DebugStream && debugRecords != null && debugRecords.IsOpen)
						{
							foreach (DebugRecord debugStream in arguments.Streams.DebugStream)
							{
								debugRecords.Add(debugStream);
							}
						}
					}
				}
				else
				{
					this.PSDebug.Set(context, arguments.Streams.DebugStream);
					return;
				}
			}
		}
Beispiel #13
0
		internal static PSWorkflowHost GetWorkflowHost(HostParameterDefaults defaults)
		{
			PSWorkflowHost instance = null;
			if (defaults != null && defaults.Runtime != null)
			{
				PSWorkflowHost runtime = defaults.Runtime;
				Interlocked.CompareExchange<PSWorkflowHost>(ref instance, runtime, null);
			}
			if (instance == null)
			{
				instance = DefaultWorkflowHost.Instance;
			}
			return instance;
		}