Ejemplo n.º 1
0
 private Command()
 {
     Parameters = new CommandParameterCollection();
     MergeMyResult = PipelineResultTypes.None;
     MergeToResult = PipelineResultTypes.None;
     ScriptBlockAst = null;
 }
Ejemplo n.º 2
0
 public JobInvocationInfo(JobDefinition definition, CommandParameterCollection parameters)
 {
     this._name = string.Empty;
     this._instanceId = Guid.NewGuid();
     this._definition = definition;
     this.Parameters.Add(parameters ?? new CommandParameterCollection());
 }
Ejemplo n.º 3
0
 public Command(string command, bool isScript, bool useLocalScope)
 {
     CommandText = command;
     IsScript = isScript;
     UseLocalScope = useLocalScope;
     Parameters = new CommandParameterCollection();
     MergeMyResult = PipelineResultTypes.None;
     MergeToResult = PipelineResultTypes.None;
 }
Ejemplo n.º 4
0
 internal Command(System.Management.Automation.CommandInfo commandInfo, bool isScript)
 {
     this._mergeInstructions = new PipelineResultTypes[4];
     this._parameters = new CommandParameterCollection();
     this._command = string.Empty;
     this._commandInfo = commandInfo;
     this._command = this._commandInfo.Name;
     this._isScript = isScript;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Binds the parameters from the command line to the command.
        /// </summary>
        /// <remarks>
        /// All abount Cmdlet parameters: http://msdn2.microsoft.com/en-us/library/ms714433(VS.85).aspx
        /// About the lifecycle: http://msdn.microsoft.com/en-us/library/ms714429(v=vs.85).aspx
        /// </remarks>
        public void BindCommandLineParameters(CommandParameterCollection parameters)
        {
            // How command line parameters are bound:
            // In general: We will bind first named parameters, then positionals, and then maybe gather some.
            // While parameters are being bound, a list of _candidateParameterSets is maintained that keeps track
            // of those sets that are eligible for being taken.
            // As we might have an early choice that can be handled, an _activeSet is maintained in addition.
            // The _candidateSet will be restricted to the _activeSet if we found one early

            // Check if one obvious choice for a parameter set to be chosen (e.g. if there is only one)
            _activeSet = SelectObviousActiveParameterSet();

            // Bind all named parameters, fail if some name is bound twice or if the selection is already ambiguos
            parameters = BindNamedParameters(parameters);

            // Bind positional parameters per parameter set
            // To do so, sort parameters of set by position, ignore bound parameters and set the first unbound position
            // Note: if we don't know the active parameter set, yet, we will bind it by Default, this is PS behavior
            // Binding will also restrict the candidate set and check for ambiguity 
            parameters = BindPositionalParameters(parameters, ActiveOrDefaultParameterSet);

            // Bind dynamic parameters based on what's already bound.
            // TODO: this is also the place to support ShouldProcess
            parameters = BindDynamicParameters(parameters);

            // Make sure that there are no parameters that couldn't be bound
            ValidateAllParametersBound(parameters);

            // There might be parameter sets with parameters that are still unbound but will be set by pipeline.
            // If not, and if we have an (active or default) parameter set that is still a candidate, then get the
            // missing parameters.
            if (!HasParameterSetsWithUnboundMandatoryPipelineParameters() &&
                _candidateParameterSets.Contains(ActiveOrDefaultParameterSet))
            {
                HandleMissingMandatoryParameters(ActiveOrDefaultParameterSet, false, true);
            }

            // We finished binding parameters without pipeline. Therefore we can restrict the candidate set to those
            // sets that have all mandatory parameters set or are able to set them by pipeline
            RestrictCandidatesByBoundParameter(false);

            // Check if we have unbound parameters that can be set by pipeline. If not and we can already do
            // our final choice (and throw an error on problems)
            if (!HasUnboundPipelineParameters())
            {
                DoFinalChoiceOfParameterSet();
            }

            // Back up the bound parameters
            BackupCommandLineParameterValues();

            // For the beginning phase: Tell the cmdlet which parameter set is likely to be used (if we know it)
            // If there is only one candidate, use it at least temporarily. Otherwise the active or default
            SetCmdletParameterSetName(_candidateParameterSets.Count == 1 ? _candidateParameterSets[0]
                                                                         : ActiveOrDefaultParameterSet);
        }
Ejemplo n.º 6
0
        public void BindingParameterAlias()
        {
            var parameters = new CommandParameterCollection {
                { "Path", "a path" }
            };

            _binder.BindCommandLineParameters(parameters);

            Assert.AreEqual("a path", _cmdlet.FilePath.ToString());
        }
Ejemplo n.º 7
0
        public void BindingFieldAlias()
        {
            var parameters = new CommandParameterCollection {
                { "fn", "John" },
                { "Variable", "foo" } // mandatory
            };

            _binder.BindCommandLineParameters(parameters);

            Assert.AreEqual("John", _cmdlet.Name);
        }
Ejemplo n.º 8
0
        public void BindingParameterByPipeline()
        {
            var parameters = new CommandParameterCollection {
                { "Variable", "foo" } // mandatory
            };

            _binder.BindCommandLineParameters(parameters);
            _binder.BindPipelineParameters(10, true);

            Assert.AreEqual("10", _cmdlet.InputObject.ToString());
        }
Ejemplo n.º 9
0
        public void BindingCombinationNonDefaultSet()
        {
            var parameters = new CommandParameterCollection {
                { "Variable", "a" },
                { "Recurse", null }
            };

            _binder.BindCommandLineParameters(parameters);

            Assert.AreEqual("a", _cmdlet.Variable);
            Assert.IsTrue(_cmdlet.Recurse.ToBool());
        }
Ejemplo n.º 10
0
        public JobInvocationInfo(JobDefinition definition, Dictionary <string, object> parameters)
        {
            this._name       = string.Empty;
            this._instanceId = Guid.NewGuid();
            this._definition = definition;
            CommandParameterCollection item = ConvertDictionaryToParameterCollection(parameters);

            if (item != null)
            {
                this.Parameters.Add(item);
            }
        }
Ejemplo n.º 11
0
        public void BindingCombinationNonDefaultSet()
        {
            var parameters = new CommandParameterCollection {
                { "Variable", "a" },
                { "Recurse", null }
            };

            _binder.BindCommandLineParameters(parameters);

            Assert.AreEqual("a", _cmdlet.Variable);
            Assert.IsTrue(_cmdlet.Recurse.ToBool());
        }
Ejemplo n.º 12
0
        public void BindingNonSwitch()
        {
            var parameters = new CommandParameterCollection {
                { "Name", "John" },
                { "Variable", "foo" }
            };

            _binder.BindCommandLineParameters(parameters);

            Assert.AreEqual("John", _cmdlet.Name);
            Assert.IsFalse(_cmdlet.Recurse.ToBool());
        }
Ejemplo n.º 13
0
 public IEnumerable <PSObject> RunCmdlet(string command, CommandParameterCollection parameters, bool throwExceptionOnError = true)
 {
     if (this.cmdletValidator.Validate(command, parameters))
     {
         return(this.ExecuteCmdlet(command, parameters, throwExceptionOnError));
     }
     if (throwExceptionOnError)
     {
         throw new CmdletExecutionException(string.Format("Command passed {0} failed validation", command));
     }
     return(new List <PSObject>());
 }
Ejemplo n.º 14
0
        public void BindingParameterSetSelectionDoubleShouldFail()
        {
            var parameters = new CommandParameterCollection {
                { "Variable", "test" },
                { "FilePath", "a path" }
            };

            Assert.Throws(typeof(ParameterBindingException), delegate()
            {
                _binder.BindCommandLineParameters(parameters);
            });
        }
Ejemplo n.º 15
0
        public void BindingParameterTwiceShouldFail()
        {
            var parameters = new CommandParameterCollection {
                { "Variable", "foo" },
                { "Variable", "bar" }
            };

            Assert.Throws(typeof(ParameterBindingException), delegate()
            {
                _binder.BindCommandLineParameters(parameters);
            });
        }
Ejemplo n.º 16
0
        private Job StartJobCommand(System.Management.Automation.PowerShell powerShell)
        {
            Job job = null;

            // Use PowerShell Start-Job cmdlet to run job.
            powerShell.AddCommand("Start-Job");

            powerShell.AddParameter("Name", _jobDefinition.Name);

            // Add job parameters from the JobInvocationInfo object.
            CommandParameterCollection parameters = _jobDefinition.InvocationInfo.Parameters[0];

            foreach (CommandParameter parameter in parameters)
            {
                switch (parameter.Name)
                {
                case "ScriptBlock":
                    powerShell.AddParameter("ScriptBlock", parameter.Value as ScriptBlock);
                    break;

                case "FilePath":
                    powerShell.AddParameter("FilePath", parameter.Value as string);
                    break;

                case "RunAs32":
                    powerShell.AddParameter("RunAs32", (bool)parameter.Value);
                    break;

                case "Authentication":
                    powerShell.AddParameter("Authentication", (AuthenticationMechanism)parameter.Value);
                    break;

                case "InitializationScript":
                    powerShell.AddParameter("InitializationScript", parameter.Value as ScriptBlock);
                    break;

                case "ArgumentList":
                    powerShell.AddParameter("ArgumentList", parameter.Value as object[]);
                    break;
                }
            }

            // Start the job.
            Collection <PSObject> rtn = powerShell.Invoke();

            if (rtn != null && rtn.Count == 1)
            {
                job = rtn[0].BaseObject as Job;
            }

            return(job);
        }
Ejemplo n.º 17
0
 public Command(string command, bool isScript, bool useLocalScope)
 {
     this._mergeInstructions = new PipelineResultTypes[4];
     this._parameters = new CommandParameterCollection();
     this._command = string.Empty;
     if (command == null)
     {
         throw PSTraceSource.NewArgumentNullException("command");
     }
     this._command = command;
     this._isScript = isScript;
     this._useLocalScope = new bool?(useLocalScope);
 }
Ejemplo n.º 18
0
        private void DeserializeInvocationInfo(SerializationInfo info)
        {
            string str  = info.GetString("InvocationInfo_Command");
            string str1 = info.GetString("InvocationInfo_Name");
            string str2 = info.GetString("InvocationInfo_ModuleName");
            string str3 = info.GetString("InvocationInfo_AdapterTypeName");
            Dictionary <string, object> strs = new Dictionary <string, object>();
            string str4 = info.GetString("InvocationParam_ScriptBlock");

            if (str4 != null)
            {
                strs.Add("ScriptBlock", ScriptBlock.Create(str4));
            }
            string str5 = info.GetString("InvocationParam_FilePath");

            if (!string.IsNullOrEmpty(str5))
            {
                strs.Add("FilePath", str5);
            }
            str4 = info.GetString("InvocationParam_InitScript");
            if (!string.IsNullOrEmpty(str4))
            {
                strs.Add("InitializationScript", ScriptBlock.Create(str4));
            }
            bool flag = info.GetBoolean("InvocationParam_RunAs32");

            strs.Add("RunAs32", flag);
            AuthenticationMechanism value = (AuthenticationMechanism)info.GetValue("InvocationParam_Authentication", typeof(AuthenticationMechanism));

            strs.Add("Authentication", value);
            object[] objArray = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[]));
            if (objArray != null)
            {
                strs.Add("ArgumentList", objArray);
            }
            JobDefinition jobDefinition = new JobDefinition(null, str, str1);

            jobDefinition.ModuleName = str2;
            jobDefinition.JobSourceAdapterTypeName = str3;
            CommandParameterCollection commandParameterCollection = new CommandParameterCollection();

            foreach (KeyValuePair <string, object> keyValuePair in strs)
            {
                CommandParameter commandParameter = new CommandParameter(keyValuePair.Key, keyValuePair.Value);
                commandParameterCollection.Add(commandParameter);
            }
            base.Definition = jobDefinition;
            base.Name       = str1;
            base.Command    = str;
            base.Parameters.Add(commandParameterCollection);
        }
        /// <summary>
        /// Creates a new migration endpoint in Exchange Online.
        /// </summary>
        /// <param name="entity">An instance of <see cref="EnvironmentEntity"/> that represents the new migration endpoint.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="entity"/> is null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="entity"/> is null.
        /// </exception>
        public async Task CreateMigrationEndpointAsync(EnvironmentEntity entity)
        {
            Command command;
            CommandParameterCollection parameters;
            PSCredential        credential;
            PSCredential        onPermiseCredential;
            Uri                 connectionUri;
            WSManConnectionInfo connectionInfo;
            string              onPermisePassword;

            entity.AssertNotNull(nameof(entity));

            try
            {
                credential = new PSCredential(
                    service.Configuration.ExchangeOnlineUsername,
                    service.Configuration.ExchangeOnlinePassword.ToSecureString());

                onPermisePassword = await service.Vault.GetAsync(entity.Password);

                onPermiseCredential = new PSCredential(entity.Username, onPermisePassword.ToSecureString());

                connectionUri  = new Uri($"{MigrationConstants.ExchangeOnlineEndpoint}{entity.Organization}");
                connectionInfo = GetConnectionInfo(connectionUri, MigrationConstants.SchemaUri, credential);

                command = new Command("New-MigrationEndpoint");

                parameters = new CommandParameterCollection
                {
                    { "Autodiscover" },
                    { "Credentials", onPermiseCredential },
                    { "EmailAddress", entity.Username },
                    { "ExchangeRemoteMove" },
                    { "Name", entity.Name }
                };

                using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
                {
                    scriptManager.InvokeCommand(runspace, command, parameters);
                }
            }
            finally
            {
                command             = null;
                connectionInfo      = null;
                connectionUri       = null;
                credential          = null;
                onPermiseCredential = null;
                parameters          = null;
            }
        }
