How to Asynchronously Run a Management Pack Task

Applies To: System Center 2012 - Operations Manager

[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

Operations Manager management pack tasks can run in either a synchronous mode or an asynchronous mode. When a software development kit (SDK) client application runs a task in an asynchronous mode, the task runs in a separate thread. This enables the client to perform other operations while the task is running.

Example

The following example demonstrates how to asynchronously run a task to get the names of the rules and monitors that are running on all agent-managed computers in the management group:

/// <summary>
/// Asynchronously runs a task to get a list of all 
/// running rules or monitors on all agent-managed
/// computers in the Management Group.
/// </summary>
using System;
using System.Xml;
using System.Collections.Generic;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.Monitoring;



namespace SDKSamples
{
    class Program
    {
        public static ManagementGroup mg = null;

        static void Main(string[] args)
        {
            mg = new ManagementGroup("localhost");

            Console.WriteLine("Asynchronously running a Management Pack task...");

            // Get the task.
            string query = "DisplayName = 'Show running rules and monitors for this health service'";
            ManagementPackTaskCriteria taskCriteria = new ManagementPackTaskCriteria(query);

            IList<ManagementPackTask> tasks = mg.TaskConfiguration.GetTasks(taskCriteria);
            ManagementPackTask task = null;
            if (tasks.Count == 1)
                task = tasks[0];
            else
                throw new InvalidOperationException(
                    "Error! Expected one task with: " + query);

            // Get the agent class.
            query = "Name = 'Microsoft.SystemCenter.ManagementServer'";
            ManagementPackClassCriteria criteria = new ManagementPackClassCriteria(query);
            IList<ManagementPackClass> classes = mg.EntityTypes.GetClasses(criteria);
            if (classes.Count != 1)
                throw new InvalidOperationException(
                    "Error! Expected one class with: " + query);

            // Create a MonitoringObject list containing all agents (the 
            // targets of the task).
            List<MonitoringObject> targets = new List<MonitoringObject>();
            IObjectReader<MonitoringObject> reader = mg.EntityObjects.GetObjectReader<MonitoringObject>(classes[0], ObjectQueryOptions.Default);
            targets.AddRange(reader);
            if (targets.Count < 1)
                throw new InvalidOperationException(
                    "Error! Expected at least one target.");

            // Use the default task configuration.
            Microsoft.EnterpriseManagement.Runtime.TaskConfiguration config = new Microsoft.EnterpriseManagement.Runtime.TaskConfiguration();

            // Run the task.
            Console.WriteLine("Starting task \"" + task.DisplayName +
                "\" on the following targets: ");
            foreach (MonitoringObject target in targets)
            {
                Console.WriteLine(target.DisplayName);
            }

            object state = null;
            IAsyncResult result = mg.TaskRuntime.BeginExecuteTask(targets, task, config, new Program().OnAsyncTaskCallback, state);
            Console.WriteLine("Task started on " + targets.Count + " targets.");

            // Perform some operation while the tasks run, and wait for
            // the task results.
            System.Threading.Thread.Sleep(30000);

        }

        // The callback function is automatically called when the task is 
        // complete.
        private void OnAsyncTaskCallback(IAsyncResult result)
        {
            Console.WriteLine("OnAsyncTaskCallback started.");
           
            // Get the task results.
            IList<Microsoft.EnterpriseManagement.Runtime.TaskResult> results = mg.TaskRuntime.EndExecuteTask(result);
            if (results.Count == 0)
                throw new InvalidOperationException("Error! Failed to return any results.");

            // Display the task results.
            int resultNo = 0;
            foreach (Microsoft.EnterpriseManagement.Runtime.TaskResult taskResult in results)
            {
                resultNo++;
                if (taskResult.Status == Microsoft.EnterpriseManagement.Runtime.TaskStatus.Failed)
                {
                    Console.WriteLine("Target #" + resultNo + " failed.");
                    Console.WriteLine("Reason: " + taskResult.ErrorCode.Value);
                }
                else
                {
                    Console.WriteLine("Target #" + resultNo + " succeeded.");

                    // Convert the task Output element from a string to XML.
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(taskResult.Output);

                    // Parse and display the output.
                    string xPathQry = @"/DataItem/Count";
                    System.Xml.XmlNode countNode = xmlDoc.SelectSingleNode(xPathQry);
                    Console.WriteLine("Target contains " + countNode.InnerText + " running rules or monitors.");
                    xPathQry = @"//Workflow";
                    System.Xml.XmlNodeList instanceList = xmlDoc.SelectNodes(xPathQry);
                    int cnt = 0;
                    foreach (System.Xml.XmlNode thisInstance in instanceList)
                    {
                        cnt++;
                        Console.WriteLine(cnt.ToString() + ". " + thisInstance.InnerText);
                    }
                }
            }
        }
    }
}

See Also

Tasks

How to Synchronously Run a Management Pack Task

Other Resources

How to Run a Management Pack Task