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

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

            if (specification.Definition.JobSourceAdapterType != GetType())
            {
                throw new InvalidOperationException(Resources.NewJobWrongType);
            }

            if (specification.Parameters.Count == 0)
            {
                // If there are no parameters passed in, we create one child job with nothing specified.
                specification.Parameters.Add(new CommandParameterCollection());
            }

            // validation has to happen before job creation
            bool?              isSuspendable = null;
            Activity           activity      = ValidateWorkflow(specification, null, ref isSuspendable);
            ContainerParentJob newJob        = GetJobManager().CreateJob(specification, activity);

            // We do not want to generate the warning message if the request is coming from
            // Server Manager
            if (PSSessionConfigurationData.IsServerManager == false)
            {
                foreach (PSWorkflowJob job in newJob.ChildJobs)
                {
                    bool?psPersistValue       = null;
                    PSWorkflowContext context = job.PSWorkflowInstance.PSWorkflowContext;
                    if (context != null && context.PSWorkflowCommonParameters != null && context.PSWorkflowCommonParameters.ContainsKey(Constants.Persist))
                    {
                        psPersistValue = context.PSWorkflowCommonParameters[Constants.Persist] as bool?;
                    }

                    // check for invocation time pspersist value if not true then there is a possibility that workflow is not suspendable.
                    if (psPersistValue == null || (psPersistValue == false))
                    {
                        // check for authoring time definition of persist activity
                        if (isSuspendable != null && isSuspendable.Value == false)
                        {
                            job.Warning.Add(new WarningRecord(Resources.WarningMessageForPersistence));
                            job.IsSuspendable = isSuspendable;
                        }
                    }
                }
            }

            StoreJobIdForReuse(newJob, true);
            _jobRepository.Add(newJob);

            return(newJob);
        }
Esempio n. 2
0
        internal void RemoveChildJob(Job2 childWorkflowJob)
        {
            object obj = null;

            this._structuredTracer.RemoveJobStarted(childWorkflowJob.InstanceId);
            this.PopulateJobRepositoryIfRequired();
            object[] instanceId = new object[1];
            instanceId[0] = childWorkflowJob.InstanceId;
            this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Removing Workflow job with instance id: {0}", instanceId));
            lock (this._syncRemoveChilJob)
            {
                PSWorkflowJob pSWorkflowJob = childWorkflowJob as PSWorkflowJob;
                if (pSWorkflowJob != null)
                {
                    PSWorkflowInstance pSWorkflowInstance = pSWorkflowJob.PSWorkflowInstance;
                    if (pSWorkflowInstance.PSWorkflowContext.JobMetadata.TryGetValue("ParentInstanceId", out obj))
                    {
                        Guid guid = (Guid)obj;
                        ContainerParentJob item = this._jobRepository.GetItem(guid);
                        item.ChildJobs.Remove(pSWorkflowJob);
                        try
                        {
                            this.GetJobManager().RemoveJob(pSWorkflowJob.InstanceId);
                            this._structuredTracer.JobRemoved(item.InstanceId, pSWorkflowJob.InstanceId, pSWorkflowJob.WorkflowGuid);
                        }
                        catch (ArgumentException argumentException1)
                        {
                            ArgumentException argumentException = argumentException1;
                            object[]          objArray          = new object[1];
                            objArray[0] = argumentException;
                            this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}", objArray));
                            this._structuredTracer.JobRemoveError(item.InstanceId, pSWorkflowJob.InstanceId, pSWorkflowJob.WorkflowGuid, argumentException.Message);
                        }
                        if (item.ChildJobs.Count == 0)
                        {
                            try
                            {
                                this._jobRepository.Remove(item);
                            }
                            catch (ArgumentException argumentException3)
                            {
                                ArgumentException argumentException2 = argumentException3;
                                object[]          objArray1          = new object[1];
                                objArray1[0] = argumentException2;
                                this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}", objArray1));
                            }
                            item.Dispose();
                        }
                    }
                }
            }
        }