Ejemplo n.º 20
0
        public void BindingCombinationAllSet(string mandatory)
        {
            var parameters = new CommandParameterCollection {
                { "Name", "John" },
                { "Recurse", null },
                { mandatory, "foo" } // chooses the parameter set
            };

            _binder.BindCommandLineParameters(parameters);

            // as the values are in both sets, it should be always set
            Assert.AreEqual("John", _cmdlet.Name);
            Assert.IsTrue(_cmdlet.Recurse.ToBool());
        }
Ejemplo n.º 21
0
        private static CommandParameterCollection ConvertDictionaryToParameterCollection(IEnumerable <KeyValuePair <string, object> > parameters)
        {
            if (parameters == null)
            {
                return(null);
            }
            CommandParameterCollection parameters2 = new CommandParameterCollection();

            foreach (CommandParameter parameter in from param in parameters select new CommandParameter(param.Key, param.Value))
            {
                parameters2.Add(parameter);
            }
            return(parameters2);
        }
Ejemplo n.º 22
0
        public void BindingParameterByPositionAfterSetSelection()
        {
            var varname    = "foo";
            var parameters = new CommandParameterCollection {
                { "ConstVar", null }, // switch parameter, should select "Variable" set
                { null, varname }
            };

            _binder.BindCommandLineParameters(parameters);

            Assert.IsTrue(_cmdlet.ConstVar.ToBool());
            Assert.AreEqual(varname, _cmdlet.Variable);
            Assert.AreEqual("Variable", _cmdlet.ParameterSetName);
        }
Ejemplo n.º 23
0
        public void BindingParameterByPositionSelectsDefaultParameterSetIncomplete()
        {
            var name       = "foo";
            var parameters = new CommandParameterCollection {
                { null, name }
            };

            var ex = Assert.Throws(typeof(ParameterBindingException), delegate()
            {
                _binder.BindCommandLineParameters(parameters);
            });

            StringAssert.Contains("FilePath", ex.Message); // should complain that no "FilePath" was provided
        }
Ejemplo n.º 24
0
        public void BindingCombinationAllSet(string mandatory)
        {
            var parameters = new CommandParameterCollection {
                { "Name", "John" },
                { "Recurse", null },
                { mandatory, "foo" } // chooses the parameter set
            };

            _binder.BindCommandLineParameters(parameters);

            // as the values are in both sets, it should be always set
            Assert.AreEqual("John", _cmdlet.Name);
            Assert.IsTrue(_cmdlet.Recurse.ToBool());
        }
Ejemplo n.º 25
0
        public void ThrowExceptionWhenParameterIsNullAndDataTypeIsNotSetInStoredProcedure()
        {
            var parameters = new CommandParameterCollection
            {
                { "@Param1", 1 },
                { "@Param2", null }
            };

            using (SqlServerTestHelper helper = CreateHelper((string)null))
            {
                QueryProvider provider = CreateQueryProvider(helper.Connection);
                Action        executeStoredProcedure = () => provider.ExecuteStoredProcedure <int>("NoProcedure", parameters);
                executeStoredProcedure.Should().Throw <ArgumentException>().WithMessage("*@Param2*");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Utility function to turn a dictionary of name/value pairs into a parameter collection
        /// </summary>
        /// <param name="parameters">The dictionary to convert</param>
        /// <returns>The converted collection</returns>
        private static CommandParameterCollection ConvertDictionaryToParameterCollection(IEnumerable <KeyValuePair <string, object> > parameters)
        {
            if (parameters == null)
            {
                return(null);
            }
            CommandParameterCollection paramCollection = new CommandParameterCollection();

            foreach (CommandParameter paramItem in
                     parameters.Select(param => new CommandParameter(param.Key, param.Value)))
            {
                paramCollection.Add(paramItem);
            }
            return(paramCollection);
        }
Ejemplo n.º 27
0
        public void BindingParameterByPositionSelectsDefaultParameterSet()
        {
            var name       = "foo";
            var path       = "a path";
            var parameters = new CommandParameterCollection {
                { null, name },
                { null, path }
            };

            _binder.BindCommandLineParameters(parameters);

            Assert.AreEqual(path, _cmdlet.FilePath);
            Assert.AreEqual(name, _cmdlet.Name);
            Assert.AreEqual("File", _cmdlet.ParameterSetName);
        }
Ejemplo n.º 28
0
        private void BindNamedParameters(CommandParameterCollection parameters)
        {
            var namedParameters = from parameter in parameters
                                  where !String.IsNullOrEmpty(parameter.Name)
                                  select parameter;

            foreach (var curParam in namedParameters)
            {
                string curName = curParam.Name;

                // try to get the parameter from any set. throws an error if the name is ambiguous or doesn't exist
                var paramInfo = _cmdletInfo.LookupParameter(curName);
                BindParameter(paramInfo, curParam.Value, true);
            }
        }
        /// <summary>
        /// Starts the migration batch in Exchange Online.
        /// </summary>
        /// <param name="entity">An instance of <see cref="MigrationBatchEntity"/> that represents the migration batch to start.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="entity"/> is null.
        /// </exception>
        public async Task MigrationBatchStartAsync(MigrationBatchEntity entity)
        {
            Command command;
            CommandParameterCollection parameters;
            EnvironmentEntity          environment;
            PSCredential        credential;
            Uri                 connectionUri;
            WSManConnectionInfo connectionInfo;

            entity.AssertNotNull(nameof(entity));

            try
            {
                credential = new PSCredential(
                    service.Configuration.ExchangeOnlineUsername,
                    service.Configuration.ExchangeOnlinePassword.ToSecureString());

                environment = await service.Storage.GetEntityAsync <EnvironmentEntity>(
                    MigrationConstants.EnvironmentTableName,
                    entity.CustomerId,
                    entity.PartitionKey);

                connectionUri  = new Uri($"{MigrationConstants.ExchangeOnlineEndpoint}{environment.Organization}");
                connectionInfo = GetConnectionInfo(connectionUri, MigrationConstants.SchemaUri, credential);

                command = new Command("Start-MigrationBatch");

                parameters = new CommandParameterCollection
                {
                    { "Identity", entity.Name }
                };

                using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
                {
                    scriptManager.InvokeCommand(runspace, command, parameters);
                }

                entity.Started = true;
                await service.Storage.WriteToTableAsync(MigrationConstants.MigrationBatchTable, entity);
            }
            finally
            {
                connectionInfo = null;
                connectionUri  = null;
                credential     = null;
                parameters     = null;
            }
        }
Ejemplo n.º 30
0
        public void ToNativeCommandShouldReturnCorrectNativeCommand(GetProcessCommand command)
        {
            // Fixture setup
            var expectedParameters = new CommandParameterCollection()
            {
                new CommandParameter("ComputerName", command.ComputerName)
            };

            // Exercise system
            var nativeCommand = command.ToNativeCommand();

            // Verify outcome
            nativeCommand.Should().NotBeNull();
            nativeCommand.CommandText.Should().Be(command.Name);
            nativeCommand.Parameters.Should().BeEquivalentTo(expectedParameters);
        }
Ejemplo n.º 31
0
        public void ExecuteUpdateQuery()
        {
            using (SqlServerTestHelper helper = CreateHelper(CreateTable_TestTable))
            {
                var query      = $"UPDATE {Table_TestTable} SET Number = @Number WHERE Id >= @Id";
                var parameters = new CommandParameterCollection
                {
                    { "@Id", 2 },
                    { "@Number", 666 }
                };

                QueryProvider provider = CreateQueryProvider(helper.Connection);
                int           result   = provider.ExecuteNonQuery(query, parameters);
                result.Should().Be(2); // Updated 2 rows.
            }
        }
Ejemplo n.º 32
0
        public void ExecuteInsertQuery()
        {
            using (SqlServerTestHelper helper = CreateHelper(CreateTable_TestTable))
            {
                var query      = $"INSERT INTO {Table_TestTable} (Id, Number, Description) VALUES (@Id, @Number, @Description)";
                var parameters = new CommandParameterCollection
                {
                    { "@Id", 6 },
                    { "@Number", 666 },
                    { "@Description", "Sed ac lobortis magna." }
                };

                QueryProvider provider = CreateQueryProvider(helper.Connection);
                int           result   = provider.ExecuteNonQuery(query, parameters);
                result.Should().Be(1); // Inserted 1 row.
            }
        }
Ejemplo n.º 33
0
        public void ReturnCorrectValueFromSelectRowStoredProcedure()
        {
            using (SqlServerTestHelper helper = CreateHelper(CreateProcedure_RowResultWithMultipleValues))
            {
                var parameters = new CommandParameterCollection
                {
                    { "@Id", 1 },
                    { "@Number", 10 },
                    { "@Description", "Lorem ipsum" }
                };

                QueryProvider provider = CreateQueryProvider(helper.Connection);
                TestItem      result   = provider.ExecuteStoredProcedure <TestItem>(Procedure_RowResultWithMultipleValues, parameters);

                result.Should().Be(new TestItem(1, 10, "Lorem ipsum"));
            }
        }
Ejemplo n.º 34
0
		private void DeserializeInvocationInfo(SerializationInfo info)
		{
			string str = info.GetString("InvocationInfo_Command");
			string str1 = info.GetString("InvocationInfo_Name");
			string str2 = info.GetString("InvocationInfo_ModuleName");
			string str3 = info.GetString("InvocationInfo_AdapterTypeName");
			Dictionary<string, object> strs = new Dictionary<string, object>();
			string str4 = info.GetString("InvocationParam_ScriptBlock");
			if (str4 != null)
			{
				strs.Add("ScriptBlock", ScriptBlock.Create(str4));
			}
			string str5 = info.GetString("InvocationParam_FilePath");
			if (!string.IsNullOrEmpty(str5))
			{
				strs.Add("FilePath", str5);
			}
			str4 = info.GetString("InvocationParam_InitScript");
			if (!string.IsNullOrEmpty(str4))
			{
				strs.Add("InitializationScript", ScriptBlock.Create(str4));
			}
			bool flag = info.GetBoolean("InvocationParam_RunAs32");
			strs.Add("RunAs32", flag);
			AuthenticationMechanism value = (AuthenticationMechanism)info.GetValue("InvocationParam_Authentication", typeof(AuthenticationMechanism));
			strs.Add("Authentication", value);
			object[] objArray = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[]));
			if (objArray != null)
			{
				strs.Add("ArgumentList", objArray);
			}
			JobDefinition jobDefinition = new JobDefinition(null, str, str1);
			jobDefinition.ModuleName = str2;
			jobDefinition.JobSourceAdapterTypeName = str3;
			CommandParameterCollection commandParameterCollection = new CommandParameterCollection();
			foreach (KeyValuePair<string, object> keyValuePair in strs)
			{
				CommandParameter commandParameter = new CommandParameter(keyValuePair.Key, keyValuePair.Value);
				commandParameterCollection.Add(commandParameter);
			}
			base.Definition = jobDefinition;
			base.Name = str1;
			base.Command = str;
			base.Parameters.Add(commandParameterCollection);
		}
