Compartir a través de


How to Synchronously Run a Management Pack Task

Applies To: Operations Manager 2007 R2, Operations Manager 2007 SP1, System Center Operations Manager 2007

Operations Manager Management Pack tasks can run in either a synchronous or an asynchronous mode. When an SDK client runs a task in a synchronous mode, the task runs in the client's thread. This requires the client to delay until the task is complete.

Example

The following example demonstrates how to synchronously run a task to get the names of rules and monitors that are running on a specific agent-managed computer.

/// <summary>
/// Synchronously runs a task to get a list of 
/// rules or monitors running on a specific agent-managed computer.
/// </summary>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Administration;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.Monitoring;
using System.Xml;
using System.Text;

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

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

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

            MonitoringTaskCriteria taskCriteria = new MonitoringTaskCriteria(query);
            ReadOnlyCollection<MonitoringTask> tasks =
                mg.GetMonitoringTasks(taskCriteria);
            MonitoringTask 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.Agent'";
            MonitoringClassCriteria criteria = new MonitoringClassCriteria(query);

            ReadOnlyCollection<MonitoringClass> classes = 
                mg.GetMonitoringClasses(criteria);
            if (classes.Count != 1)
                throw new InvalidOperationException(
                    "Error! Expected one class with: " + query);

            // Create a MonitoringObject list containing a specific agent (the 
            // target of the task).
            string fullAgentName = "EnterFullyQualifiedAgentNameHere";
            List<MonitoringObject> targets = new List<MonitoringObject>();
            query = "DisplayName = '" + fullAgentName + "'";
            MonitoringObjectCriteria targetCriteria = 
                new MonitoringObjectCriteria(query, classes[0]);
            targets.AddRange(mg.GetMonitoringObjects(targetCriteria));
            if (targets.Count != 1)
                throw new InvalidOperationException(
                    "Error! Expected one target.");

            // Use the default task configuration.
            MonitoringTaskConfiguration config = new MonitoringTaskConfiguration();

            // Run the task.
            Console.WriteLine("Starting task \"" +
                task.DisplayName + "\" on the following target: ");
            foreach (MonitoringObject target in targets)
            {
                Console.WriteLine(target.DisplayName);
            }
            Console.WriteLine("Task started.");
            ReadOnlyCollection<MonitoringTaskResult> results = 
                mg.ExecuteMonitoringTask(targets, task, config);
            if (results.Count == 0)
                throw new InvalidOperationException(
                    "Failed to return any results.");

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

                    // Convert the task Output element from a string to XML.
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(res.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);
                    }
                }
            }
        }
    }
}
' Synchronously runs a task to get a list of 
' rules or monitors running on a specific agent-managed computer.
Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports Microsoft.EnterpriseManagement
Imports Microsoft.EnterpriseManagement.Administration
Imports Microsoft.EnterpriseManagement.Common
Imports Microsoft.EnterpriseManagement.Configuration
Imports Microsoft.EnterpriseManagement.Monitoring
Imports System.Xml
Imports System.Text

Namespace SDKSamples
    Class Program
        Public Overloads Shared Function Main(ByVal args() As String) As Integer

            Dim mg As ManagementGroup = New ManagementGroup("localhost")

            Console.WriteLine("Synchronously running a Management Pack task...")

            ' Get the task.
            Dim query As String = "DisplayName = 'Show running rules and monitors for this health service'"

            Dim taskCriteria As MonitoringTaskCriteria = New MonitoringTaskCriteria(query)
            Dim tasks As ReadOnlyCollection(Of MonitoringTask) = _
                mg.GetMonitoringTasks(taskCriteria)
            Dim task As MonitoringTask = Nothing
            If (tasks.Count = 1) Then
                task = tasks(0)
            else
                Throw New InvalidOperationException( _
                    "Error! Expected one task with: " & query)
            End If

            ' Get the agent class.
            query = "Name = 'Microsoft.SystemCenter.Agent'"
            Dim criteria As MonitoringClassCriteria = New MonitoringClassCriteria(query)

            Dim classes As ReadOnlyCollection(Of MonitoringClass) = _
                mg.GetMonitoringClasses(criteria)
            If (classes.Count <> 1) Then
                Throw New InvalidOperationException( _
                    "Error! Expected one class with: " & query)
            End If

            ' Create a MonitoringObject list containing a specific agent (the 
            ' target of the task).
            Dim fullAgentName As String = "EnterFullyQualifiedAgentNameHere"
            Dim targets As List(Of MonitoringObject) = New List(Of MonitoringObject)()
            query = "DisplayName = '" & fullAgentName & "'"
            Dim targetCriteria As MonitoringObjectCriteria = _
                New MonitoringObjectCriteria(query, classes(0))
            targets.AddRange(mg.GetMonitoringObjects(targetCriteria))
            If (targets.Count <> 1) Then
                Throw New InvalidOperationException( _
                    "Error! Expected one target.")
            End If

            ' Use the default task configuration.
            Dim config As MonitoringTaskConfiguration = New MonitoringTaskConfiguration()

            ' Run the task.
            Console.WriteLine("Starting task """ & _
                task.DisplayName & """ on the following target: ")

            For Each target As MonitoringObject In targets

                Console.WriteLine(target.DisplayName)
            Next

            Console.WriteLine("Task started.")
            Dim results As ReadOnlyCollection(Of MonitoringTaskResult) = _
                mg.ExecuteMonitoringTask(targets, task, config)
            If (results.Count = 0) Then
                Throw New InvalidOperationException( _
                    "Failed to return any results.")
            End If

            ' Display the task results.
            Dim resultNo As Integer = 0
            For Each res As MonitoringTaskResult In results

                resultNo = resultNo + 1
                If (res.Status = TaskStatus.Failed) Then

                    Console.WriteLine("Target #" & resultNo & " failed.")
                    Console.WriteLine("Reason: " & res.ErrorCode.Value)

                Else

                    Console.WriteLine("Target #" & resultNo & " succeeded.")

                    ' Convert the task Output element from a string to XML.
                    Dim xmlDoc As XmlDocument = New XmlDocument()
                    xmlDoc.LoadXml(res.Output)

                    ' Parse and display the output.
                    Dim xPathQry As String = "/DataItem/Count"
                    Dim countNode As XmlNode = xmlDoc.SelectSingleNode(xPathQry)
                    Console.WriteLine("Target contains " & countNode.InnerText & " running rules or monitors.")
                    xPathQry = "//Workflow"

                    Dim instanceList As XmlNodeList = xmlDoc.SelectNodes(xPathQry)
                    Dim cnt As Integer = 0
                    For Each thisInstance As XmlNode In instanceList

                        cnt = cnt + 1
                        Console.WriteLine(cnt.ToString() & ". " & thisInstance.InnerText)
                    Next
                End If
            Next
        End Function
    End Class
End Namespace

See Also

Tasks

How to Asynchronously Run a Management Pack Task