Esempio n. 3
0
        private void ProcessExecutionErrorsAndReleaseWaitHandle(System.Management.Automation.Job job)
        {
            bool flag = false;

            lock (this._syncObject)
            {
                if (this._pendingJobs.Contains(job.InstanceId))
                {
                    this._pendingJobs.Remove(job.InstanceId);
                }
                else
                {
                    return;
                }
                if (this._needToCheckForWaitingJobs && (this._pendingJobs.Count == 0))
                {
                    flag = true;
                }
            }
            if (!this._wait)
            {
                job.StateChanged -= new EventHandler <JobStateEventArgs>(this.noWait_Job2_StateChanged);
                Job2 job2 = job as Job2;
                if (job2 != null)
                {
                    job2.SuspendJobCompleted -= new EventHandler <AsyncCompletedEventArgs>(this.HandleSuspendJobCompleted);
                }
            }
            ContainerParentJob job3 = job as ContainerParentJob;

            if ((job3 != null) && (job3.ExecutionError.Count > 0))
            {
                foreach (ErrorRecord record in from e in job3.ExecutionError
                         where e.FullyQualifiedErrorId == "ContainerParentJobSuspendAsyncError"
                         select e)
                {
                    if (record.Exception is InvalidJobStateException)
                    {
                        this._warnInvalidState = true;
                    }
                    else
                    {
                        this._errorsToWrite.Add(record);
                    }
                }
            }
            if (flag)
            {
                this._waitForJobs.Set();
            }
        }
Esempio n. 4
0
        private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eventArgs)
        {
            System.Management.Automation.Job job = sender as System.Management.Automation.Job;
            if ((eventArgs.Error != null) && (eventArgs.Error is InvalidJobStateException))
            {
                this._warnInvalidState = true;
            }
            ContainerParentJob job2 = job as ContainerParentJob;

            if ((job2 != null) && (job2.ExecutionError.Count > 0))
            {
                foreach (ErrorRecord record in from e in job2.ExecutionError
                         where e.FullyQualifiedErrorId == "ContainerParentJobResumeAsyncError"
                         select e)
                {
                    if (record.Exception is InvalidJobStateException)
                    {
                        this._warnInvalidState = true;
                    }
                    else
                    {
                        this._errorsToWrite.Add(record);
                    }
                }
                job2.ExecutionError.Clear();
            }
            bool flag = false;

            lock (this._syncObject)
            {
                if (this._pendingJobs.Contains(job.InstanceId))
                {
                    this._pendingJobs.Remove(job.InstanceId);
                }
                if (this._needToCheckForWaitingJobs && (this._pendingJobs.Count == 0))
                {
                    flag = true;
                }
            }
            if (flag)
            {
                this._waitForJobs.Set();
            }
        }
Esempio n. 5
0
        private void HandleStopJobCompleted(object sender, AsyncCompletedEventArgs eventArgs)
        {
            System.Management.Automation.Job targetObject = sender as System.Management.Automation.Job;
            if (eventArgs.Error != null)
            {
                this._errorsToWrite.Add(new ErrorRecord(eventArgs.Error, "StopJobError", ErrorCategory.ReadError, targetObject));
            }
            ContainerParentJob job2 = targetObject as ContainerParentJob;

            if ((job2 != null) && (job2.ExecutionError.Count > 0))
            {
                foreach (ErrorRecord record in from e in job2.ExecutionError
                         where e.FullyQualifiedErrorId == "ContainerParentJobStopAsyncError"
                         select e)
                {
                    this._errorsToWrite.Add(record);
                }
            }
            bool flag = false;

            lock (this._syncObject)
            {
                if (this._pendingJobs.Contains(targetObject.InstanceId))
                {
                    this._pendingJobs.Remove(targetObject.InstanceId);
                }
                if (this._needToCheckForWaitingJobs && (this._pendingJobs.Count == 0))
                {
                    flag = true;
                }
            }
            if (flag)
            {
                this._waitForJobs.Set();
            }
        }
        private IEnumerable <Job2> CreateJobsFromWorkflows(IEnumerable <Job2> workflowJobs, bool returnParents)
        {
            // Jobs in this collection correspond to the ContainerParentJob objects. PSWorkflowJob objects
            // are children of these.
            var reconstructedParentJobs = new Dictionary <Guid, Job2>();
            var jobs = new List <Job2>();

            if (workflowJobs == null)
            {
                return(jobs);
            }

            // If a workflow instance has incomplete metadata, we do not create the job for it.
            foreach (var job in workflowJobs)
            {
                var wfjob = job as PSWorkflowJob;
                Debug.Assert(wfjob != null, "Job supplied must be of type PSWorkflowJob");
                PSWorkflowInstance instance = wfjob.PSWorkflowInstance;
                Dbg.Assert(instance != null, "PSWorkflowInstance should be reconstructed before attempting to rehydrate job");

                if (!instance.JobStateRetrieved || instance.PSWorkflowContext.JobMetadata == null || instance.PSWorkflowContext.JobMetadata.Count == 0)
                {
                    continue;
                }

                object data;
                string name, command;
                Guid   instanceId;
                if (!GetJobInfoFromMetadata(instance, out command, out name, out instanceId))
                {
                    continue;
                }

                if (!instance.PSWorkflowContext.JobMetadata.TryGetValue(Constants.JobMetadataParentInstanceId, out data))
                {
                    continue;
                }
                var parentInstanceId = (Guid)data;

                // If the parent job is needed, find or create it now so that the ID is sequentially lower.
                if (returnParents && !reconstructedParentJobs.ContainsKey(parentInstanceId))
                {
                    if (!instance.PSWorkflowContext.JobMetadata.TryGetValue(Constants.JobMetadataParentName, out data))
                    {
                        continue;
                    }
                    var parentName = (string)data;

                    if (!instance.PSWorkflowContext.JobMetadata.TryGetValue(Constants.JobMetadataParentCommand, out data))
                    {
                        continue;
                    }
                    var parentCommand = (string)data;

                    JobIdentifier      parentId  = RetrieveJobIdForReuse(parentInstanceId);
                    ContainerParentJob parentJob = parentId != null
                                                       ? new ContainerParentJob(parentCommand, parentName, parentId, AdapterTypeName)
                                                       : new ContainerParentJob(parentCommand, parentName, parentInstanceId, AdapterTypeName);

                    // update job metadata with new parent session Id--needed for filtering.
                    // The pid in the metadata has already been updated at this point.
                    Dbg.Assert(
                        instance.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataParentSessionId),
                        "Job Metadata for instance incomplete.");
                    if (instance.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataParentSessionId))
                    {
                        instance.PSWorkflowContext.JobMetadata[Constants.JobMetadataParentSessionId] = parentJob.Id;
                    }

                    reconstructedParentJobs.Add(parentInstanceId, parentJob);
                }

                // update job metadata with new session Id--needed for filtering.
                Dbg.Assert(instance.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataSessionId), "Job Metadata for instance incomplete.");
                Dbg.Assert(instance.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataPid), "Job Metadata for instance incomplete.");
                if (instance.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataSessionId))
                {
                    instance.PSWorkflowContext.JobMetadata[Constants.JobMetadataSessionId] = job.Id;
                }
                if (instance.PSWorkflowContext.JobMetadata.ContainsKey(Constants.JobMetadataPid))
                {
                    instance.PSWorkflowContext.JobMetadata[Constants.JobMetadataPid] = Process.GetCurrentProcess().Id;
                }

                job.StartParameters = new List <CommandParameterCollection>();
                CommandParameterCollection commandParameterCollection = new CommandParameterCollection();
                AddStartParametersFromCollection(instance.PSWorkflowContext.WorkflowParameters, commandParameterCollection);
                AddStartParametersFromCollection(instance.PSWorkflowContext.PSWorkflowCommonParameters, commandParameterCollection);

                bool takesPSPrivateMetadata;
                if (instance.PSWorkflowContext.JobMetadata.ContainsKey(Constants.WorkflowTakesPrivateMetadata))
                {
                    takesPSPrivateMetadata = (bool)instance.PSWorkflowContext.JobMetadata[Constants.WorkflowTakesPrivateMetadata];
                }
                else
                {
                    DynamicActivity da = instance.PSWorkflowDefinition != null ? instance.PSWorkflowDefinition.Workflow as DynamicActivity : null;
                    takesPSPrivateMetadata = da != null && da.Properties.Contains(Constants.PrivateMetadata);
                }

                // If there is Private Metadata and it is not included in the "Input" collection, add it now.
                if (instance.PSWorkflowContext.PrivateMetadata != null &&
                    instance.PSWorkflowContext.PrivateMetadata.Count > 0 &&
                    !takesPSPrivateMetadata)
                {
                    Hashtable privateMetadata = new Hashtable();
                    foreach (var pair in instance.PSWorkflowContext.PrivateMetadata)
                    {
                        privateMetadata.Add(pair.Key, pair.Value);
                    }
                    commandParameterCollection.Add(new CommandParameter(Constants.PrivateMetadata, privateMetadata));
                }
                job.StartParameters.Add(commandParameterCollection);

                if (returnParents)
                {
                    ((ContainerParentJob)reconstructedParentJobs[parentInstanceId]).AddChildJob(job);
                }
                else
                {
                    jobs.Add(job);
                }

                if (!wfjob.WorkflowInstanceLoaded)
                {
                    // RestoreFromWorkflowInstance sets the job state. Because we've used AddChildJob, the parent's state will be
                    // updated automatically.
                    wfjob.RestoreFromWorkflowInstance(instance);
                }
            }

            if (returnParents)
            {
                jobs.AddRange(reconstructedParentJobs.Values);
            }

            return(jobs);
        }
        internal void RemoveChildJob(Job2 childWorkflowJob)
        {
            _structuredTracer.RemoveJobStarted(childWorkflowJob.InstanceId);
            PopulateJobRepositoryIfRequired();

            _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Removing Workflow job with instance id: {0}", childWorkflowJob.InstanceId));

            lock (_syncRemoveChilJob)
            {
                PSWorkflowJob childJob = childWorkflowJob as PSWorkflowJob;
                if (childJob == null)
                {
                    return;
                }

                object             data;
                PSWorkflowInstance instance = childJob.PSWorkflowInstance;

                if (!instance.PSWorkflowContext.JobMetadata.TryGetValue(Constants.JobMetadataParentInstanceId, out data))
                {
                    return;
                }
                var parentInstanceId   = (Guid)data;
                ContainerParentJob job = _jobRepository.GetItem(parentInstanceId);

                job.ChildJobs.Remove(childJob);


                try
                {
                    GetJobManager().RemoveJob(childJob.InstanceId);
                    _structuredTracer.JobRemoved(job.InstanceId,
                                                 childJob.InstanceId, childJob.WorkflowGuid);
                }
                catch (ArgumentException exception)
                {
                    //ignoring the error message and just logging them into ETW
                    _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                       "WorkflowJobSourceAdapter: Ignoring the exception. Exception details: {0}",
                                                       exception));

                    _structuredTracer.JobRemoveError(job.InstanceId,
                                                     childJob.InstanceId, childJob.WorkflowGuid,
                                                     exception.Message);
                }

                if (job.ChildJobs.Count == 0)
                {
                    // remove the container parent job from repository
                    try
                    {
                        _jobRepository.Remove(job);
                    }
                    catch (ArgumentException exception)
                    {
                        //ignoring the error message and just logging them into ETW
                        _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                           "WorkflowJobSourceAdapter: Ignoring the exception. Exception details: {0}",
                                                           exception));
                    }
                    job.Dispose();
                }
            }
        }
        /// <summary>
        /// Get list of jobs based on the adapter specific
        /// filter parameters
        /// </summary>
        /// <param name="filter">dictionary containing name value
        ///   pairs for adapter specific filters</param>
        /// <param name="recurse"></param>
        /// <returns>collection of jobs that match the
        /// specified criteria</returns>
        public override IList <Job2> GetJobsByFilter(Dictionary <string, object> filter, bool recurse)
        {
            if (filter == null)
            {
                throw new ArgumentNullException("filter");
            }
            _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                               "WorkflowJobSourceAdapter: Getting Workflow jobs by filter: {0}", filter));
            PopulateJobRepositoryIfRequired();

            // Do not modify the user's collection.
            Dictionary <string, object> filter2 = new Dictionary <string, object>(filter, StringComparer.CurrentCultureIgnoreCase);
            bool addPid           = false;
            bool searchParentJobs = true;

            if (filter2.Keys.Count == 0)
            {
                searchParentJobs = false;
            }
            else
            {
                if (filter2.Keys.Any(key => (((!key.Equals(Constants.JobMetadataSessionId, StringComparison.OrdinalIgnoreCase) && !key.Equals(Constants.JobMetadataInstanceId, StringComparison.OrdinalIgnoreCase)) && !key.Equals(Constants.JobMetadataName, StringComparison.OrdinalIgnoreCase)) && !key.Equals(Constants.JobMetadataCommand, StringComparison.OrdinalIgnoreCase)) && !key.Equals(Constants.JobMetadataFilterState, StringComparison.OrdinalIgnoreCase)))
                {
                    searchParentJobs = false;
                }
            }

            List <Job2> jobs = new List <Job2>();

            // search container parent jobs first
            if (searchParentJobs)
            {
                List <ContainerParentJob> repositoryJobs = _jobRepository.GetItems();

                List <Job2> searchList = SearchJobsOnV2Parameters(repositoryJobs, filter2);
                repositoryJobs.Clear();

                if (searchList.Count > 0)
                {
                    jobs.AddRange(searchList);
                }
            }

            if (recurse)
            {
                // If the session Id parameter is present, make sure that the Id match is valid by adding the process Id to the filter.
                if (filter2.ContainsKey(Constants.JobMetadataSessionId))
                {
                    addPid = true;
                }

                if (addPid)
                {
                    filter2.Add(Constants.JobMetadataPid, Process.GetCurrentProcess().Id);
                }

                if (filter2.ContainsKey(Constants.JobMetadataFilterState))
                {
                    filter2.Remove(Constants.JobMetadataFilterState);
                }

                LoadWorkflowInstancesFromStore();

                // remove state from filter here and do it separately
                IEnumerable <Job2> workflowInstances = GetJobManager().GetJobs(WorkflowFilterTypes.All, filter2);

                if (filter.ContainsKey(Constants.JobMetadataFilterState))
                {
                    JobState searchState =
                        (JobState)
                        LanguagePrimitives.ConvertTo(filter[Constants.JobMetadataFilterState], typeof(JobState), CultureInfo.InvariantCulture);
                    var list = workflowInstances.Where(job => job.JobStateInfo.State == searchState).ToList();
                    jobs.AddRange(list);
                }
                else
                {
                    jobs.AddRange(workflowInstances);
                }
            }

            List <Job2> cpjs = new List <Job2>();

            foreach (var job in jobs)
            {
                if (job is ContainerParentJob && !cpjs.Contains(job))
                {
                    cpjs.Add(job);
                    continue;
                }

                PSWorkflowJob wfj = job as PSWorkflowJob;
                Dbg.Assert(wfj != null, "if it's not a containerparentjob, it had better be a workflowjob");
                ContainerParentJob cpj = _jobRepository.GetItem((Guid)wfj.JobMetadata[Constants.JobMetadataParentInstanceId]);
                if (!cpjs.Contains(cpj))
                {
                    cpjs.Add(cpj);
                }
            }

            return(cpjs);
        }
Esempio n. 9
0
        private IEnumerable <Job2> CreateJobsFromWorkflows(IEnumerable <Job2> workflowJobs, bool returnParents)
        {
            object                  obj  = null;
            string                  str  = null;
            string                  str1 = null;
            Guid                    guid;
            bool                    item;
            DynamicActivity         workflow;
            bool                    flag;
            ContainerParentJob      containerParentJob;
            Dictionary <Guid, Job2> guids = new Dictionary <Guid, Job2>();
            List <Job2>             job2s = new List <Job2>();

            if (workflowJobs != null)
            {
                foreach (Job2 workflowJob in workflowJobs)
                {
                    PSWorkflowJob      pSWorkflowJob      = workflowJob as PSWorkflowJob;
                    PSWorkflowInstance pSWorkflowInstance = pSWorkflowJob.PSWorkflowInstance;
                    if (!pSWorkflowInstance.JobStateRetrieved || pSWorkflowInstance.PSWorkflowContext.JobMetadata == null || pSWorkflowInstance.PSWorkflowContext.JobMetadata.Count == 0 || !WorkflowJobSourceAdapter.GetJobInfoFromMetadata(pSWorkflowInstance, out str1, out str, out guid) || !pSWorkflowInstance.PSWorkflowContext.JobMetadata.TryGetValue("ParentInstanceId", out obj))
                    {
                        continue;
                    }
                    Guid guid1 = (Guid)obj;
                    if (returnParents && !guids.ContainsKey(guid1))
                    {
                        if (!pSWorkflowInstance.PSWorkflowContext.JobMetadata.TryGetValue("ParentName", out obj))
                        {
                            continue;
                        }
                        string str2 = (string)obj;
                        if (!pSWorkflowInstance.PSWorkflowContext.JobMetadata.TryGetValue("ParentCommand", out obj))
                        {
                            continue;
                        }
                        string        str3          = (string)obj;
                        JobIdentifier jobIdentifier = base.RetrieveJobIdForReuse(guid1);
                        if (jobIdentifier != null)
                        {
                            containerParentJob = new ContainerParentJob(str3, str2, jobIdentifier, "PSWorkflowJob");
                        }
                        else
                        {
                            containerParentJob = new ContainerParentJob(str3, str2, guid1, "PSWorkflowJob");
                        }
                        ContainerParentJob containerParentJob1 = containerParentJob;
                        if (pSWorkflowInstance.PSWorkflowContext.JobMetadata.ContainsKey("ParentSessionId"))
                        {
                            pSWorkflowInstance.PSWorkflowContext.JobMetadata["ParentSessionId"] = containerParentJob1.Id;
                        }
                        guids.Add(guid1, containerParentJob1);
                    }
                    if (pSWorkflowInstance.PSWorkflowContext.JobMetadata.ContainsKey("Id"))
                    {
                        pSWorkflowInstance.PSWorkflowContext.JobMetadata["Id"] = workflowJob.Id;
                    }
                    if (pSWorkflowInstance.PSWorkflowContext.JobMetadata.ContainsKey("ProcessId"))
                    {
                        pSWorkflowInstance.PSWorkflowContext.JobMetadata["ProcessId"] = Process.GetCurrentProcess().Id;
                    }
                    workflowJob.StartParameters = new List <CommandParameterCollection>();
                    CommandParameterCollection commandParameterCollection = new CommandParameterCollection();
                    WorkflowJobSourceAdapter.AddStartParametersFromCollection(pSWorkflowInstance.PSWorkflowContext.WorkflowParameters, commandParameterCollection);
                    WorkflowJobSourceAdapter.AddStartParametersFromCollection(pSWorkflowInstance.PSWorkflowContext.PSWorkflowCommonParameters, commandParameterCollection);
                    if (!pSWorkflowInstance.PSWorkflowContext.JobMetadata.ContainsKey("WorkflowTakesPrivateMetadata"))
                    {
                        if (pSWorkflowInstance.PSWorkflowDefinition != null)
                        {
                            workflow = pSWorkflowInstance.PSWorkflowDefinition.Workflow as DynamicActivity;
                        }
                        else
                        {
                            workflow = null;
                        }
                        DynamicActivity dynamicActivity = workflow;
                        if (dynamicActivity == null)
                        {
                            flag = false;
                        }
                        else
                        {
                            flag = dynamicActivity.Properties.Contains("PSPrivateMetadata");
                        }
                        item = flag;
                    }
                    else
                    {
                        item = (bool)pSWorkflowInstance.PSWorkflowContext.JobMetadata["WorkflowTakesPrivateMetadata"];
                    }
                    if (pSWorkflowInstance.PSWorkflowContext.PrivateMetadata != null && pSWorkflowInstance.PSWorkflowContext.PrivateMetadata.Count > 0 && !item)
                    {
                        Hashtable hashtables = new Hashtable();
                        foreach (KeyValuePair <string, object> privateMetadatum in pSWorkflowInstance.PSWorkflowContext.PrivateMetadata)
                        {
                            hashtables.Add(privateMetadatum.Key, privateMetadatum.Value);
                        }
                        commandParameterCollection.Add(new CommandParameter("PSPrivateMetadata", hashtables));
                    }
                    workflowJob.StartParameters.Add(commandParameterCollection);
                    if (!returnParents)
                    {
                        job2s.Add(workflowJob);
                    }
                    else
                    {
                        ((ContainerParentJob)guids[guid1]).AddChildJob(workflowJob);
                    }
                    if (pSWorkflowJob.WorkflowInstanceLoaded)
                    {
                        continue;
                    }
                    pSWorkflowJob.RestoreFromWorkflowInstance(pSWorkflowInstance);
                }
                if (returnParents)
                {
                    foreach (Job2 value in guids.Values)
                    {
                        PSSQMAPI.InitiateWorkflowStateDataTracking(value);
                    }
                    job2s.AddRange(guids.Values);
                }
                return(job2s);
            }
            else
            {
                return(job2s);
            }
        }
