コード例 #1
0
        // In this function the activity action is performed
        private void PerformWork(ActivityActionData data)
        {
            bool      failed    = false;
            Exception exception = null;

            try
            {
                // setting up the streams
                data.command.Streams.Debug    = data.streams.DebugStream;
                data.command.Streams.Error    = data.streams.ErrorStream;
                data.command.Streams.Progress = data.streams.ProgressStream;
                data.command.Streams.Verbose  = data.streams.VerboseStream;
                data.command.Streams.Warning  = data.streams.WarningStream;


                // Custom WinRM Workflow Endpoint details
                // run CustomWorkflowEndpointSetup.ps1 in Powershell console as administrator, if you have not done.
                //
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
                connectionInfo.ShellUri = "http://schemas.microsoft.com/powershell/CustomeWorkflowEndpoint";

                // Create runspace pool on custom workflow endpoint where command will be invoked
                using (RunspacePool r = RunspaceFactory.CreateRunspacePool(1, 1, connectionInfo))
                {
                    try
                    {
                        r.Open();
                        data.command.RunspacePool = r;

                        // now executing the powershell command.
                        data.command.Invoke(data.streams.InputStream, data.streams.OutputStream, new PSInvocationSettings());
                    }
                    finally
                    {
                        r.Close();
                        r.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                // since work is getting performed on background thread so there should not be any exception.
                failed    = true;
                exception = e;
            }

            // Now since activity action has already been performed so now we need to resume the execution of the
            // workflow. This will be done by
            PSWorkflowJob job = _runtime.JobManager.GetJob(data.jobInstanceId);

            // Now resuming the job
            if (failed)
            {
                job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams, exception);
            }
            else
            {
                job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams);
            }
        }
コード例 #2
0
        static void Main(string[] args)
        {
            // Create a variable for the workflow path.
            string workflowFileName = "SampleWorkflow.xaml";

            // Read the XAML into the variable.
            string xaml = File.ReadAllText(workflowFileName);

            // Create a runtime to host the workflow, passing the custom configuration provider.
            PSWorkflowRuntime runtime = new PSWorkflowRuntime(new SampleConfigurationProvider());

            // Parameters to the workflow can be provided in this dictionary.
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            // Pass the ID of the current process, which the sample workflow expects as an input parameter.
            parameters.Add("ProcessId", (new List <int>()
            {
                Process.GetCurrentProcess().Id
            }).ToArray());

            // Create the job, providing the XAML definition.
            PSWorkflowJob job = runtime.JobManager.CreateJob(Guid.NewGuid(), xaml, "Get-CurrentProcess", "SampleWorkflow", parameters);

            // Subscribe to the state change event before starting the job.
            AutoResetEvent wfEvent = new AutoResetEvent(false);

            job.StateChanged += delegate(object sender, JobStateEventArgs e)
            {
                switch (e.JobStateInfo.State)
                {
                case JobState.Failed:
                case JobState.Completed:
                {
                    wfEvent.Set();
                }
                break;
                }
            };

            // Start the job.
            job.StartJob();

            // Wait for the state changes event.
            wfEvent.WaitOne();

            if (job.JobStateInfo.State == JobState.Completed)
            {
                Console.WriteLine("The job has completed successfully.");
                Console.WriteLine("Total processes found: " + job.PSWorkflowInstance.Streams.OutputStream.Count);
            }
            else
            {
                Console.WriteLine("The job has Failed.");
            }

            Console.WriteLine("Press <Enter> to continue...");
            Console.ReadLine();
        }
コード例 #3
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();
                        }
                    }
                }
            }
        }
