Example #1
0
        /// <summary>
        /// Creates a new job of the appropriate type given by JobDefinition passed in.
        /// </summary>
        /// <param name="specification">JobInvocationInfo defining the command.</param>
        /// <returns>Job2 object of the appropriate type specified by the definition.</returns>
        /// <exception cref="InvalidOperationException">If JobSourceAdapter type specified
        /// in definition is not registered.</exception>
        /// <exception cref="Exception">JobSourceAdapter implementation exception thrown on error.
        /// </exception>
        public Job2 NewJob(JobInvocationInfo specification)
        {
            if (specification == null)
            {
                throw new ArgumentNullException(nameof(specification));
            }

            if (specification.Definition == null)
            {
                throw new ArgumentException(RemotingErrorIdStrings.NewJobSpecificationError, nameof(specification));
            }

            JobSourceAdapter sourceAdapter = GetJobSourceAdapter(specification.Definition);
            Job2             newJob        = null;

#pragma warning disable 56500
            try
            {
                newJob = sourceAdapter.NewJob(specification);
            }
            catch (Exception exception)
            {
                // Since we are calling into 3rd party code
                // catching Exception is allowed. In all
                // other cases the appropriate exception
                // needs to be caught.

                // sourceAdapter.NewJob returned unknown error.
                _tracer.TraceException(exception);
                throw;
            }
#pragma warning restore 56500

            return(newJob);
        }
Example #2
0
        public Job2 NewJob(JobInvocationInfo specification)
        {
            if (specification == null)
            {
                throw new ArgumentNullException("specification");
            }
            if (specification.Definition == null)
            {
                throw new ArgumentException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "NewJobSpecificationError"), "specification");
            }
            JobSourceAdapter jobSourceAdapter = this.GetJobSourceAdapter(specification.Definition);
            Job2             job = null;

            try
            {
                job = jobSourceAdapter.NewJob(specification);
            }
            catch (Exception exception)
            {
                this.Tracer.TraceException(exception);
                CommandProcessorBase.CheckForSevereException(exception);
                throw;
            }
            return(job);
        }
        /// <summary>
        /// Create a new Job2 results instance.
        /// </summary>
        /// <param name="specification">Job specification</param>
        /// <returns>Job2</returns>
        public override Job2 NewJob(JobInvocationInfo specification)
        {
            if (specification == null)
            {
                throw new PSArgumentNullException("specification");
            }

            ScheduledJobDefinition scheduledJobDef = new ScheduledJobDefinition(
                specification, null, null, null);

            return new ScheduledJob(
                specification.Command, 
                specification.Name,
                scheduledJobDef);
        }
        protected override void ProcessRecord()
        {
            // Get full path to source.
            ProviderInfo provider;
            string fullSourcePath = GetResolvedProviderPathFromPSPath(SourcePath, out provider).FirstOrDefault();
            if (string.IsNullOrEmpty(fullSourcePath))
            {
                throw new ArgumentException(SourcePath);
            }

            // Get full path for destination file (which may not exist).
            string fullDestPath = null;
            string destFile = Path.GetFileName(DestinationPath);
            string path = GetResolvedProviderPathFromPSPath(
                Path.GetDirectoryName(DestinationPath), out provider).FirstOrDefault();
            if (path != null)
            {
                fullDestPath = Path.Combine(path, destFile);
            }
            if (string.IsNullOrEmpty(fullDestPath))
            {
                throw new ArgumentException(DestinationPath);
            }

            // Create job source adapter.
            FileCopyJobSourceAdapter jobSourceAdapter = new FileCopyJobSourceAdapter();

            // Create FileCopyJob parameters (source and destination paths).
            Dictionary<string, object> copyJobParameters = new Dictionary<string, object>();
            copyJobParameters.Add(FileCopyJobSourceAdapter.SourcePathProperty, fullSourcePath);
            copyJobParameters.Add(FileCopyJobSourceAdapter.DestinationPathProperty, fullDestPath);

            // Create job specification.
            JobInvocationInfo copyJobSpecification = new JobInvocationInfo(
                new JobDefinition(typeof(FileCopyJobSourceAdapter), string.Empty, Name),
                copyJobParameters);
            copyJobSpecification.Name = Name;

            // Create file copy job from job source adapter and start it.
            Job2 fileCopyJob = jobSourceAdapter.NewJob(copyJobSpecification);
            fileCopyJob.StartJob();

            WriteObject(fileCopyJob);
        }
Example #5
0
        /// <summary>
        /// Construct a PSWorkflowJob.
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="specification">JobInvocationInfo representing the command this job will invoke.</param>
        /// <param name="JobInstanceId"></param>
        /// <param name="creationContext"></param>
        internal PSWorkflowJob(PSWorkflowRuntime runtime, JobInvocationInfo specification, Guid JobInstanceId, Dictionary<string, object> creationContext)
            : base(Validate(specification).Command, specification.Definition.Name, JobInstanceId)
        {
            Dbg.Assert(runtime != null, "runtime must not be null.");
            // If specification is null, ArgumentNullException would be raised from
            // the static validate method.
            StartParameters = specification.Parameters;
            _definition = WorkflowJobDefinition.AsWorkflowJobDefinition(specification.Definition);
            _jobCreationContext = creationContext;

            _runtime = runtime;
            CommonInit();
        }
Example #6
0
        /// <summary>
        /// Construct a PSWorkflowJob.
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="specification">JobInvocationInfo representing the command this job
        /// will invoke.</param>
        internal PSWorkflowJob(PSWorkflowRuntime runtime, JobInvocationInfo specification)
            : base(Validate(specification).Command)
        {
            Dbg.Assert(runtime != null, "runtime must not be null.");
            // If specification is null, ArgumentNullException would be raised from
            // the static validate method.
            StartParameters = specification.Parameters;
            _definition = WorkflowJobDefinition.AsWorkflowJobDefinition(specification.Definition);

            _runtime = runtime;
            CommonInit();
        }
Example #7
0
		public static ContainerParentJob StartWorkflowApplication(PSCmdlet command, string jobName, string workflowGuid, bool startAsync, bool parameterCollectionProcessed, Hashtable[] parameters)
		{
			Guid guid = Guid.NewGuid();
			ImportWorkflowCommand._structuredTracer.BeginStartWorkflowApplication(guid);
			if (!string.IsNullOrEmpty(workflowGuid))
			{
				if (command != null)
				{
					if (parameterCollectionProcessed)
					{
						StringBuilder stringBuilder = new StringBuilder();
						StringBuilder stringBuilder1 = new StringBuilder();
						stringBuilder.Append(string.Concat("commandName ='", command.MyInvocation.MyCommand.Name, "'\n"));
						stringBuilder.Append(string.Concat("jobName ='", jobName, "'\n"));
						stringBuilder.Append(string.Concat("workflowGUID = ", workflowGuid, "\n"));
						stringBuilder.Append(string.Concat("startAsync ", startAsync.ToString(), "\n"));
						if (parameters != null)
						{
							Hashtable[] hashtableArrays = parameters;
							for (int i = 0; i < (int)hashtableArrays.Length; i++)
							{
								Hashtable hashtables = hashtableArrays[i];
								stringBuilder.Append("@{");
								bool flag = true;
								foreach (DictionaryEntry dictionaryEntry in hashtables)
								{
									if (dictionaryEntry.Key == null)
									{
										continue;
									}
									if (flag)
									{
										flag = false;
									}
									else
									{
										stringBuilder.Append("'; ");
									}
									stringBuilder.Append(dictionaryEntry.Key.ToString());
									stringBuilder.Append("='");
									if (dictionaryEntry.Value == null)
									{
										continue;
									}
									if (string.Equals(dictionaryEntry.Key.ToString(), "PSComputerName", StringComparison.OrdinalIgnoreCase))
									{
										stringBuilder1.Append(LanguagePrimitives.ConvertTo<string>(dictionaryEntry.Value));
									}
									stringBuilder.Append(dictionaryEntry.Value.ToString());
								}
								stringBuilder.Append("}\n ");
							}
						}
						ImportWorkflowCommand._structuredTracer.ParameterSplattingWasPerformed(stringBuilder.ToString(), stringBuilder1.ToString());
					}
					JobDefinition definition = DefinitionCache.Instance.GetDefinition(new Guid(workflowGuid));
					if (definition != null)
					{
						List<Dictionary<string, object>> dictionaries = new List<Dictionary<string, object>>();
						if (parameters == null || (int)parameters.Length == 0)
						{
							dictionaries.Add(new Dictionary<string, object>());
						}
						else
						{
							if ((int)parameters.Length != 1 || parameterCollectionProcessed)
							{
								Hashtable[] hashtableArrays1 = parameters;
								for (int j = 0; j < (int)hashtableArrays1.Length; j++)
								{
									Hashtable hashtables1 = hashtableArrays1[j];
									if (hashtables1 != null)
									{
										Dictionary<string, object> parameterDictionary = ImportWorkflowCommand.ConvertToParameterDictionary(hashtables1);
										dictionaries.Add(parameterDictionary);
									}
								}
							}
							else
							{
								Hashtable hashtables2 = parameters[0];
								Dictionary<string, object> strs = new Dictionary<string, object>();
								foreach (object key in parameters[0].Keys)
								{
									strs.Add((string)key, hashtables2[key]);
								}
								dictionaries.Add(strs);
							}
						}
						JobInvocationInfo jobInvocationInfo = new JobInvocationInfo(definition, dictionaries);
						jobInvocationInfo.Name = jobName;
						jobInvocationInfo.Command = command.MyInvocation.InvocationName;
						ImportWorkflowCommand._structuredTracer.BeginCreateNewJob(guid);
						ContainerParentJob containerParentJob = command.JobManager.NewJob(jobInvocationInfo) as ContainerParentJob;
						ImportWorkflowCommand._structuredTracer.EndCreateNewJob(guid);
						PSSQMAPI.IncrementWorkflowExecuted(definition.Command);
						if (!startAsync)
						{
							foreach (PSWorkflowJob childJob in containerParentJob.ChildJobs)
							{
								childJob.SynchronousExecution = true;
							}
							containerParentJob.StartJob();
						}
						else
						{
							if (!PSSessionConfigurationData.IsServerManager)
							{
								foreach (PSWorkflowJob pSWorkflowJob in containerParentJob.ChildJobs)
								{
									pSWorkflowJob.EnableStreamUnloadOnPersistentState();
								}
							}
							containerParentJob.StartJobAsync();
						}
						ImportWorkflowCommand._structuredTracer.EndStartWorkflowApplication(guid);
						ImportWorkflowCommand._structuredTracer.TrackingGuidContainerParentJobCorrelation(guid, containerParentJob.InstanceId);
						return containerParentJob;
					}
					else
					{
						object[] cacheSize = new object[1];
						cacheSize[0] = DefinitionCache.Instance.CacheSize;
						InvalidOperationException invalidOperationException = new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, Resources.InvalidWorkflowDefinitionState, cacheSize));
						ImportWorkflowCommand.Tracer.TraceException(invalidOperationException);
						throw invalidOperationException;
					}
				}
				else
				{
					ArgumentNullException argumentNullException = new ArgumentNullException("command");
					ImportWorkflowCommand.Tracer.TraceException(argumentNullException);
					throw argumentNullException;
				}
			}
			else
			{
				ArgumentNullException argumentNullException1 = new ArgumentNullException("workflowGuid");
				ImportWorkflowCommand.Tracer.TraceException(argumentNullException1);
				throw argumentNullException1;
			}
		}
Example #8
0
 /// <summary>
 /// Create a new job with the specified JobSpecification
 /// </summary>
 /// <param name="specification">specification</param>
 /// <returns>job object</returns>
 public abstract Job2 NewJob(JobInvocationInfo specification);
Example #9
0
		private ScheduledJobDefinition(SerializationInfo info, StreamingContext context)
		{
			this._globalId = Guid.NewGuid();
			this._name = string.Empty;
			this._id = ScheduledJobDefinition.GetCurrentId();
			this._executionHistoryLength = ScheduledJobDefinition.DefaultExecutionHistoryLength;
			this._enabled = true;
			this._triggers = new Dictionary<int, ScheduledJobTrigger>();
			if (info != null)
			{
				this._options = (ScheduledJobOptions)info.GetValue("Options_Member", typeof(ScheduledJobOptions));
				this._globalId = Guid.Parse(info.GetString("GlobalId_Member"));
				this._name = info.GetString("Name_Member");
				this._executionHistoryLength = info.GetInt32("HistoryLength_Member");
				this._enabled = info.GetBoolean("Enabled_Member");
				this._triggers = (Dictionary<int, ScheduledJobTrigger>)info.GetValue("Triggers_Member", typeof(Dictionary<int, ScheduledJobTrigger>));
				this._currentTriggerId = info.GetInt32("CurrentTriggerId_Member");
				this._definitionFilePath = info.GetString("FilePath_Member");
				this._definitionOutputPath = info.GetString("OutputPath_Member");
				object value = info.GetValue("InvocationInfo_Member", typeof(object));
				this._invocationInfo = value as JobInvocationInfo;
				this._options.JobDefinition = this;
				foreach (ScheduledJobTrigger scheduledJobTrigger in this._triggers.Values)
				{
					scheduledJobTrigger.JobDefinition = this;
				}
				this._isDisposed = false;
				return;
			}
			else
			{
				throw new PSArgumentNullException("info");
			}
		}
Example #10
0
		public void UpdateJobInvocationInfo(JobInvocationInfo jobInvocationInfo, bool save)
		{
			this.IsDisposed();
			if (jobInvocationInfo != null)
			{
				this._invocationInfo = jobInvocationInfo;
				this._name = jobInvocationInfo.Name;
				if (save)
				{
					this.SaveToStore();
				}
				return;
			}
			else
			{
				throw new PSArgumentNullException("jobInvocationInfo");
			}
		}
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="invocationInfo">Information to invoke Job</param>
        /// <param name="triggers">ScheduledJobTriggers</param>
        /// <param name="options">ScheduledJobOptions</param>
        /// <param name="credential">Credential</param>
        public ScheduledJobDefinition(
            JobInvocationInfo invocationInfo,
            IEnumerable<ScheduledJobTrigger> triggers,
            ScheduledJobOptions options,
            PSCredential credential)
        {
            if (invocationInfo == null)
            {
                throw new PSArgumentNullException("invocationInfo");
            }

            _name = invocationInfo.Name;
            _invocationInfo = invocationInfo;

            SetTriggers(triggers, false);
            _options = (options != null) ? new ScheduledJobOptions(options) : 
                                           new ScheduledJobOptions();
            _options.JobDefinition = this;

            _credential = credential;
        }