Ejemplo n.º 35
0
 internal Command(Command command)
 {
     this._mergeInstructions = new PipelineResultTypes[4];
     this._parameters = new CommandParameterCollection();
     this._command = string.Empty;
     this._isScript = command._isScript;
     this._useLocalScope = command._useLocalScope;
     this._command = command._command;
     this._mergeInstructions = command._mergeInstructions;
     this._mergeMyResult = command._mergeMyResult;
     this._mergeToResult = command._mergeToResult;
     this._mergeUnclaimedPreviousCommandResults = command._mergeUnclaimedPreviousCommandResults;
     this.isEndOfStatement = command.isEndOfStatement;
     foreach (CommandParameter parameter in command.Parameters)
     {
         this.Parameters.Add(new CommandParameter(parameter.Name, parameter.Value));
     }
 }
Ejemplo n.º 36
0
        private void ValidateAllParametersBound(CommandParameterCollection parameters)
        {
            if (parameters.Count < 1)
            {
                return;
            }
            var curParam = parameters[0];

            if (!String.IsNullOrEmpty(curParam.Name))
            {
                var msg = String.Format("No parameter was found that matches the name or alias '{0}'.", curParam.Name);
                throw new ParameterBindingException(msg, "ParameterNotFound");
            }
            else
            {
                var msg = String.Format("Positional parameter not found for provided argument '{0}'", curParam.Value);
                throw new ParameterBindingException(msg, "PositionalParameterNotFound");
            }
        }
Ejemplo n.º 37
0
        public void BindCommandLineParameters(CommandParameterCollection parameters)
        {
            // TODO: as soon as we support cmdlet functions, we should think about using the CmdletParameterBinder
            // or at least extract common functionality
            var unboundArguments = new List<CommandParameter>(parameters);
            var unboundScriptParameters = new List<ParameterAst>(_scriptParameters);

            // bind arguments by name
            BindArgumentsByName(unboundScriptParameters, unboundArguments);

            // then we set all parameters by position
            BindArgumentsByPosition(unboundScriptParameters, unboundArguments);

            // parameters that are still unbound should get their default value
            SetUnboundParametersToDefaultValue(unboundScriptParameters);

            // finally we will set the $Args variable with all values that are left
            SetArgsVariableFromUnboundArgs(unboundArguments);
        }
Ejemplo n.º 38
0
        public void BindCommandLineParameters(CommandParameterCollection parameters)
        {
            // TODO: as soon as we support cmdlet functions, we should think about using the CmdletParameterBinder
            // or at least extract common functionality
            var unboundArguments        = new List <CommandParameter>(parameters);
            var unboundScriptParameters = new List <ParameterAst>(_scriptParameters);

            // bind arguments by name
            BindArgumentsByName(unboundScriptParameters, unboundArguments);

            // then we set all parameters by position
            BindArgumentsByPosition(unboundScriptParameters, unboundArguments);

            // parameters that are still unbound should get their default value
            SetUnboundParametersToDefaultValue(unboundScriptParameters);

            // finally we will set the $Args variable with all values that are left
            SetArgsVariableFromUnboundArgs(unboundArguments);
        }
Ejemplo n.º 39
0
        private void BindPositionalParameters(CommandParameterCollection parameters, CommandParameterSetInfo parameterSet)
        {
            var parametersWithoutName = from param in parameters
                                        where String.IsNullOrEmpty(param.Name)
                                        select param;

            if (parameterSet == null)
            {
                if (parametersWithoutName.Any())
                {
                    ThrowAmbiguousParameterSetException();
                }
                return;
            }
            var positionals = (from param in parameterSet.Parameters
                               where param.Position >= 0
                               orderby param.Position ascending
                               select param).ToList();
            int i = 0;

            foreach (var curParam in parametersWithoutName)
            {
                bool bound = false;
                while (!bound)
                {
                    if (i < positionals.Count)
                    {
                        var affectedParam = positionals[i];
                        if (!_boundParameters.Contains(affectedParam.MemberInfo))
                        {
                            BindParameter(affectedParam, curParam.Value, true);
                            bound = true;
                        }
                        i++;
                    }
                    else
                    {
                        var msg = String.Format("Positional parameter not found for provided argument '{0}'", curParam.Value);
                        throw new ParameterBindingException(msg, "PositionalParameterNotFound");
                    }
                }
            }
        }