コード例 #4
0
        static void Main(string[] args)
        {
            // Set the path to the XAML workflow.
            string workflowFileName = "SampleWorkflow.xaml";

            // Read the XAML from the workflow into the variable
            string xaml = File.ReadAllText(workflowFileName);

            // Create a runtime to host the workflow, passing the custom configuration provider to the constructor.
            PSWorkflowRuntime runtime = new PSWorkflowRuntime(new SampleConfigurationProvider());

            // Parameters for the workflow can be provided in this dictionary
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            // Create the job. Because we are using the default file-based store, we need to provide the XAML worklfow definition.
            PSWorkflowJob job = runtime.JobManager.CreateJob(Guid.NewGuid(), xaml, "Get-CurrentProcess", "SampleWorkflow", parameters);

            // Subscribe to the state change event before starting the job.
            AutoResetEvent wfEvent = new AutoResetEvent(false);

            job.StateChanged += delegate(object sender, JobStateEventArgs e)
            {
                switch (e.JobStateInfo.State)
                {
                case JobState.Failed:
                case JobState.Completed:
                {
                    wfEvent.Set();
                }
                break;
                }
            };

            // Start the job
            job.StartJob();

            // Wait for the state change event.
            wfEvent.WaitOne();

            if (job.JobStateInfo.State == JobState.Completed)
            {
                Console.WriteLine("The job has completed successfully.");
                Console.WriteLine("Total Commands found: " + job.PSWorkflowInstance.Streams.OutputStream.Count);
            }
            else
            {
                Console.WriteLine("The job has Failed.");
            }

            Console.WriteLine("Press <Enter> to continue...");
            Console.ReadLine();
        }
コード例 #5
0
        /// <summary>
        /// Begin for obtaining a runspace for the specified ConnectionInfo
        /// </summary>
        /// <param name="connectionInfo">connection info to be used for remote connections</param>
        /// <param name="retryCount">number of times to retry</param>
        /// <param name="callback">optional user defined callback</param>
        /// <param name="state">optional user specified state</param>
        /// <param name="retryInterval">time in milliseconds before the next retry has to be attempted</param>
        /// <returns>async result</returns>
        public override IAsyncResult BeginGetRunspace(WSManConnectionInfo connectionInfo, uint retryCount, uint retryInterval, AsyncCallback callback, object state)
        {
            if (connectionInfo != null)
            {
                throw new InvalidOperationException();
            }

            LocalRunspaceAsyncResult asyncResult = new LocalRunspaceAsyncResult(state, callback, Guid.Empty);

            // Get the source language mode from the activity arguments if available and pass to runspace fetching.
            PSLanguageMode?      sourceLanguageMode = null;
            RunCommandsArguments args = state as RunCommandsArguments;

            if (args != null)
            {
                PSWorkflowRuntime wfRuntime = args.WorkflowHost as PSWorkflowRuntime;
                if (wfRuntime != null)
                {
                    PSWorkflowJob wfJob = wfRuntime.JobManager.GetJob(args.PSActivityContext.JobInstanceId);
                    if (wfJob != null)
                    {
                        sourceLanguageMode = wfJob.SourceLanguageMode;
                    }
                }
            }

            Runspace runspace = AssignRunspaceIfPossible(sourceLanguageMode);

            if (runspace != null)
            {
                asyncResult.Runspace = runspace;
                asyncResult.CompletedSynchronously = true;
                asyncResult.SetAsCompleted(null);
            }
            else
            {
                // queue the request
                _requests.Enqueue(asyncResult);
                CheckAndStartRequestServicingThread();
            }

            return(asyncResult);
        }