Esempio n. 10
0
 public override void RemoveJob(Job2 job)
 {
     if (job != null)
     {
         this._structuredTracer.RemoveJobStarted(job.InstanceId);
         ContainerParentJob item = this._jobRepository.GetItem(job.InstanceId);
         if (item == null)
         {
             this.PopulateJobRepositoryIfRequired();
         }
         if (job as ContainerParentJob != null)
         {
             object[] instanceId = new object[1];
             instanceId[0] = job.InstanceId;
             this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Removing Workflow job with instance id: {0}", instanceId));
             Exception exception = null;
             foreach (Job childJob in job.ChildJobs)
             {
                 PSWorkflowJob pSWorkflowJob = childJob as PSWorkflowJob;
                 if (pSWorkflowJob == null)
                 {
                     continue;
                 }
                 try
                 {
                     this.GetJobManager().RemoveJob(pSWorkflowJob.InstanceId);
                     this._structuredTracer.JobRemoved(job.InstanceId, childJob.InstanceId, pSWorkflowJob.WorkflowGuid);
                 }
                 catch (ArgumentException argumentException1)
                 {
                     ArgumentException argumentException = argumentException1;
                     object[]          objArray          = new object[1];
                     objArray[0] = argumentException;
                     this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}", objArray));
                     exception = argumentException;
                     this._structuredTracer.JobRemoveError(job.InstanceId, childJob.InstanceId, pSWorkflowJob.WorkflowGuid, argumentException.Message);
                 }
             }
             try
             {
                 this._jobRepository.Remove((ContainerParentJob)job);
             }
             catch (ArgumentException argumentException3)
             {
                 ArgumentException argumentException2 = argumentException3;
                 object[]          objArray1          = new object[1];
                 objArray1[0] = argumentException2;
                 this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Ingnoring the exception. Exception details: {0}", objArray1));
                 exception = argumentException2;
             }
             job.Dispose();
             if (exception != null)
             {
                 new ArgumentException(Resources.WorkflowChildCouldNotBeRemoved, "job", exception);
             }
             return;
         }
         else
         {
             throw new InvalidOperationException(Resources.CannotRemoveWorkflowJobDirectly);
         }
     }
     else
     {
         throw new ArgumentNullException("job");
     }
 }
