How To Programmatically Get Related Objects

A question that comes up fairly often is how to programmatically determine which objects are related to another object. An example of this is: “How do I get the members of a group?”

Here is a quick code sample that shows how to do this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.EnterpriseManagement;

using Microsoft.EnterpriseManagement.Common;

using Microsoft.EnterpriseManagement.Configuration;

 

namespace GetObjectsInGroup

{

class Program

{

static void Main(string[] args)

{

EnterpriseManagementGroup emg = new EnterpriseManagementGroup(“localhost”);

// Note: You’ll need to get a GUID that makes sense in your deployment to put in here. You can get this from the BaseManagedEntityTable.

// Make sure for this example code to work that you choose an object which contains other objects like a group or a Windows computer.

Guid guidObjectID = new Guid(“2D7968F7-2AE7-6CE2-6273-54D110A35A8A”);

ManagementPack mpSystem = emg.ManagementPacks.GetManagementPack(SystemManagementPack.System);

ManagementPackRelationship relContainment = mpSystem.GetRelationship(“System.Containment”);

TraversalDepth tdRecursive = TraversalDepth.Recursive;

IList<EnterpriseManagementObject> listContainedObjects = emg.EntityObjects.GetRelatedObjects<EnterpriseManagementObject>(guidObjectID, relContainment, tdRecursive, ObjectQueryOptions.Default);

foreach (EnterpriseManagementObject emo in listContainedObjects)

{

Console.WriteLine(emo.DisplayName);

}

}

}

}

 

The key to this is the GetRelatedObjects() method. There are 10 overloads for this method so there are lots of different ways to query. You can filter by relationship type as I did above or by class. You can even use property level criteria.

 

Example command line application can be found here:

http://cid-17faa48294add53f.office.live.com/self.aspx/.Public/Examples/GetObjectsInGroup.zip