Example #12
0
		internal ContainerParentJob CreateJob(JobInvocationInfo jobInvocationInfo, Activity activity)
		{
			object obj = null;
			if (jobInvocationInfo != null)
			{
				if (jobInvocationInfo.Definition != null)
				{
					if (jobInvocationInfo.Command != null)
					{
						DynamicActivity dynamicActivity = activity as DynamicActivity;
						object[] instanceId = new object[1];
						instanceId[0] = jobInvocationInfo.Definition.InstanceId;
						PSWorkflowJobManager.Tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Creating Workflow job with definition: {0}", instanceId));
						ContainerParentJob containerParentJob = new ContainerParentJob(jobInvocationInfo.Command, jobInvocationInfo.Name, "PSWorkflowJob");
						foreach (CommandParameterCollection commandParameterCollection in commandParameterCollection)
						{
							Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
							IEnumerator<CommandParameter> enumerator = commandParameterCollection.GetEnumerator();
							using (enumerator)
							{
								while (enumerator.MoveNext())
								{
									CommandParameter commandParameter = commandParameterCollection;
									strs.Add(commandParameter.Name, commandParameter.Value);
								}
							}
							string[] strArrays = null;
							bool flag = false;
							if (strs.Count != 0 && strs.TryGetValue("PSComputerName", out obj) && LanguagePrimitives.TryConvertTo<string[]>(obj, CultureInfo.InvariantCulture, out strArrays))
							{
								flag = strArrays != null;
							}
							PSWorkflowJobManager.StructuredTracer.ParentJobCreated(containerParentJob.InstanceId);
							bool flag1 = false;
							if (dynamicActivity != null && dynamicActivity.Properties.Contains("PSComputerName"))
							{
								flag1 = true;
							}
							dynamicActivity = null;
							if (!flag1)
							{
								strs.Remove("PSComputerName");
								if (!flag)
								{
									this.CreateChildJob(jobInvocationInfo, activity, containerParentJob, commandParameterCollection, strs, null, strArrays);
								}
								else
								{
									string[] strArrays1 = strArrays;
									for (int i = 0; i < (int)strArrays1.Length; i++)
									{
										string str = strArrays1[i];
										this.CreateChildJob(jobInvocationInfo, activity, containerParentJob, commandParameterCollection, strs, str, strArrays);
									}
								}
							}
							else
							{
								JobInvocationInfo command = new JobInvocationInfo(jobInvocationInfo.Definition, strs);
								command.Command = containerParentJob.Command;
								if (flag)
								{
									CommandParameter commandParameter1 = new CommandParameter("PSComputerName", strArrays);
									command.Parameters[0].Add(commandParameter1);
								}
								PSWorkflowJob pSWorkflowJob = new PSWorkflowJob(this._runtime, command);
								pSWorkflowJob.JobMetadata = PSWorkflowJobManager.CreateJobMetadata(pSWorkflowJob, containerParentJob.InstanceId, containerParentJob.Id, containerParentJob.Name, containerParentJob.Command, strArrays);
								pSWorkflowJob.LoadWorkflow(commandParameterCollection, activity, null);
								this.AddJob(pSWorkflowJob);
								containerParentJob.AddChildJob(pSWorkflowJob);
								PSWorkflowJobManager.StructuredTracer.ChildWorkflowJobAddition(pSWorkflowJob.InstanceId, containerParentJob.InstanceId);
								PSWorkflowJobManager.StructuredTracer.WorkflowJobCreated(containerParentJob.InstanceId, pSWorkflowJob.InstanceId, pSWorkflowJob.WorkflowGuid);
							}
						}
						PSWorkflowJobManager.StructuredTracer.JobCreationComplete(containerParentJob.InstanceId, jobInvocationInfo.InstanceId);
						PSWorkflowJobManager.Tracer.TraceJob(containerParentJob);
						PSSQMAPI.InitiateWorkflowStateDataTracking(containerParentJob);
						return containerParentJob;
					}
					else
					{
						throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");
					}
				}
				else
				{
					throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");
				}
			}
			else
			{
				throw new ArgumentNullException("jobInvocationInfo");
			}
		}
Example #13
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);
		}
Example #14
0
        /// <summary>
        /// Provide validation of constructor parameter that could cause NullReferenceException.
        /// </summary>
        /// <param name="specification">JobInvocationInfo for construction.</param>
        /// <returns>specification parameter if not null.</returns>
        private static JobInvocationInfo Validate(JobInvocationInfo specification)
        {
            if (specification == null)
            {
                throw new ArgumentNullException("specification");
            }

            if (specification.Definition == null)
            {
                throw new ArgumentException(Resources.UninitializedSpecification, "specification");
            }

            if (string.IsNullOrEmpty(specification.Definition.Command))
            {
                throw new ArgumentException(Resources.UninitializedSpecification, "specification");
            }

            return specification;
        }
Example #15
0
		internal PSWorkflowJob CreateJobInternal(Guid jobInstanceId, Activity workflow, string command, string name, Dictionary<string, object> parameters, string xaml)
		{
			object obj = null;
			PSWorkflowJob pSWorkflowJob;
			if (jobInstanceId != Guid.Empty)
			{
				if (workflow != null)
				{
					if (command != null)
					{
						if (name != null)
						{
							if (!this._wfJobTable.ContainsKey(jobInstanceId))
							{
								lock (this.lockObjects.GetLockObject(jobInstanceId))
								{
									if (!this._wfJobTable.ContainsKey(jobInstanceId))
									{
										JobDefinition jobDefinition = new JobDefinition(typeof(WorkflowJobSourceAdapter), command, name);
										Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
										if (parameters != null)
										{
											foreach (KeyValuePair<string, object> parameter in parameters)
											{
												strs.Add(parameter.Key, parameter.Value);
											}
										}
										string[] strArrays = null;
										bool flag = false;
										if (strs.Count != 0 && strs.TryGetValue("PSComputerName", out obj) && LanguagePrimitives.TryConvertTo<string[]>(obj, CultureInfo.InvariantCulture, out strArrays))
										{
											flag = strArrays != null;
										}
										if (flag)
										{
											if ((int)strArrays.Length <= 1)
											{
												strs.Remove("PSComputerName");
											}
											else
											{
												throw new ArgumentException(Resources.OneComputerNameAllowed);
											}
										}
										JobInvocationInfo jobInvocationInfo = new JobInvocationInfo(jobDefinition, strs);
										jobInvocationInfo.Command = command;
										if (flag)
										{
											CommandParameter commandParameter = new CommandParameter("PSComputerName", strArrays);
											jobInvocationInfo.Parameters[0].Add(commandParameter);
										}
										PSWorkflowJob pSWorkflowJob1 = new PSWorkflowJob(this._runtime, jobInvocationInfo, jobInstanceId);
										pSWorkflowJob1.JobMetadata = PSWorkflowJobManager.CreateJobMetadataWithNoParentDefined(pSWorkflowJob1, strArrays);
										pSWorkflowJob1.LoadWorkflow(jobInvocationInfo.Parameters[0], workflow, xaml);
										this.AddJob(pSWorkflowJob1);
										pSWorkflowJob = pSWorkflowJob1;
									}
									else
									{
										ArgumentException argumentException = new ArgumentException(Resources.DuplicateInstanceId);
										PSWorkflowJobManager.Tracer.TraceException(argumentException);
										throw argumentException;
									}
								}
								return pSWorkflowJob;
							}
							else
							{
								ArgumentException argumentException1 = new ArgumentException(Resources.DuplicateInstanceId);
								PSWorkflowJobManager.Tracer.TraceException(argumentException1);
								throw argumentException1;
							}
						}
						else
						{
							throw new ArgumentNullException("name");
						}
					}
					else
					{
						throw new ArgumentNullException("command");
					}
				}
				else
				{
					throw new ArgumentNullException("workflow");
				}
			}
			else
			{
				throw new ArgumentNullException("jobInstanceId");
			}
		}
        /// <summary>
        /// Updates the JobInvocationInfo object.
        /// </summary>
        /// <param name="jobInvocationInfo">JobInvocationInfo</param>
        /// <param name="save">Save to store</param>
        public void UpdateJobInvocationInfo(
            JobInvocationInfo jobInvocationInfo,
            bool save)
        {
            IsDisposed();

            if (jobInvocationInfo == null)
            {
                throw new PSArgumentNullException("jobInvocationInfo");
            }

            _invocationInfo = jobInvocationInfo;
            _name = jobInvocationInfo.Name;

            if (save)
            {
                SaveToStore();
            }
        }
        public override Job2 NewJob(JobInvocationInfo specification)
        {
            if (specification == null)
            {
                throw new NullReferenceException("specification");
            }

            if (specification.Parameters.Count != 1)
            {
                throw new ArgumentException("JobInvocationInfo specification parameters not specified.");
            }

            // Retrieve source and destination path information from specification
            // parameters.
            string sourcePath = null;
            string destinationPath = null;
            CommandParameterCollection parameters = specification.Parameters[0];
            foreach (var item in parameters)
            {
                if (item.Name.Equals(SourcePathProperty, StringComparison.OrdinalIgnoreCase))
                {
                    sourcePath = item.Value as string;
                }
                else if (item.Name.Equals(DestinationPathProperty, StringComparison.OrdinalIgnoreCase))
                {
                    destinationPath = item.Value as string;
                }
            }

            // Create FileCopyJob
            FileCopyJob rtnJob = new FileCopyJob(specification.Name, sourcePath, destinationPath);
            lock (JobRepository)
            {
                JobRepository.Add(rtnJob);
            }
            return rtnJob;
        }
        private ScheduledJobDefinition(
            SerializationInfo info,
            StreamingContext context)
        {
            if (info == null)
            {
                throw new PSArgumentNullException("info");
            }

            _options = (ScheduledJobOptions)info.GetValue("Options_Member", typeof(ScheduledJobOptions));
            _globalId = Guid.Parse(info.GetString("GlobalId_Member"));
            _name = info.GetString("Name_Member");
            _executionHistoryLength = info.GetInt32("HistoryLength_Member");
            _enabled = info.GetBoolean("Enabled_Member");
            _triggers = (Dictionary<Int32, ScheduledJobTrigger>)info.GetValue("Triggers_Member", typeof(Dictionary<Int32, ScheduledJobTrigger>));
            _currentTriggerId = info.GetInt32("CurrentTriggerId_Member");
            _definitionFilePath = info.GetString("FilePath_Member");
            _definitionOutputPath = info.GetString("OutputPath_Member");

            object invocationObject = info.GetValue("InvocationInfo_Member", typeof(object));
            _invocationInfo = invocationObject as JobInvocationInfo;

            // Set the JobDefinition reference for the ScheduledJobTrigger and
            // ScheduledJobOptions objects.
            _options.JobDefinition = this;
            foreach (ScheduledJobTrigger trigger in _triggers.Values)
            {
                trigger.JobDefinition = this;
            }

            // Instance information.
            _isDisposed = false;
        }