Esempio n. 11
0
        public override Job2 NewJob(JobInvocationInfo specification)
        {
            bool hasValue;

            if (specification != null)
            {
                if (specification.Definition != null)
                {
                    if (specification.Definition.JobSourceAdapterType == base.GetType())
                    {
                        if (specification.Parameters.Count == 0)
                        {
                            specification.Parameters.Add(new CommandParameterCollection());
                        }
                        bool?              nullable           = null;
                        Activity           activity           = this.ValidateWorkflow(specification, null, ref nullable);
                        ContainerParentJob containerParentJob = this.GetJobManager().CreateJob(specification, activity);
                        if (!PSSessionConfigurationData.IsServerManager)
                        {
                            foreach (PSWorkflowJob childJob in containerParentJob.ChildJobs)
                            {
                                bool?item = null;
                                PSWorkflowContext pSWorkflowContext = childJob.PSWorkflowInstance.PSWorkflowContext;
                                if (pSWorkflowContext != null && pSWorkflowContext.PSWorkflowCommonParameters != null && pSWorkflowContext.PSWorkflowCommonParameters.ContainsKey("PSPersist"))
                                {
                                    item = (bool?)(pSWorkflowContext.PSWorkflowCommonParameters["PSPersist"] as bool?);
                                }
                                if (item.HasValue)
                                {
                                    bool?nullable1 = item;
                                    if (nullable1.GetValueOrDefault())
                                    {
                                        hasValue = false;
                                    }
                                    else
                                    {
                                        hasValue = nullable1.HasValue;
                                    }
                                    if (!hasValue)
                                    {
                                        continue;
                                    }
                                }
                                if (!nullable.HasValue || nullable.Value)
                                {
                                    continue;
                                }
                                childJob.Warning.Add(new WarningRecord(Resources.WarningMessageForPersistence));
                                childJob.IsSuspendable = nullable;
                            }
                        }
                        base.StoreJobIdForReuse(containerParentJob, true);
                        this._jobRepository.Add(containerParentJob);
                        return(containerParentJob);
                    }
                    else
                    {
                        throw new InvalidOperationException(Resources.NewJobWrongType);
                    }
                }
                else
                {
                    throw new ArgumentException(Resources.NewJobDefinitionNull, "specification");
                }
            }
            else
            {
                throw new ArgumentNullException("specification");
            }
        }
