Creating (or Editing) an Object From a Template Programmatically

Published Feb 15 2019 04:18 AM 48 Views
First published on TECHNET on Nov 07, 2010

Sorry I haven’t been blogging in a while. I’ve been on a whirlwind tour around South Africa and Europe for the last three weeks presenting about Service Manager in one forum or another essentially every day.  It’s been exciting, but hasn’t left a lot of time for blogging.


I just needed to write some code today and had this question come up from our internal distribution list so I thought I would take a minute to answer it.  The question was how to create a new change request (or any object really) from a template programmatically.


Here you go:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;



namespace ApplyTemplate
{
class Program
{
static void Main(string[] args)
{
EnterpriseManagementGroup emg = new EnterpriseManagementGroup("localhost");

//You'll need to get the ObjectTemplateId GUID from the database after you have created it. You can find it on the ObjectTemplate table by running a query like this:
/*
select MP.MPName,OT.* from ObjectTemplate as OT, ManagementPack as MP order by MP.MPName, OT.ObjectTemplateName
*/
ManagementPackObjectTemplate mpt = emg.Templates.GetObjectTemplate(new Guid("8B1AA102-F8A5-07D0-FC9A-2DB2A4FD5003")); // <-- TODO: YOU'LL NEED TO REPLACE THIS GUID - SEE ABOVE

//This is how you apply a template to a new object projection you want to create:
EnterpriseManagementObjectProjection emop = new EnterpriseManagementObjectProjection(emg, mpt);
emop.Overwrite();

//This is how you apply a class-targeted template to an object.
/*
ManagementPackClass classChangeRequest = emg.EntityTypes.GetClass(new Guid("E6C9CF6E-D7FE-1B5D-216C-C3F5D2C7670C"));
CreatableEnterpriseManagementObject cemo = new CreatableEnterpriseManagementObject(emg, classChangeRequest);
cemo.ApplyTemplate(mpt);
cemo.Commit();
*/
}
}
}

You can also call the .ApplyTemplate() method on a EnterpriseManaegmentObject or a EnterpriseManagementObjectProjection to update an object/projection that already exists.




The source code is attached in a Visual Studio application.


ApplyTemplate.zip

Version history
Last update:
‎Mar 11 2019 08:35 AM
Updated by: