C# code snippets for Service Manager #1

This post contains a few code snippets for some of the things you might want to do with System Center Service Manager using C#. Hopefully these would be of use to anyone who is new to the SDK and wants to start out creating custom console tasks and workflows. These will work on both 2010 and 2012.

Basic References

Obtained from Management Server “C:\Program Files\Microsoft System Center\Service Manager 2010\SDK Binaries” or “C:\Program Files\Microsoft System Center\Service Manager 2012\SDK Binaries” and “C:\Program Files\Microsoft System Center\Service Manager 2010″ or “C:\Program Files\Microsoft System Center\Service Manager 2012″. There is no separate download for the SCSM SDK, it’s part of the actual product. Some examples below require additional references.

Basic using statements

using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;

Connecting to a Management Server

EnterpriseManagementGroup emg = new EnterpriseManagementGroup("yourscsmserver");

Getting a Management Pack and Class reference via Guid

//Get the system.workitem class                        
ManagementPackClass mpcWorkitem = emg.EntityTypes.GetClass(new Guid("f59821e2-0364-ed2c-19e3-752efbb1ece9"));

//Get system.workitem.library mp
ManagementPack mpWorkitem = emg.ManagementPacks.GetManagementPack(new Guid("405d5590-b45f-1c97-024f-24338290453e"));

Getting a Management Pack and Class reference via Name

//Get the incident MP (System.WorkItem.Incident.Library)
ManagementPack mpIncident = emg.ManagementPacks.GetManagementPack("System.WorkItem.Incident.Library", "31bf3856ad364e35", new Version(1, 0, 0, 0));

//Get the incident class from the MP (System.WorkItem.Incident)
ManagementPackClass mpcIncident = mpIncident.GetClass("System.WorkItem.Incident");

Search for a Work Item by Id and return an EnterpriseManagementObject

//Get the system.workitem class                        
ManagementPackClass mpcWorkitem = emg.EntityTypes.GetClass(new Guid("f59821e2-0364-ed2c-19e3-752efbb1ece9"));

//Get system.workitem.library mp
ManagementPack mpWorkitem = emg.ManagementPacks.GetManagementPack(new Guid("405d5590-b45f-1c97-024f-24338290453e"));

string strIncidentSearchCriteria = "";
       
//Attempt to get results for single workitem
strIncidentSearchCriteria = String.Format(@"<Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/"">" +
                "<Expression>" +
                "<SimpleExpression>" +
                    "<ValueExpressionLeft>" +
                    "<Property>$Context/Property[Type='System.WorkItem']/Id$</Property>" +
                    "</ValueExpressionLeft>" +
                    "<Operator>Equal</Operator>" +
                    "<ValueExpressionRight>" +
                    "<Value>" + sId + "</Value>" +
                    "</ValueExpressionRight>" +
                "</SimpleExpression>" +
                "</Expression>" +
            "</Criteria>");
         
EnterpriseManagementObjectCriteria emocWorkitem = new EnterpriseManagementObjectCriteria((string)strIncidentSearchCriteria, mpcWorkitem, mpWorkitem, emg);
IObjectReader<EnterpriseManagementObject> readerWorkitem = emg.EntityObjects.GetObjectReader<EnterpriseManagementObject>(emocWorkitem, ObjectQueryOptions.Default);
EnterpriseManagementObject emoWorkItem = readerWorkitem.ElementAt(0);

Setting an Incident Status to Closed

string sClosedStatusGuid = "bd0ae7c4-3315-2eb3-7933-82dfc482dbaf";
emoIncident[mpcIncident, "Status"].Value = new Guid(sClosedStatusGuid);
emoIncident[mpcIncident, "ClosedDate"].Value = DateTime.UtcNow;

//OR

ManagementPackEnumeration mpeIRClosed = emg.EntityTypes.GetEnumeration(new Guid("bd0ae7c4-3315-2eb3-7933-82dfc482dbaf"));
emoIncident[mpcIncident, "Status"].Value = mpeIRClosed;
emoIncident[mpcIncident, "ClosedDate"].Value = DateTime.UtcNow;

//Save
emoIncident.Commit(); //I normally use this for console tasks 

//OR
emoIncident.Overwrite(); //I normally use this for workflows 

Creating an SMTP address for a user CI object

//emoUser already contains your user as EnterpriseManagementObject
//emg is an already connected EnterpriseManagementGroup
//sSMTP contains your SMTP address to add

//Get the notifications MP
ManagementPack mpNotifications = emg.ManagementPacks.GetManagementPack(new Guid("8e02a0aa-04b1-812b-6ab5-1c12e3288e99"));

//Get the Subscriber Address class
ManagementPackClass mpcNotification = emg.EntityTypes.GetClass("System.Notification.Endpoint", mpNotifications);

//Get the Has Preference (System.SupportingItem.Library) relationship
ManagementPackRelationship relNotification =
    emg.EntityTypes.GetRelationshipClass(new Guid("649e37ab-bf89-8617-94f6-d4d041a05171"));

//Create new relationship
CreatableEnterpriseManagementRelationshipObject cemroNotification =
    new CreatableEnterpriseManagementRelationshipObject(emg, relNotification);

//Create a new notification endpoint
CreatableEnterpriseManagementObject cemoNotification = new CreatableEnterpriseManagementObject(emg, mpcNotification);

//Setup the properties for the new notification object
cemoNotification[mpcNotification, "Id"].Value = Guid.NewGuid().ToString();
cemoNotification[mpcNotification, "ChannelName"].Value = "SMTP";
cemoNotification[mpcNotification, "DisplayName"].Value = "SMTPAddress";
cemoNotification[mpcNotification, "TargetAddress"].Value = sSMTP;
cemoNotification[mpcNotification, "Description"].Value = "SMTPAddress";

cemroNotification.SetSource(emoUser);
cemroNotification.SetTarget(cemoNotification);
cemroNotification.Commit();

Adding an Attachment to a Work Item

//System.SupportingItem.Library
ManagementPack mpSupporting =
    emg.ManagementPacks.GetManagementPack(new Guid("23e3ae8e-1981-8560-2e55-8730cbc04965"));

//Get the System.FileAttachment class
ManagementPackClass mpcAttachment = emg.EntityTypes.GetClass("System.FileAttachment", mpSupporting);

//Get attachment details
string sExt = Path.GetExtension(sFile);
string sAttachmentName = Path.GetFileNameWithoutExtension(sFile);

//Create new stream and read file into memory
MemoryStream ms = new MemoryStream();

using (FileStream fs = File.OpenRead(sFile))
{
    ms.SetLength(fs.Length);
    fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
}

//Did we get any data?
if (ms != null && ms.Length != 0)
{
    //Reset stream position
    ms.Position = 0;

    //Create a new attachment
    CreatableEnterpriseManagementObject cemoAttachment = new CreatableEnterpriseManagementObject(emg, mpcAttachment);

    //Create a new attachment relationship
    ManagementPackRelationship relAttachment =
    emg.EntityTypes.GetRelationshipClass(new Guid("aa8c26dc-3a12-5f88-d9c7-753e5a8a55b4"));
    CreatableEnterpriseManagementRelationshipObject cemroAttachment =
        new CreatableEnterpriseManagementRelationshipObject(emg, relAttachment);

    //Create a new added by user relationship
    ManagementPackRelationship relAddedByUser =
    emg.EntityTypes.GetRelationshipClass(new Guid("ffd71f9e-7346-d12b-85d6-7c39f507b7bb"));
    CreatableEnterpriseManagementRelationshipObject cemroAddedByUser =
        new CreatableEnterpriseManagementRelationshipObject(emg, relAddedByUser);

    //Set properties of attachment
    string sFileName = sAttachmentName;
    if (sExt != "") sFileName += "." + sExt;
    cemoAttachment[mpcAttachment, "AddedDate"].Value = DateTime.UtcNow;
    cemoAttachment[mpcAttachment, "DisplayName"].Value = sFileName;
    cemoAttachment[mpcAttachment, "Extension"].Value = sExt;
    cemoAttachment[mpcAttachment, "Content"].Value = ms;
    cemoAttachment[mpcAttachment, "Size"].Value = ms.Length;
    cemoAttachment[mpcAttachment, "Description"].Value = sFileName;
    cemoAttachment[mpcAttachment, "Id"].Value = Guid.NewGuid().ToString();

    //Set the source and target for the attachment and save (this must be done first)
    cemroAttachment.SetSource(emoWorkItem);
    cemroAttachment.SetTarget(cemoAttachment);
    cemroAttachment.Commit();

    //Set the added by user relationship (this must done after the previous relationship)
    cemroAddedByUser.SetSource(cemoAttachment);
    cemroAddedByUser.SetTarget(emoUser);
    cemroAddedByUser.Commit();
}

Listing all the Type Projections in a Management Group

foreach (ManagementPackTypeProjection mptp in emg.EntityTypes.GetTypeProjections())
{
     Console.WriteLine(mptp.DisplayName + " " + mptp.Id.ToString());
}

Deleting a Work Item