Example #19
0
        internal PSWorkflowJob CreateJobInternal(Guid jobInstanceId, Activity workflow, string command, string name, Dictionary<string, object> parameters, string xaml, Dictionary<string, object> creationContext)
        {
            AssertNotDisposed();

            if (jobInstanceId == Guid.Empty)
                throw new ArgumentNullException("jobInstanceId");

            if (workflow == null)
                throw new ArgumentNullException("workflow");

            if (command == null)
                throw new ArgumentNullException("command");

            if (name == null)
                throw new ArgumentNullException("name");

            if (_wfJobTable.ContainsKey(jobInstanceId))
            {
                ArgumentException exception = new ArgumentException(Resources.DuplicateInstanceId);
                Tracer.TraceException(exception);
                throw exception;
            }

            lock (lockObjects.GetLockObject(jobInstanceId))
            {

                if (_wfJobTable.ContainsKey(jobInstanceId))
                {
                    ArgumentException exception = new ArgumentException(Resources.DuplicateInstanceId);
                    Tracer.TraceException(exception);
                    throw exception;
                }

                JobDefinition definition = new JobDefinition(typeof(WorkflowJobSourceAdapter), command, name);

                var parameterDictionary = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);

                if (parameters != null)
                {
                    foreach (KeyValuePair<string, object> param in parameters)
                    {
                        parameterDictionary.Add(param.Key, param.Value);
                    }
                }

                string[] computerNames = null;
                bool gotComputerNames = false;
                object value;
                if (parameterDictionary.Count != 0 && parameterDictionary.TryGetValue(Constants.ComputerName, out value))
                {
                    if (LanguagePrimitives.TryConvertTo(value, CultureInfo.InvariantCulture, out computerNames))
                        gotComputerNames = computerNames != null;
                }

                if (gotComputerNames)
                {
                    if (computerNames.Length > 1)
                        throw new ArgumentException(Resources.OneComputerNameAllowed);

                    parameterDictionary.Remove(Constants.ComputerName);
                }

                var childSpecification = new JobInvocationInfo(definition, parameterDictionary);
                childSpecification.Command = command;

                // If actual computernames were specified, then set the PSComputerName parameter.
                if (gotComputerNames)
                {
                    var computerNameParameter = new CommandParameter(Constants.ComputerName, computerNames);
                    childSpecification.Parameters[0].Add(computerNameParameter);
                }

                // Job objects will be disposed of on parent job removal.
                var childJob = new PSWorkflowJob(_runtime, childSpecification, jobInstanceId, creationContext);
                childJob.JobMetadata = CreateJobMetadataWithNoParentDefined(childJob, computerNames);

                childJob.LoadWorkflow(childSpecification.Parameters[0], workflow, xaml);
                this.AddJob(childJob);

                return childJob;
            }
        }
Example #20
0
		public ScheduledJobDefinition(JobInvocationInfo invocationInfo, IEnumerable<ScheduledJobTrigger> triggers, ScheduledJobOptions options, PSCredential credential)
		{
			ScheduledJobOptions scheduledJobOption;
			this._globalId = Guid.NewGuid();
			this._name = string.Empty;
			this._id = ScheduledJobDefinition.GetCurrentId();
			this._executionHistoryLength = ScheduledJobDefinition.DefaultExecutionHistoryLength;
			this._enabled = true;
			this._triggers = new Dictionary<int, ScheduledJobTrigger>();
			if (invocationInfo != null)
			{
				this._name = invocationInfo.Name;
				this._invocationInfo = invocationInfo;
				this.SetTriggers(triggers, false);
				ScheduledJobDefinition scheduledJobDefinition = this;
				if (options != null)
				{
					scheduledJobOption = new ScheduledJobOptions(options);
				}
				else
				{
					scheduledJobOption = new ScheduledJobOptions();
				}
				scheduledJobDefinition._options = scheduledJobOption;
				this._options.JobDefinition = this;
				this._credential = credential;
				return;
			}
			else
			{
				throw new PSArgumentNullException("invocationInfo");
			}
		}