コード例 #6
0
        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();
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Remove a job from the store
        /// </summary>
        /// <param name="job">job object to remove</param>
        public override void RemoveJob(Job2 job)
        {
            if (job == null)
            {
                throw new ArgumentNullException("job");
            }
            _structuredTracer.RemoveJobStarted(job.InstanceId);

            var jobInMemory = _jobRepository.GetItem(job.InstanceId);

            if (jobInMemory == null)
            {
                // the specified job is not available in memory
                // load the job repository
                PopulateJobRepositoryIfRequired();
            }

            if (!(job is ContainerParentJob))
            {
                throw new InvalidOperationException(Resources.CannotRemoveWorkflowJobDirectly);
            }

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

            Exception innerException = null;

            foreach (Job childJob in job.ChildJobs)
            {
                PSWorkflowJob workflowChildJob = childJob as PSWorkflowJob;

                if (workflowChildJob == null)
                {
                    continue;
                }

                try
                {
                    GetJobManager().RemoveJob(workflowChildJob.InstanceId);
                    _structuredTracer.JobRemoved(job.InstanceId,
                                                 childJob.InstanceId, workflowChildJob.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));
                    innerException = exception;
                    _structuredTracer.JobRemoveError(job.InstanceId,
                                                     childJob.InstanceId, workflowChildJob.WorkflowGuid,
                                                     exception.Message);
                }
            }

            // remove the container parent job from repository
            try
            {
                _jobRepository.Remove((ContainerParentJob)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));
                innerException = exception;
            }
            job.Dispose();

            // Failed to remove the job?
            if (innerException != null)
            {
                ArgumentException exc = new ArgumentException(Resources.WorkflowChildCouldNotBeRemoved, "job", innerException);
                throw exc;
            }
        }
コード例 #8
0
        /// <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);
        }
コード例 #9
0
 public virtual PSWorkflowInstance CreatePSWorkflowInstance(PSWorkflowDefinition definition, PSWorkflowContext metadata, PSDataCollection <PSObject> pipelineInput, PSWorkflowJob job)
 {
     return(new PSWorkflowApplicationInstance(this.Runtime, definition, metadata, pipelineInput, job));
 }
コード例 #10
0
        static void Main(string[] args)
        {
            // Creat a variable for the workflow path.
            string workflowFileName = "SampleWorkflow.xaml";
            // Specify the database server name and instace before executing this command.
            string dbServer = "ServerName\\InstanceName";
            string database = "M3PExtendedStore";

            // Read the XAML into the variable
            string xaml = File.ReadAllText(workflowFileName);

            string conString = GetConnectionString(dbServer, database);

            // Create a runtime to host the application, passing the custom configuration provider.
            PSWorkflowRuntime runtime = new PSWorkflowRuntime(new SampleConfigurationProvider(conString));

            // Parameters to the workflow can be provided in this dictionary
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            // Create the job, providing the XAML definition.
            PSWorkflowJob job = runtime.JobManager.CreateJob(Guid.NewGuid(), xaml, "Get-CurrentProcess", "SampleWorkflow", parameters);

            // Subscribe to the state change event before starting the job.
            AutoResetEvent wfEvent = new AutoResetEvent(false);

            job.StateChanged += delegate(object sender, JobStateEventArgs e)
            {
                switch (e.JobStateInfo.State)
                {
                case JobState.Failed:
                case JobState.Completed:
                case JobState.Suspended:
                {
                    wfEvent.Set();
                }
                break;
                }
            };

            // Start the job
            job.StartJob();

            // Wait for the state changes event
            wfEvent.WaitOne();

            // Check whether the workflow is in the suspended state.
            if (job.JobStateInfo.State == JobState.Suspended)
            {
                Console.WriteLine("The job has suspended successfully.");
            }
            else
            {
                // If not, inform the user that the job was not suspended.
                Console.WriteLine("The job has not reached a desired state.");
                Console.ReadLine();
                return;
            }


            Console.WriteLine("Resuming the job.");
            // Resume
            job.ResumeJob();

            // Wait for the state changes event
            wfEvent.WaitOne();

            // The workfow should be completed
            if (job.JobStateInfo.State == JobState.Completed)
            {
                Console.WriteLine("The job has completed successfully.");
                Console.WriteLine("Total Process found: " + job.PSWorkflowInstance.Streams.OutputStream.Count);
            }
            else
            {
                Console.WriteLine("The job has Failed.");
            }

            Console.WriteLine("Press <Enter> to continue...");
            Console.ReadLine();
        }
コード例 #11
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);
            }
        }
コード例 #12
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");
     }
 }
コード例 #13
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");
     }
 }