Ejemplo n.º 40
0
 public JobInvocationInfo(JobDefinition definition, IEnumerable <Dictionary <string, object> > parameterCollectionList)
 {
     this._name       = string.Empty;
     this._instanceId = Guid.NewGuid();
     this._definition = definition;
     if (parameterCollectionList != null)
     {
         foreach (Dictionary <string, object> dictionary in parameterCollectionList)
         {
             if (dictionary != null)
             {
                 CommandParameterCollection item = ConvertDictionaryToParameterCollection(dictionary);
                 if (item != null)
                 {
                     this.Parameters.Add(item);
                 }
             }
         }
     }
 }
Ejemplo n.º 41
0
        public void ReturnCorrectValueFromStoredProcedure()
        {
            using (SqlServerTestHelper helper = CreateHelper(CreateProcedure_ScalarResult))
            {
                const int param1   = 11;
                const int param2   = 22;
                const int expected = 33;

                var parameters = new CommandParameterCollection
                {
                    { "@Param1", param1 },
                    { "@Param2", param2 }
                };

                QueryProvider provider = CreateQueryProvider(helper.Connection);
                int           result   = provider.ExecuteStoredProcedure <int>(Procedure_ScalarResult, parameters);

                result.Should().Be(expected);
            }
        }
 public JobInvocationInfo(JobDefinition definition, IEnumerable <Dictionary <string, object> > parameterCollectionList)
 {
     _definition = definition;
     if (parameterCollectionList == null)
     {
         return;
     }
     foreach (var parameterCollection in parameterCollectionList)
     {
         if (parameterCollection == null)
         {
             continue;
         }
         CommandParameterCollection convertedCollection = ConvertDictionaryToParameterCollection(parameterCollection);
         if (convertedCollection != null)
         {
             Parameters.Add(convertedCollection);
         }
     }
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Binds the parameters from the command line to the command.
        /// </summary>
        /// <remarks>
        /// All abount Cmdlet parameters: http://msdn2.microsoft.com/en-us/library/ms714433(VS.85).aspx
        /// About the lifecycle: http://msdn.microsoft.com/en-us/library/ms714429(v=vs.85).aspx
        /// </remarks>
        public void BindCommandLineParameters(CommandParameterCollection parameters)
        {
            // How command line parameters are bound:
            // 1. Bind all named parameters, fail if some name is bound twice
            BindNamedParameters(parameters);

            // 2. Check if there is an "active" parameter set, yet.
            //    If there is more than one "active" parameter set, fail with ambigous error
            CheckForActiveParameterSet();

            // 3. Bind positional parameters per parameter set
            //    To do so, sort parameters of set by position, ignore bound parameters and set the first unbound position
            //    Note: if we don't know the active parameter set, yet, we will bind it by Default, this is PS behavior
            BindPositionalParameters(parameters, ActiveOrDefaultParameterSet);

            // 4. This would be the place for common parameters, support of ShouldProcess and dynamic parameters
            // TODO: care about "common" parameters and dynamic parameters

            // 5. Check if there is an "active" parameter set, yet, and fail if there are more than one
            CheckForActiveParameterSet();

            // 6. For either the (active or default) parameter set: Gather missing mandatory parameters by UI
            // 7. Check if (active or default) parameter set has unbound mandatory parameters and fail if so
            //    But not pipeline related parameters, they might get passed later on
            HandleMissingMandatoryParameters(ActiveOrDefaultParameterSet, false, true);

            // 8. Check for an active parameter set. If the default set had unique mandatory parameters, we might
            //    know that the default set is the active set
            CheckForActiveParameterSet();

            // 9. Define "candidate" parameter sets: All that have mandatory parameters set, ignoring pipeline related
            //    If one set is already active, this should be the only candidate set
            // NOTE: makes sense if there has been no unique parameter, but multiple sets have their mandatories set
            _candidateParameterSets = GetCandidateParameterSets(false);

            // 10. Back up the bound parameters
            BackupCommandLineParameterValues();

            // 11. For the beginning phase: Tell the cmdlet which parameter set is likely to be used (if we know it)
            ChooseParameterSet(ActiveOrDefaultParameterSet);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Binds the parameters from the command line to the command.
        /// </summary>
        /// <remarks>
        /// All abount Cmdlet parameters: http://msdn2.microsoft.com/en-us/library/ms714433(VS.85).aspx
        /// About the lifecycle: http://msdn.microsoft.com/en-us/library/ms714429(v=vs.85).aspx
        /// </remarks>
        public void BindCommandLineParameters(CommandParameterCollection parameters)
        {
            // How command line parameters are bound:
            // 1. Bind all named parameters, fail if some name is bound twice
            BindNamedParameters(parameters);

            // 2. Check if there is an "active" parameter set, yet.
            //    If there is more than one "active" parameter set, fail with ambigous error
            CheckForActiveParameterSet();

            // 3. Bind positional parameters per parameter set
            //    To do so, sort parameters of set by position, ignore bound parameters and set the first unbound position
            //    Note: if we don't know the active parameter set, yet, we will bind it by Default, this is PS behavior
            BindPositionalParameters(parameters, ActiveOrDefaultParameterSet);

            // 4. This would be the place for common parameters, support of ShouldProcess and dynamic parameters
            // TODO: care about "common" parameters and dynamic parameters

            // 5. Check if there is an "active" parameter set, yet, and fail if there are more than one
            CheckForActiveParameterSet();

            // 6. For either the (active or default) parameter set: Gather missing mandatory parameters by UI
            // 7. Check if (active or default) parameter set has unbound mandatory parameters and fail if so
            //    But not pipeline related parameters, they might get passed later on
            HandleMissingMandatoryParameters(ActiveOrDefaultParameterSet, false, true);

            // 8. Check for an active parameter set. If the default set had unique mandatory parameters, we might
            //    know that the default set is the active set
            CheckForActiveParameterSet();

            // 9. Define "candidate" parameter sets: All that have mandatory parameters set, ignoring pipeline related
            //    If one set is already active, this should be the only candidate set
            // NOTE: makes sense if there has been no unique parameter, but multiple sets have their mandatories set
            _candidateParameterSets = GetCandidateParameterSets(false);

            // 10. Back up the bound parameters
            BackupCommandLineParameterValues();

            // 11. For the beginning phase: Tell the cmdlet which parameter set is likely to be used (if we know it)
            ChooseParameterSet(ActiveOrDefaultParameterSet);
        }
Ejemplo n.º 45
0
        private CommandParameterCollection BindNamedParameters(CommandParameterCollection parameters)
        {
            var namedParameters = from parameter in parameters
                                  where !String.IsNullOrEmpty(parameter.Name)
                                  select parameter;
            var parametersLeft = new CommandParameterCollection(parameters);

            foreach (var curParam in namedParameters)
            {
                string curName = curParam.Name;

                // try to get the parameter from any set. throws an error if the name is ambiguous or doesn't exist
                var paramInfo = _cmdletInfo.LookupParameter(curName);
                if (paramInfo != null)
                {
                    BindParameter(paramInfo, curParam.Value, true);
                    parametersLeft.Remove(curParam);
                }
            }
            return(parametersLeft);
        }
Ejemplo n.º 46
0
        private void DeserializeInvocationInfo(SerializationInfo info)
        {
            string command = info.GetString("InvocationInfo_Command");
            string name = info.GetString("InvocationInfo_Name");
            string moduleName = info.GetString("InvocationInfo_ModuleName");
            string adapterTypeName = info.GetString("InvocationInfo_AdapterTypeName");

            //
            // Parameters
            Dictionary<string, object> parameters = new Dictionary<string, object>();

            // ScriptBlock
            string script = info.GetString("InvocationParam_ScriptBlock");
            if (script != null)
            {
                parameters.Add(ScriptBlockParameter, ScriptBlock.Create(script));
            }

            // FilePath
            string filePath = info.GetString("InvocationParam_FilePath");
            if (!string.IsNullOrEmpty(filePath))
            {
                parameters.Add(FilePathParameter, filePath);
            }

            // InitializationScript
            script = info.GetString("InvocationParam_InitScript");
            if (!string.IsNullOrEmpty(script))
            {
                parameters.Add(InitializationScriptParameter, ScriptBlock.Create(script));
            }

            // RunAs32
            bool runAs32 = info.GetBoolean("InvocationParam_RunAs32");
            parameters.Add(RunAs32Parameter, runAs32);

            // Authentication
            AuthenticationMechanism authentication = (AuthenticationMechanism)info.GetValue("InvocationParam_Authentication",
                typeof(AuthenticationMechanism));
            parameters.Add(AuthenticationParameter, authentication);

            // ArgumentList
            object[] argList = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[]));
            if (argList != null)
            {
                parameters.Add(ArgumentListParameter, argList);
            }

            JobDefinition jobDefinition = new JobDefinition(null, command, name);
            jobDefinition.ModuleName = moduleName;
            jobDefinition.JobSourceAdapterTypeName = adapterTypeName;

            // Convert to JobInvocationParameter collection
            CommandParameterCollection paramCollection = new CommandParameterCollection();
            foreach (KeyValuePair<string, object> param in parameters)
            {
                CommandParameter paramItem = new CommandParameter(param.Key, param.Value);
                paramCollection.Add(paramItem);
            }

            this.Definition = jobDefinition;
            this.Name = name;
            this.Command = command;
            this.Parameters.Add(paramCollection);
        }