Esempio n. 12
0
 public override IList <Job2> GetJobsByFilter(Dictionary <string, object> filter, bool recurse)
 {
     if (filter != null)
     {
         object[] objArray = new object[1];
         objArray[0] = filter;
         this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Getting Workflow jobs by filter: {0}", objArray));
         this.PopulateJobRepositoryIfRequired();
         Dictionary <string, object> strs = new Dictionary <string, object>(filter, StringComparer.CurrentCultureIgnoreCase);
         bool flag  = false;
         bool flag1 = true;
         if (strs.Keys.Count != 0)
         {
             var keys = strs.Keys;
             if (keys.Any <string>((string key) => {
                 if (key.Equals("Id", StringComparison.OrdinalIgnoreCase) || key.Equals("InstanceId", StringComparison.OrdinalIgnoreCase) || key.Equals("Name", StringComparison.OrdinalIgnoreCase) || key.Equals("Command", StringComparison.OrdinalIgnoreCase))
                 {
                     return(false);
                 }
                 else
                 {
                     return(!key.Equals("State", StringComparison.OrdinalIgnoreCase));
                 }
             }
                                   ))
             {
                 flag1 = false;
             }
         }
         else
         {
             flag1 = false;
         }
         List <Job2> job2s = new List <Job2>();
         if (flag1)
         {
             List <ContainerParentJob> items = this._jobRepository.GetItems();
             List <Job2> job2s1 = WorkflowJobSourceAdapter.SearchJobsOnV2Parameters(items, strs);
             items.Clear();
             if (job2s1.Count > 0)
             {
                 job2s.AddRange(job2s1);
             }
         }
         if (recurse)
         {
             if (strs.ContainsKey("Id"))
             {
                 flag = true;
             }
             if (flag)
             {
                 strs.Add("ProcessId", Process.GetCurrentProcess().Id);
             }
             if (strs.ContainsKey("State"))
             {
                 strs.Remove("State");
             }
             this.LoadWorkflowInstancesFromStore();
             IEnumerable <Job2> jobs = this.GetJobManager().GetJobs(WorkflowFilterTypes.All, strs);
             if (!filter.ContainsKey("State"))
             {
                 job2s.AddRange(jobs);
             }
             else
             {
                 List <Job2> list = jobs.Where <Job2>((Job2 job) => job.JobStateInfo.State == (JobState)LanguagePrimitives.ConvertTo(filter["State"], typeof(JobState), CultureInfo.InvariantCulture)).ToList <Job2>();
                 job2s.AddRange(list);
             }
         }
         List <Job2> job2s2 = new List <Job2>();
         foreach (Job2 job2 in job2s)
         {
             if (job2 as ContainerParentJob == null || job2s2.Contains(job2))
             {
                 PSWorkflowJob      pSWorkflowJob = job2 as PSWorkflowJob;
                 ContainerParentJob item          = this._jobRepository.GetItem((Guid)pSWorkflowJob.JobMetadata["ParentInstanceId"]);
                 if (job2s2.Contains(item))
                 {
                     continue;
                 }
                 job2s2.Add(item);
             }
             else
             {
                 job2s2.Add(job2);
             }
         }
         return(job2s2);
     }
     else
     {
         throw new ArgumentNullException("filter");
     }
 }