Example #21
0
        /// <summary>
        /// CreateJob
        /// </summary>
        /// <param name="jobInvocationInfo"></param>
        /// <param name="activity"></param>
        /// <returns></returns>
        internal ContainerParentJob CreateJob(JobInvocationInfo jobInvocationInfo, Activity activity)
        {
            if (jobInvocationInfo == null)
                throw new ArgumentNullException("jobInvocationInfo");

            if (jobInvocationInfo.Definition == null)
                throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");

            if (jobInvocationInfo.Command == null)
                throw new ArgumentException(Resources.NewJobDefinitionNull, "jobInvocationInfo");

            DynamicActivity dynamicActivity = activity as DynamicActivity;

            Debug.Assert(dynamicActivity != null, "Passed workflow must be a DynamicActivity");

            Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Creating Workflow job with definition: {0}", jobInvocationInfo.Definition.InstanceId));

            // Create parent job. All PSWorkflowJob objects will be a child of some ContainerParentJob
            // This job will be disposed of when RemoveJob is called.
            ContainerParentJob newJob = new ContainerParentJob(
                jobInvocationInfo.Command, 
                jobInvocationInfo.Name,
                WorkflowJobSourceAdapter.AdapterTypeName);

            foreach (CommandParameterCollection commandParameterCollection in jobInvocationInfo.Parameters)
            {
                var parameterDictionary = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
                foreach (CommandParameter param in commandParameterCollection)
                {
                    parameterDictionary.Add(param.Name, param.Value);
                }

                string[] computerNames = null;
                bool gotComputerNames = false;
                object value;
                if (parameterDictionary.Count != 0 && parameterDictionary.TryGetValue(Constants.ComputerName, out value))
                {
                    if (LanguagePrimitives.TryConvertTo(value, CultureInfo.InvariantCulture, out computerNames))
                        gotComputerNames = computerNames != null;
                }

                StructuredTracer.ParentJobCreated(newJob.InstanceId);

                bool isComputerNameExists = false;

                if (dynamicActivity != null && dynamicActivity.Properties.Any(x => x.Name.Equals(Constants.ComputerName, StringComparison.CurrentCultureIgnoreCase)))
                {
                    isComputerNameExists = true;
                }

                dynamicActivity = null;

                if (isComputerNameExists)
                {
                    var childSpecification = new JobInvocationInfo(jobInvocationInfo.Definition, parameterDictionary);
                    childSpecification.Command = newJob.Command;

                    // If actual computernames were specified, then set the PSComputerName parameter.
                    if (gotComputerNames)
                    {
                        var computerNameParameter = new CommandParameter(Constants.ComputerName, computerNames);
                        childSpecification.Parameters[0].Add(computerNameParameter);
                    }

                    // 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);

                    childJob.LoadWorkflow(commandParameterCollection, activity, null);
                    this.AddJob(childJob);
                    newJob.AddChildJob(childJob);
                    StructuredTracer.ChildWorkflowJobAddition(childJob.InstanceId, newJob.InstanceId);
                    StructuredTracer.WorkflowJobCreated(newJob.InstanceId, childJob.InstanceId, childJob.WorkflowGuid);
                }
                else
                {
                    // Remove array of computerNames from collection.
                    parameterDictionary.Remove(Constants.ComputerName);

                    if (gotComputerNames)
                    {
                        foreach (var computerName in computerNames)
                        {
                            CreateChildJob(jobInvocationInfo, activity, newJob, commandParameterCollection, parameterDictionary, computerName, computerNames);
                        }
                    }
                    else
                    {
                        CreateChildJob(jobInvocationInfo, activity, newJob, commandParameterCollection, parameterDictionary, null, computerNames);
                    }
                }
            }

            StructuredTracer.JobCreationComplete(newJob.InstanceId, jobInvocationInfo.InstanceId);
            Tracer.TraceJob(newJob);

            return newJob;
        }
Example #22
0
 /// <summary>
 /// Create a new job with the specified JobSpecification
 /// </summary>
 /// <param name="specification">specification</param>
 /// <returns>job object</returns>
 public abstract Job2 NewJob(JobInvocationInfo specification);
Example #23
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);
        }