Ejemplo n.º 47
0
        private CommandParameterCollection BindDynamicParameters(CommandParameterCollection parameters)
        {
            var dynamicParamsCmdlet = _cmdlet as IDynamicParameters;
            if (dynamicParamsCmdlet == null) // no support for dynamic parameters
            {
                return parameters;
            }
            // get the object with dynamic parameters
            var parameterObject = dynamicParamsCmdlet.GetDynamicParameters();
            if (parameterObject == null)
            {
                return parameters;
            }

            var discovery = new CommandParameterDiscovery(parameterObject.GetType());
            // add the parameters to the cmdletInfo
            _cmdletInfo.AddParametersToAllSets(discovery);
            // as we updated parameter sets, we need to rebuild some cached values
            _activeSet = _activeSet == null ? null : GetParameterSet(_activeSet.Name);
            _defaultSet = _defaultSet == null ? null : GetParameterSet(_defaultSet.Name);
            _candidateParameterSets = (from p in _candidateParameterSets select GetParameterSet(p.Name)).ToList();

            AddBindDestionations(discovery, parameterObject);
            // now try to rebind the parameters
            parameters = BindNamedParameters(parameters);
            return BindPositionalParameters(parameters, ActiveOrDefaultParameterSet);
        }
Ejemplo n.º 48
0
 private void ValidateAllParametersBound(CommandParameterCollection parameters)
 {
     if (parameters.Count < 1)
     {
         return;
     }
     var curParam = parameters[0];
     if (!String.IsNullOrEmpty(curParam.Name))
     {
         var msg = String.Format("No parameter was found that matches the name or alias '{0}'.", curParam.Name);
         throw new ParameterBindingException(msg, "ParameterNotFound");
     }
     else
     {
         var msg = String.Format("Positional parameter not found for provided argument '{0}'", curParam.Value);
         throw new ParameterBindingException(msg, "PositionalParameterNotFound");
     }
 }
Ejemplo n.º 49
0
 private void BindPositionalParameters(CommandParameterCollection parameters, CommandParameterSetInfo parameterSet)
 {
     var parametersWithoutName = from param in parameters
                                     where String.IsNullOrEmpty(param.Name)
                                 select param;
     if (parameterSet == null)
     {
         if (parametersWithoutName.Any())
         {
             throw new ParameterBindingException("The parameter set to be used cannot be resolved.",
                  "AmbiguousParameterSet");
         }
         return;
     }
     var positionals = (from param in parameterSet.Parameters
         where param.Position >= 0
         orderby param.Position ascending
         select param).ToList();
     int i = 0;
     foreach (var curParam in parametersWithoutName)
     {
         if (i < positionals.Count)
         {
             var affectedParam = positionals[i];
             BindParameter(affectedParam, curParam.Value, true);
             i++;
         }
         else
         {
             var msg = String.Format("Positional parameter not found for provided argument '{0}'", curParam.Value);
             throw new ParameterBindingException(msg, "PositionalParameterNotFound");
         }
     }
 }
Ejemplo n.º 50
0
        private void BindNamedParameters(CommandParameterCollection parameters)
        {
            var namedParameters = from parameter in parameters
                                      where !String.IsNullOrEmpty(parameter.Name)
                                  select parameter;

            foreach (var curParam in namedParameters)
            {
                string curName = curParam.Name;

                // try to get the parameter from any set. throws an error if the name is ambiguous or doesn't exist
                var paramInfo = _cmdletInfo.LookupParameter(curName);
                BindParameter(paramInfo, curParam.Value, true);
            }
        }
Ejemplo n.º 51
0
        private CommandParameterCollection BindNamedParameters(CommandParameterCollection parameters)
        {
            var namedParameters = from parameter in parameters
                                  where !String.IsNullOrEmpty(parameter.Name)
                                  select parameter;
            var parametersLeft = new CommandParameterCollection(parameters);
            foreach (var curParam in namedParameters)
            {
                string curName = curParam.Name;

                // try to get the parameter from any set. throws an error if the name is ambiguous or doesn't exist
                var paramInfo = _cmdletInfo.LookupParameter(curName);
                if (paramInfo != null) {
                    BindParameter(paramInfo, curParam.Value, true);
                    parametersLeft.Remove(curParam);
                }
            }
            return parametersLeft;
        }
Ejemplo n.º 52
0
 /// <summary>
 /// Utility function to turn a dictionary of name/value pairs into a parameter collection
 /// </summary>
 /// <param name="parameters">The dictionary to convert</param>
 /// <returns>The converted collection</returns>
 private static CommandParameterCollection ConvertDictionaryToParameterCollection(IEnumerable<KeyValuePair<string, object>> parameters)
 {
     if (parameters == null)
         return null;
     CommandParameterCollection paramCollection = new CommandParameterCollection();
     foreach (CommandParameter paramItem in
         parameters.Select(param => new CommandParameter(param.Key, param.Value)))
     {
         paramCollection.Add(paramItem);
     }
     return paramCollection;
 }
Ejemplo n.º 53
0
 private Command()
 {
     Parameters = new CommandParameterCollection();
     MergeMyResult = PipelineResultTypes.None;
     MergeToResult = PipelineResultTypes.None;
 }