Esempio n. 13
0
        protected override void ProcessRecord()
        {
            List <System.Management.Automation.Job> collection = null;
            string parameterSetName = base.ParameterSetName;

            if (parameterSetName != null)
            {
                if (!(parameterSetName == "NameParameterSet"))
                {
                    if (parameterSetName == "InstanceIdParameterSet")
                    {
                        collection = base.FindJobsMatchingByInstanceId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "SessionIdParameterSet")
                    {
                        collection = base.FindJobsMatchingBySessionId(true, false, true, false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "StateParameterSet")
                    {
                        collection = base.FindJobsMatchingByState(false);
                        goto Label_00A2;
                    }
                    if (parameterSetName == "FilterParameterSet")
                    {
                        collection = base.FindJobsMatchingByFilter(false);
                        goto Label_00A2;
                    }
                }
                else
                {
                    collection = base.FindJobsMatchingByName(true, false, true, false);
                    goto Label_00A2;
                }
            }
            collection = base.CopyJobsToList(this.jobs, false, false);
Label_00A2:
            this._allJobsToStop.AddRange(collection);
            foreach (System.Management.Automation.Job job in collection)
            {
                if (base.Stopping)
                {
                    break;
                }
                if (!job.IsFinishedState(job.JobStateInfo.State))
                {
                    string target = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, new object[] { job.Command, job.Id });
                    if (base.ShouldProcess(target, "Stop"))
                    {
                        Job2 key = job as Job2;
                        if (key != null)
                        {
                            this._cleanUpActions.Add(key, new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted));
                            key.StopJobCompleted += new EventHandler <AsyncCompletedEventArgs>(this.HandleStopJobCompleted);
                            lock (this._syncObject)
                            {
                                if (!key.IsFinishedState(key.JobStateInfo.State) && !this._pendingJobs.Contains(key.InstanceId))
                                {
                                    this._pendingJobs.Add(key.InstanceId);
                                }
                            }
                            key.StopJobAsync();
                        }
                        else
                        {
                            job.StopJob();
                            ContainerParentJob job3 = job as ContainerParentJob;
                            if ((job3 != null) && (job3.ExecutionError.Count > 0))
                            {
                                foreach (ErrorRecord record in from e in job3.ExecutionError
                                         where e.FullyQualifiedErrorId == "ContainerParentJobStopError"
                                         select e)
                                {
                                    base.WriteError(record);
                                }
                            }
                        }
                    }
                }
            }
        }