//Requires using Microsoft.EnterpriseManagement.ConnectorFramework;
IncrementalDiscoveryData idd = new IncrementalDiscoveryData();
idd.Remove(emoWorkItem);
idd.Commit(emg);

Returning the Guid of an Incident Classification Enumeration by Display Name

//Incident class top parent enum guid
Guid gClassParent = new Guid("1f77f0ce-9e43-340f-1fd5-b11cc36c9cba");
sClassDisplayName = sClassDisplayName.ToLower();

foreach (ManagementPackEnumeration mpeClass in emg.EntityTypes.GetChildEnumerations(gClassParent, TraversalDepth.Recursive))
{
    if (mpeClass.DisplayName.ToLower() == sClassDisplayName) return mpeClass.Id.ToString();
}

Reading Manual Activity History records to determine the last modified by user

//Get the last modified user from the newest history record
//emoMA contains a Manual Activity as EnterpriseManagementObject
IList<EnterpriseManagementObjectHistoryTransaction> listHistory = emg.EntityObjects.GetObjectHistoryTransactions(emoMA);
string sDomainUserName = "";

foreach (EnterpriseManagementObjectHistoryTransaction emoht in listHistory.OrderByDescending(e => e.DateOccurred))
{
    //This will be the most recent history entry so get the username involved
    sDomainUserName = emoht.UserName;
    break;
}

How to find the current Assigned To User relationship for a Work Item

//Assigned to user relationship Guid
Guid rel = new Guid("15e577a3-6bf9-6713-4eac-ba5a5b7c4722");

EnterpriseManagementObject emoAssignedToUser = null;

foreach (EnterpriseManagementRelationshipObject<EnterpriseManagementObject> obj in
    emg.EntityObjects.GetRelationshipObjectsWhereSource<EnterpriseManagementObject>(emoWorkItem.Id, TraversalDepth.OneLevel, ObjectQueryOptions.Default))
{
    if (obj.RelationshipId == rel)
        emoAssignedToUser = obj.TargetObject;
}

Programmatically determine Work Item Prefixes from Admin Settings

//Get the incident settings class
ManagementPackClass mpcIncidentSettings = emg.EntityTypes.GetClass(new Guid("613c9f3e-9b94-1fef-4088-16c33bfd0be1"));

//Get activity settings class
ManagementPackClass mpcActivitySettings = emg.EntityTypes.GetClass(new Guid("5e04a50d-01d1-6fce-7946-15580aa8681d"));

//Get the problem settings class
ManagementPackClass mpcProblemSettings = emg.EntityTypes.GetClass(new Guid("da0eeac9-9c85-e72b-f321-44a3fcec9c9a"));

//Get the CR settings class
ManagementPackClass mpcCRSettings = emg.EntityTypes.GetClass(new Guid("c7fe33bb-9760-3f88-59fc-0951e3221be4"));

//Settings EMOs

//Get the emo for the incident settings
EnterpriseManagementObject emoIncidentSettings = emg.EntityObjects.GetObject<EnterpriseManagementObject>(mpcIncidentSettings.Id, ObjectQueryOptions.Default);

//Get the emo for the activity settings
EnterpriseManagementObject emoActivitySettings = emg.EntityObjects.GetObject<EnterpriseManagementObject>(mpcActivitySettings.Id, ObjectQueryOptions.Default);

//Get the emo for the problem settings
EnterpriseManagementObject emoProblemSettings = emg.EntityObjects.GetObject<EnterpriseManagementObject>(mpcProblemSettings.Id, ObjectQueryOptions.Default);

//Get the emo for the CR settings
EnterpriseManagementObject emoCRSettings = emg.EntityObjects.GetObject<EnterpriseManagementObject>(mpcCRSettings.Id, ObjectQueryOptions.Default);

//Get the Id Prefix lengths
string sIRPrefix = emoIncidentSettings[mpcIncidentSettings, "PrefixForId"].Value.ToString();
string sRAPrefix = emoActivitySettings[mpcActivitySettings, "SystemWorkItemActivityReviewActivityIdPrefix"].Value.ToString();
string sMAPrefix = emoActivitySettings[mpcActivitySettings, "SystemWorkItemActivityManualActivityIdPrefix"].Value.ToString();
string sPRPrefix = emoProblemSettings[mpcProblemSettings, "ProblemIdPrefix"].Value.ToString();
string sCRPrefix = emoCRSettings[mpcCRSettings, "SystemWorkItemChangeRequestIdPrefix"].Value.ToString();

Now see C# code snippets for Service Manager #2.

This entry was posted in Code and tagged , , . Bookmark the permalink.