Ejemplo n.º 54
0
        /// <summary>
        /// Create necessary dictionaries for WorkflowManager consumption based on StartParameters.
        /// </summary>
        private void SortStartParameters(DynamicActivity dynamicActivity, CommandParameterCollection parameters)
        {
            bool selfRemoting = dynamicActivity != null && dynamicActivity.Properties.Any(x => x.Name.Equals(Constants.ComputerName, StringComparison.CurrentCultureIgnoreCase));
            bool takesPSPrivateMetadata = dynamicActivity != null && dynamicActivity.Properties.Contains(Constants.PrivateMetadata);
            _jobMetadata.Add(Constants.WorkflowTakesPrivateMetadata, takesPSPrivateMetadata);

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    _tracer.WriteMessage(ClassNameTrace, "SortStartParameters", WorkflowGuidForTraces, this, "Found parameter; {0}; {1}", parameter.Name,
                        parameter.Value == null ? null : parameter.Value.ToString());
                    switch (parameter.Name)
                    {
                        case Constants.ComputerName:
                            if (selfRemoting)
                            {
                                // If we're self-remoting, location becomes the default computer
                                // and the PSComputerNames is passed in as an argument instead
                                // of going to the ubiquitous parameters
                                _location = Constants.DefaultComputerName;
                                string parameterName = dynamicActivity.Properties.First(x => x.Name.Equals(Constants.ComputerName, StringComparison.CurrentCultureIgnoreCase)).Name;
                                _workflowParameters[parameterName] = LanguagePrimitives.ConvertTo<string[]>(parameter.Value);
                            }
                            else
                            {
                                // Set _location before adding parameter.
                                var computer = parameter.Value as string;
                                _location = computer;
                                string[] computerNames = LanguagePrimitives.ConvertTo<string[]>(parameter.Value);
                                _psWorkflowCommonParameters[parameter.Name] = computerNames;
                            }
                            break;
                        case Constants.PrivateMetadata:
                            Hashtable privateData = parameter.Value as Hashtable;
                            if (privateData != null)
                            {
                                IDictionaryEnumerator enumerator = privateData.GetEnumerator();
                                while (enumerator.MoveNext())
                                {
                                    _privateMetadata.Add(enumerator.Key.ToString(), enumerator.Value);
                                }

                                // Make the combined object available within the workflow as well...
                                if (takesPSPrivateMetadata)
                                {
                                    _workflowParameters.Add(parameter.Name, parameter.Value);
                                }
                            }
                            break;

                        case Constants.PSInputCollection:
                            {
                                // Remove the input collection so we can properly pass it to the workflow job
                                object baseObject = parameter.Value is PSObject
                                                        ? ((PSObject)parameter.Value).BaseObject
                                                        : parameter.Value;

                                if (baseObject is PSDataCollection<PSObject>)
                                {
                                    _inputCollection = baseObject as PSDataCollection<PSObject>;
                                }
                                else
                                {
                                    var inputCollection = new PSDataCollection<PSObject>();
                                    var e = LanguagePrimitives.GetEnumerator(baseObject);
                                    if (e != null)
                                    {
                                        while (e.MoveNext())
                                        {
                                            inputCollection.Add(PSObject.AsPSObject(e.Current));
                                        }
                                    }
                                    else
                                    {
                                        inputCollection.Add(PSObject.AsPSObject(parameter.Value));
                                    }
                                    _inputCollection = inputCollection;
                                }
                            }
                            break;

                        case Constants.PSParameterCollection:
                            // Remove this one from the parameter collection...
                            break;
                        case Constants.PSRunningTime:
                        case Constants.PSElapsedTime:
                        case Constants.ConnectionRetryCount:
                        case Constants.ActionRetryCount:
                        case Constants.ConnectionRetryIntervalSec:
                        case Constants.ActionRetryIntervalSec:
                            _psWorkflowCommonParameters.Add(parameter.Name, parameter.Value);
                            break;

                        case Constants.Persist:
                        case Constants.Credential:
                        case Constants.Port:
                        case Constants.UseSSL:
                        case Constants.ConfigurationName:
                        case Constants.ApplicationName:
                        case Constants.ConnectionURI:
                        case Constants.SessionOption:
                        case Constants.Authentication:
                        case Constants.AuthenticationLevel:
                        case Constants.CertificateThumbprint:
                        case Constants.AllowRedirection:
                        case Constants.Verbose:
                        case Constants.Debug:
                        case Constants.ErrorAction:
                        case Constants.WarningAction:
                        case Constants.InformationAction:
                        case Constants.PSWorkflowErrorAction:
                        case Constants.PSSuspendOnError:
                        case Constants.PSSenderInfo:
                        case Constants.ModulePath:
                        case Constants.PSCurrentDirectory:
                            // Note: We don't add ErrorVariable, WarningVariable, OutVariable, or OutBuffer
                            // here because they are interpreted by PowerShell in the function generated over
                            // the workflow definition.
                            _psWorkflowCommonParameters.Add(parameter.Name, parameter.Value);
                            break;
                        default:
                            _workflowParameters.Add(parameter.Name, parameter.Value);
                            break;
                    }
                }
            }

            // Add in the workflow command name...
            _psWorkflowCommonParameters.Add("WorkflowCommandName", _definition.Command);
        }
Ejemplo n.º 55
0
        internal void LoadWorkflow(CommandParameterCollection commandParameterCollection, Activity activity, string xaml)
        {
            _tracer.WriteMessage(ClassNameTrace, "LoadWorkflow", WorkflowGuidForTraces, this, "BEGIN");
            Dbg.Assert(_workflowInstance == null, "LoadWorkflow() should only be called once by the adapter");

            // If activity hasn't been cached, we can't generate it from _definition.
            if (activity == null)
            {
                bool windowsWorkflow;
                activity = DefinitionCache.Instance.GetActivityFromCache(_definition, out windowsWorkflow);

                if (activity == null)
                {
                    // The workflow cannot be run.
                    throw new InvalidOperationException(Resources.ActivityNotCached);
                }
            }

            string workflowXaml;
            string runtimeAssemblyPath;

            if (string.IsNullOrEmpty(xaml))
            {
                workflowXaml = DefinitionCache.Instance.GetWorkflowXaml(_definition);
                runtimeAssemblyPath = DefinitionCache.Instance.GetRuntimeAssemblyPath(_definition);
            }
            else
            {
                workflowXaml = xaml;
                runtimeAssemblyPath = null;
            }

            _location = null;
            SortStartParameters(activity as DynamicActivity, commandParameterCollection);

            // Set location if ComputerName wasn't specified in the parameters.
            if (string.IsNullOrEmpty(_location)) _location = Constants.DefaultComputerName;
            if (_jobMetadata.ContainsKey(Constants.JobMetadataLocation))
                _jobMetadata.Remove(Constants.JobMetadataLocation);
            _jobMetadata.Add(Constants.JobMetadataLocation, _location);

            if (_jobMetadata.ContainsKey(Constants.WorkflowJobCreationContext))
                _jobMetadata.Remove(Constants.WorkflowJobCreationContext);
            _jobMetadata.Add(Constants.WorkflowJobCreationContext, _jobCreationContext);

            PSWorkflowDefinition definition = new PSWorkflowDefinition(activity, workflowXaml, runtimeAssemblyPath, _definition.RequiredAssemblies);
            PSWorkflowContext metadatas = new PSWorkflowContext(_workflowParameters, _psWorkflowCommonParameters, _jobMetadata, _privateMetadata);

            _workflowInstance = _runtime.Configuration.CreatePSWorkflowInstance(definition, metadatas, _inputCollection, this);
            this.ConfigureWorkflowHandlers();

            // Create a WorkflowApplication instance.
            _tracer.WriteMessage(ClassNameTrace, "LoadWorkflow", WorkflowGuidForTraces, this, "Calling instance loader");

            #if DEBUG
            try
            {
                _workflowInstance.CreateInstance();
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf("Cannot create unknown type", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    // Capture environment to help diagnose: MSFT:246456
                    PSObject inputObject = new PSObject();
                    inputObject.Properties.Add(
                        new PSNoteProperty("activity", activity));
                    inputObject.Properties.Add(
                        new PSNoteProperty("workflowXaml", workflowXaml));
                    inputObject.Properties.Add(
                        new PSNoteProperty("runtimeAssemblyPath", runtimeAssemblyPath));
                    inputObject.Properties.Add(
                        new PSNoteProperty("_definition.RequiredAssemblies", _definition.RequiredAssemblies));

                    string tempPath = System.IO.Path.GetTempFileName();
                    System.Management.Automation.PowerShell.Create().AddCommand("Export-CliXml").
                        AddParameter("InputObject", inputObject).
                        AddParameter("Depth", 10).
                        AddParameter("Path", tempPath).Invoke();

                    throw new Exception("Bug MSFT:246456 detected. Please capture " + tempPath + ", open a new issue " +
                        "at https://github.com/PowerShell/PowerShell/issues/new and attach the file.");
                }
                else
                {
                    throw;
                }
            }
            #else
            _workflowInstance.CreateInstance();
            #endif

            InitializeWithWorkflow(_workflowInstance);
            WorkflowInstanceLoaded = true;
            _tracer.WriteMessage(ClassNameTrace, "LoadWorkflow", WorkflowGuidForTraces, this, "END");
        }