Example #24
0
        /// <summary>
        /// Executes an instance of the workflow object graph identified by the passed
        /// GUID, binding parameters from the Parameters hashtable.
        /// </summary>
        /// <param name="command">The powershell command.</param>
        /// <param name="workflowGuid">The GUID used to identify the workflow to run.</param>
        /// <param name="parameters">The parameters to pass to the workflow instance.</param>
        /// <param name="jobName">The friendly name for the job</param>
        /// <param name="parameterCollectionProcessed">True if there was a PSParameters collection</param>
        /// <param name="startAsync"></param>
        /// <param name="debuggerActive">True if debugger is in active state.</param>
        /// <param name="SourceLanguageMode">Language mode of source creating workflow.</param>
        public static ContainerParentJob StartWorkflowApplication(PSCmdlet command, string jobName, string workflowGuid, bool startAsync,
            bool parameterCollectionProcessed, Hashtable[] parameters, bool debuggerActive, string SourceLanguageMode)
        {
            Guid trackingGuid = Guid.NewGuid();
            _structuredTracer.BeginStartWorkflowApplication(trackingGuid);

            if (string.IsNullOrEmpty(workflowGuid))
            {
                var exception = new ArgumentNullException("workflowGuid");
                Tracer.TraceException(exception);
                throw exception;
            }

            if (command == null)
            {
                var exception = new ArgumentNullException("command");
                Tracer.TraceException(exception);
                throw exception;
            }

            if (parameterCollectionProcessed)
            {
                StringBuilder paramString = new StringBuilder();
                StringBuilder computers = new StringBuilder();

                // Add context for this trace record...
                paramString.Append("commandName ='" + command.MyInvocation.MyCommand.Name + "'\n");
                paramString.Append("jobName ='" + jobName + "'\n");
                paramString.Append("workflowGUID = " + workflowGuid + "\n");
                paramString.Append("startAsync " + startAsync.ToString() + "\n");

                // Stringize the parameter table to look like @{ k1 = v1; k2 = v2; ... }
                if (parameters != null)
                {
                    foreach (Hashtable h in parameters)
                    {
                        paramString.Append("@{");
                        bool first = true;
                        foreach (DictionaryEntry e in h)
                        {
                            if (e.Key != null)
                            {
                                if (!first)
                                {
                                    paramString.Append("'; ");
                                }
                                else
                                {
                                    first = false;
                                }
                                paramString.Append(e.Key.ToString());
                                paramString.Append("='");
                                if (e.Value != null)
                                {
                                    if (string.Equals(e.Key.ToString(), Constants.ComputerName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        computers.Append(LanguagePrimitives.ConvertTo<string>(e.Value));
                                    }

                                    paramString.Append(e.Value.ToString());
                                }
                            }
                        }
                        paramString.Append("}\n ");
                    }
                }

                _structuredTracer.ParameterSplattingWasPerformed(paramString.ToString(), computers.ToString());
            }

            JobDefinition workFlowDefinition = DefinitionCache.Instance.GetDefinition(new Guid(workflowGuid));

            if (workFlowDefinition == null)
            {
                var invalidOpException = new InvalidOperationException(
                                                                string.Format(
                                                                    CultureInfo.CurrentUICulture, 
                                                                    Resources.InvalidWorkflowDefinitionState, 
                                                                    DefinitionCache.Instance.CacheSize));
                Tracer.TraceException(invalidOpException);
                throw invalidOpException;
            }

            ContainerParentJob myJob = null;

            /*
             * Iterate through the list of parameters hashtables. Each table may, in turn
             * contain a list of computers to target.
             */
            var parameterDictionaryList = new List<Dictionary<string, object>>();
            if (parameters == null || parameters.Length == 0)
            {
                // There were no parameters so add a dummy parameter collection
                // to ensure that at least one child job is created...
                parameterDictionaryList.Add(new Dictionary<string, object>());
            }
            else if (parameters.Length == 1 && !parameterCollectionProcessed)
            {
                // If the parameter collection is just the $PSBoundParameters
                // i.e. did not come through the PSParameterCollection list
                // then just we can use it as is since it's already been processed through the parameter
                // binder...
                Hashtable h = parameters[0];
                Dictionary<string, object> paramDictionary = new Dictionary<string, object>();
                foreach (var key in parameters[0].Keys)
                {
                    paramDictionary.Add((string)key, h[key]);
                }
                parameterDictionaryList.Add(paramDictionary);
            }
            else
            {
                // Otherwise, iterate through the list of parameter collections using
                // a function to apply the parameter binder transformations on each item in the list.
                // on the hashtable.

                // Convert the parameters into dictionaries.
                foreach (Hashtable h in parameters)
                {
                    if (h != null)
                    {
                        Dictionary<string, object> canonicalEntry = ConvertToParameterDictionary(h);

                        // Add parameter dictionary to the list...
                        parameterDictionaryList.Add(canonicalEntry);
                    }
                }
            }

            JobInvocationInfo specification = new JobInvocationInfo(workFlowDefinition, parameterDictionaryList);
            specification.Name = jobName;

            specification.Command = command.MyInvocation.InvocationName;
            _structuredTracer.BeginCreateNewJob(trackingGuid);
            myJob = command.JobManager.NewJob(specification) as ContainerParentJob;
            _structuredTracer.EndCreateNewJob(trackingGuid);

            // Pass the source language mode to the workflow job so that it can be
            // applied during activity execution.
            PSLanguageMode sourceLanguageModeValue;
            PSLanguageMode? sourceLanguageMode = null;
            if (!string.IsNullOrEmpty(SourceLanguageMode) && Enum.TryParse<PSLanguageMode>(SourceLanguageMode, out sourceLanguageModeValue))
            {
                sourceLanguageMode = sourceLanguageModeValue;
            }

            // Raise engine event of new WF job start for debugger, if 
            // debugger is active (i.e., has breakpoints set).
            if (debuggerActive)
            {
                RaiseWFJobEvent(command, myJob, startAsync);
            }

            if (startAsync)
            {
                foreach(PSWorkflowJob childjob in myJob.ChildJobs)
                {
                    if (!PSSessionConfigurationData.IsServerManager)
                    {
                        childjob.EnableStreamUnloadOnPersistentState();
                    }
                    childjob.SourceLanguageMode = sourceLanguageMode;
                }
                myJob.StartJobAsync();
            }
            else
            {
                // If the job is running synchronously, the PSWorkflowJob(s) need to know
                // so that errors are decorated correctly.
                foreach (PSWorkflowJob childJob in myJob.ChildJobs)
                {
                    childJob.SynchronousExecution = true;
                    childJob.SourceLanguageMode = sourceLanguageMode;
                }
                myJob.StartJob();
            }

            // write an event specifying that job creation is done
            _structuredTracer.EndStartWorkflowApplication(trackingGuid);
            _structuredTracer.TrackingGuidContainerParentJobCorrelation(trackingGuid, myJob.InstanceId);

            return myJob;
        }
Example #25
0
		internal PSWorkflowJob(PSWorkflowRuntime runtime, JobInvocationInfo specification, Guid JobInstanceId) : base(PSWorkflowJob.Validate(specification).Command, specification.Definition.Name, JobInstanceId)
		{
			this._tracer = PowerShellTraceSourceFactory.GetTraceSource();
			this._syncObject = new object();
			this._resumeErrorSyncObject = new object();
			this._statusMessage = string.Empty;
			this._location = string.Empty;
			this._resumeErrors = new Dictionary<Guid, Exception>();
			this._workflowParameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
			this._psWorkflowCommonParameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
			this._jobMetadata = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
			this._privateMetadata = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
			this.IsSuspendable = null;
			this.listOfLabels = new List<string>();
			base.StartParameters = specification.Parameters;
			this._definition = WorkflowJobDefinition.AsWorkflowJobDefinition(specification.Definition);
			this._runtime = runtime;
			this.CommonInit();
		}