Ejemplo n.º 56
0
        private void CreateChildJob(JobInvocationInfo specification, Activity activity, ContainerParentJob newJob, CommandParameterCollection commandParameterCollection, Dictionary<string, object> parameterDictionary, string computerName, string[] computerNames)
        {
            if (!string.IsNullOrEmpty(computerName))
            {
                string[] childTargetComputerList = { computerName };

                // Set the target computer for this child job...
                parameterDictionary[Constants.ComputerName] = childTargetComputerList;
            }

            var childSpecification = new JobInvocationInfo(specification.Definition, parameterDictionary);

            // Job objects will be disposed of on parent job removal.
            var childJob = new PSWorkflowJob(_runtime, childSpecification);
            childJob.JobMetadata = CreateJobMetadata(childJob, newJob.InstanceId, newJob.Id, newJob.Name, newJob.Command, computerNames);

            // Remove the parameter from the collection...
            for (int index = 0; index < commandParameterCollection.Count; index++)
            {
                if (string.Equals(commandParameterCollection[index].Name, Constants.ComputerName, StringComparison.OrdinalIgnoreCase))
                {
                    commandParameterCollection.RemoveAt(index);
                    break;
                }
            }

            if (!string.IsNullOrEmpty(computerName))
            {
                var computerNameParameter = new CommandParameter(Constants.ComputerName, computerName);
                commandParameterCollection.Add(computerNameParameter);
            }

            this.AddJob(childJob);
            childJob.LoadWorkflow(commandParameterCollection, activity, null);
            newJob.AddChildJob(childJob);
            StructuredTracer.ChildWorkflowJobAddition(childJob.InstanceId, newJob.InstanceId);
            Tracer.TraceJob(childJob);
            StructuredTracer.WorkflowJobCreated(newJob.InstanceId, childJob.InstanceId, childJob.WorkflowGuid);
        }
Ejemplo n.º 57
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="definition"></param>
 /// <param name="parameters"></param>
 public JobInvocationInfo(JobDefinition definition, CommandParameterCollection parameters)
 {
     _definition = definition;
     Parameters.Add(parameters ?? new CommandParameterCollection());
 }
Ejemplo n.º 58
0
        private CommandParameterCollection BindPositionalParameters(CommandParameterCollection parameters, CommandParameterSetInfo parameterSet)
        {
            var parametersWithoutName = from param in parameters
                                        where String.IsNullOrEmpty(param.Name)
                                        select param;
            if (parameterSet == null)
            {
                if (parametersWithoutName.Any())
                {
                    ThrowAmbiguousParameterSetException();
                }
                return parameters;
            }
            var positionals = (from param in parameterSet.Parameters
                where param.Position >= 0 && !_boundParameters.Contains(param.MemberInfo)
                orderby param.Position ascending
                select param).ToList();
            int i = 0;
            var parametersLeft = new CommandParameterCollection(parameters);
            foreach (var curParam in parametersWithoutName)
            {
                if (i >= positionals.Count)
                {
                    break; // can't bind it
                }

                BindParameter(positionals[i], curParam.Value, true);
                parametersLeft.Remove(curParam);
                i++;
            }
            return parametersLeft;
        }
Ejemplo n.º 59
0
 internal CommandProcessorBase(CommandInfo cmdInfo)
 {
     CommandInfo = cmdInfo;
     Parameters = new CommandParameterCollection();
 }
Ejemplo n.º 60
0
		private void CreateChildJob(JobInvocationInfo specification, Activity activity, ContainerParentJob newJob, CommandParameterCollection commandParameterCollection, Dictionary<string, object> parameterDictionary, string computerName, string[] computerNames)
		{
			if (!string.IsNullOrEmpty(computerName))
			{
				string[] strArrays = new string[1];
				strArrays[0] = computerName;
				string[] strArrays1 = strArrays;
				parameterDictionary["PSComputerName"] = strArrays1;
			}
			JobInvocationInfo jobInvocationInfo = new JobInvocationInfo(specification.Definition, parameterDictionary);
			PSWorkflowJob pSWorkflowJob = new PSWorkflowJob(this._runtime, jobInvocationInfo);
			pSWorkflowJob.JobMetadata = PSWorkflowJobManager.CreateJobMetadata(pSWorkflowJob, newJob.InstanceId, newJob.Id, newJob.Name, newJob.Command, computerNames);
			int num = 0;
			while (num < commandParameterCollection.Count)
			{
				if (!string.Equals(commandParameterCollection[num].Name, "PSComputerName", StringComparison.OrdinalIgnoreCase))
				{
					num++;
				}
				else
				{
					commandParameterCollection.RemoveAt(num);
					break;
				}
			}
			if (!string.IsNullOrEmpty(computerName))
			{
				CommandParameter commandParameter = new CommandParameter("PSComputerName", computerName);
				commandParameterCollection.Add(commandParameter);
			}
			this.AddJob(pSWorkflowJob);
			pSWorkflowJob.LoadWorkflow(commandParameterCollection, activity, null);
			newJob.AddChildJob(pSWorkflowJob);
			PSWorkflowJobManager.StructuredTracer.ChildWorkflowJobAddition(pSWorkflowJob.InstanceId, newJob.InstanceId);
			PSWorkflowJobManager.Tracer.TraceJob(pSWorkflowJob);
			PSWorkflowJobManager.StructuredTracer.WorkflowJobCreated(newJob.InstanceId, pSWorkflowJob.InstanceId, pSWorkflowJob.WorkflowGuid);
		}