private void LoadFormDataTimerTypeEnums(EnterpriseManagementObject emoActivity) { //Load our list of Timer Type enumerations var emg = emoActivity.ManagementGroup; var mpcTimerActivity = emoActivity.GetLeastDerivedNonAbstractClass().GetManagementPack(); var enumTimerDelayTypeRootEnum = emg.EntityTypes.GetEnumeration("TimeDelayTypeEnum", mpcTimerActivity); //The room enum. var ilistEnumTimerTypes = (emg.EntityTypes.GetChildEnumerations(enumTimerDelayTypeRootEnum.Id, TraversalDepth.Recursive)).OrderBy(x => x.Ordinal); ObservableCollection <ManagementPackEnumeration> ocEnumerations = new ObservableCollection <ManagementPackEnumeration>(ilistEnumTimerTypes); this.timeDurationTypeSource = ocEnumerations; //Set the selected value that was previously saved, if it exists. if (ocEnumerations.Count > 0) { //And also select the template that was previously saved on the activity. ManagementPackEnumeration mpeSavedEnum = GetEnumerationFromEmoProperty(emoActivity, "TimeDelayType_Enum"); //might be null ManagementPackEnumeration matchingEnum = null; if (mpeSavedEnum != null) { matchingEnum = this.timeDurationTypeSource.Where(x => x.Name == mpeSavedEnum.Name).FirstOrDefault(); } if (matchingEnum != null) { this.selectedDurationType = matchingEnum; //And select our current value that is saved on the form. //this.SelectedNotificationTemplateDescription = matchingNotificationTemplate.templateDescription; } } }
private static void CreateQueue(ManagementPackClass mpc, ManagementPackEnumeration mpe, string strMPAlias, ManagementPackProperty mpp, ref ManagementPack mp, EnterpriseManagementGroup emg) { string strQueueDisplayName = String.Format("{0}: {1}", mpc.DisplayName, mpe.DisplayName); string strCriteria = ConstructCriteria(strMPAlias, mpc, mpp, mpe); Helper.CreateQueue(strQueueDisplayName, Helper.MakeMPElementSafeName(strQueueDisplayName), strCriteria, mpc, ref mp, emg); }
protected override void BeginProcessing() { // the base.BeginProcesing must come first as it sets up the enterprisemanagementgroup! base.BeginProcessing(); ManagementPackClass clsAnnouncement = SMHelpers.GetManagementPackClass(ClassTypes.System_Announcement_Item, SMHelpers.GetManagementPack(ManagementPacks.System_AdminItem_Library, _mg), _mg); // Compare the string case insenstively if (_Priority != null) { if (String.Compare(_Priority, "low", true) == 0) { enumPriority = SMHelpers.GetEnum(Enumerations.System_Announcement_PriorityEnum_Low, _mg); } else if (String.Compare(_Priority, "critical", true) == 0) { enumPriority = SMHelpers.GetEnum(Enumerations.System_Announcement_PriorityEnum_Critical, _mg); } else if (String.Compare(_Priority, "medium", true) == 0) { enumPriority = SMHelpers.GetEnum(Enumerations.System_Announcement_PriorityEnum_Medium, _mg); } else { ThrowTerminatingError(new ErrorRecord(new ArgumentException("Priority"), "Priority must be low/medium/critical", ErrorCategory.InvalidOperation, _Priority)); } } }
public static string SearchObjectByEnumerationCriteriaXml(ManagementPackEnumeration mpe, ManagementPackClass mpc, ManagementPackProperty mpp) { ManagementPack mp = mpc.GetManagementPack(); string strMPName = MakeSafeXML(mp.Name); string strMPVersion = MakeSafeXML(mp.Version.ToString()); string strMPPublicKeyToken = MakeSafeXML(mp.KeyToken); string strClassName = MakeSafeXML(mpc.Name); string strPropertyName = MakeSafeXML(mpp.Name); // This is XML that validates against the Microsoft.EnterpriseManagement.Core.Criteria schema. string strCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""{0}"" Version=""{1}"" PublicKeyToken=""{2}"" Alias=""MP"" /> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='MP!{3}']/{4}$</Property> </ValueExpressionLeft> <Operator>Equal</Operator> <ValueExpressionRight> <Value>{{{5}}}</Value> </ValueExpressionRight> </SimpleExpression> </Expression> </Criteria> ", strMPName, strMPVersion, strMPPublicKeyToken, strClassName, strPropertyName, mpe.Id.ToString()); return(strCriteria); }
//Get tier children for passed tier private void AddTierChildren( ManagementPackEnumeration mpe, ComboBox cbox, ComboBox cboxguids, string sSpacer, string s ) { try { ManagementPackEnumerationCriteria mpenumCriteriaKids = new ManagementPackEnumerationCriteria("Parent = '" + mpe.Id.ToString() + "'"); IList <ManagementPackEnumeration> listEnumTierKids = emg.EntityTypes.GetEnumerations(mpenumCriteriaKids); //Sort by ordinal IEnumerable <ManagementPackEnumeration> tiers = listEnumTierKids.OrderBy(x => x.Ordinal); //Add children (we don't curently have any further levels) foreach (ManagementPackEnumeration mpenumTierKids in tiers) { cbox.Items.Add(sSpacer + mpenumTierKids.DisplayName); cboxguids.Items.Add(mpenumTierKids.Id.ToString()); AddTierChildren(mpenumTierKids, cbox, cboxguids, sSpacer + " ", s); } } catch { } }
private static void CreateAddNotificationRule(ManagementPackClass mpc, ManagementPackEnumeration mpe, string strMPAlias, ManagementPackProperty mpp, ref ManagementPack mp, EnterpriseManagementObject emoUser, ManagementPackObjectTemplate mpot, EnterpriseManagementGroup emg) { string strRuleDisplayName = String.Format("{0}: Add: {1}", mpc.DisplayName, mpe.DisplayName); string strCriteria = ConstructAddCriteria(strMPAlias, mpc, mpp, mpe); Helper.CreateNotificationRule(strRuleDisplayName, Helper.MakeMPElementSafeName(strRuleDisplayName), strCriteria, emoUser, mpc, mpot, ref mp, emg); }
private ManagementPackEnumeration CreateEnumeration(string strName, ref ManagementPackEnumeration mpeBase, ref ManagementPack mpNew) { ManagementPackEnumeration mpeNew = new ManagementPackEnumeration(mpNew, strName, ManagementPackAccessibility.Public); mpeNew.Parent = mpeBase; mpeNew.DisplayName = String.Format("Test Value {0}", strName); iNumberOfEnumsCreated++; return(mpeNew); }
private static void DoSomeProblemWork() { DateTime dtProblemWorkStart = DateTime.Now; int intRadomClassification = Helper.GetRandomNumber(0, listProblemClassificationEnums.Count); ManagementPackEnumeration mpeRandomClassification = listProblemClassificationEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRadomClassification); string strClassificationCriteriaXml = Helper.SearchObjectByEnumerationCriteriaXml(mpeRandomClassification, mpcProblem, mppProblemClassification); IObjectProjectionReader <EnterpriseManagementObject> oprProblemView = Helper.GetBufferedObjectProjectionReader(strClassificationCriteriaXml, intNumberOfWorkItemsToGet, mptpProblemView, emg); if (oprProblemView == null) { Console.WriteLine("No objects to retrieve given the criteria"); } else { //Get a particular problem (full projection) and update it by adding an action log entry and string strProblemId = null; if (oprProblemView.Count > 0) { strProblemId = oprProblemView.ElementAtOrDefault <EnterpriseManagementObjectProjection>(Helper.GetRandomNumber(0, oprProblemView.Count - 1)).Object[mpcProblem, "Id"].Value.ToString(); } if (strProblemId != null) { string strCriteriaXml = Helper.SearchWorkItemByIDCriteriaXml(strProblemId, mpSystemWorkItemLibrary.Name, mpSystemWorkItemLibrary.Version.ToString(), mpSystemWorkItemLibrary.KeyToken, "System.WorkItem"); ObjectProjectionCriteria opcProblemFull = new ObjectProjectionCriteria(strCriteriaXml, mptpProblemFull, emg); IObjectProjectionReader <EnterpriseManagementObject> oprProblemFull = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opcProblemFull, ObjectQueryOptions.Default); EnterpriseManagementObjectProjection emopProblemFull = oprProblemFull.First <EnterpriseManagementObjectProjection>(); emopProblemFull.Object[mpcProblem, "Description"].Value = Guid.NewGuid().ToString(); int intRandomEnumID = Helper.GetRandomNumber(0, listProblemClassificationEnums.Count); ManagementPackEnumeration mpeClassification = listProblemClassificationEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomEnumID); emopProblemFull.Object[mpcProblemExtension, "Classification"].Value = mpeClassification; //EnterpriseManagementObjectCriteria emocComputer = new EnterpriseManagementObjectCriteria(); ObjectQueryOptions oqoComputer = new ObjectQueryOptions(); oqoComputer.MaxResultCount = 5; oqoComputer.DefaultPropertyRetrievalBehavior = ObjectPropertyRetrievalBehavior.All; oqoComputer.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered; IObjectReader <EnterpriseManagementObject> orComputers = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(mpcComputer, oqoComputer); if (bSimulateHumanWaitTime) { Thread.Sleep(intDoWorkPause); } emopProblemFull.Overwrite(); DateTime dtProblemWorkEnd = DateTime.Now; TimeSpan tsProblemWork = dtProblemWorkEnd - dtProblemWorkStart; pcProblemWork.RawValue = (long)tsProblemWork.TotalSeconds; Console.WriteLine("Problem work completed (seconds): " + tsProblemWork.TotalSeconds); } } }
protected override void BeginProcessing() { base.BeginProcessing(); // get the BaseEnums, these are used later! impactBase = SMHelpers.GetEnum("System.WorkItem.TroubleTicket.ImpactEnum", _mg); urgencyBase = SMHelpers.GetEnum("System.WorkItem.TroubleTicket.UrgencyEnum", _mg); statusBase = SMHelpers.GetEnum("IncidentStatusEnum", _mg); classificationBase = SMHelpers.GetEnum("IncidentClassificationEnum", _mg); systemMp = _mg.ManagementPacks.GetManagementPack(SystemManagementPack.System); incidentMp = _mg.ManagementPacks.GetManagementPacks(new ManagementPackCriteria("Name = 'System.WorkItem.Incident.Library'")).First(); }
protected override void ProcessRecord() { try { ManagementPackClass clsAnnouncement = SMHelpers.GetManagementPackClass(ClassTypes.System_Announcement_Item, SMHelpers.GetManagementPack(ManagementPacks.System_AdminItem_Library, _mg), _mg); ManagementPackEnumeration enumPriority = null; switch (_Priority) { case "Low": enumPriority = SMHelpers.GetEnum(Enumerations.System_Announcement_PriorityEnum_Low, _mg); break; case "Critical": enumPriority = SMHelpers.GetEnum(Enumerations.System_Announcement_PriorityEnum_Critical, _mg); break; case "Medium": enumPriority = SMHelpers.GetEnum(Enumerations.System_Announcement_PriorityEnum_Medium, _mg); break; default: enumPriority = SMHelpers.GetEnum(Enumerations.System_Announcement_PriorityEnum_Medium, _mg); break; } CreatableEnterpriseManagementObject emo = new CreatableEnterpriseManagementObject(_mg, clsAnnouncement); emo[clsAnnouncement, "Id"].Value = System.Guid.NewGuid().ToString(); if (_DisplayName != null) { emo[clsAnnouncement, "DisplayName"].Value = _DisplayName; } emo[clsAnnouncement, "Title"].Value = _DisplayName; if (_Body != null) { emo[clsAnnouncement, "Body"].Value = _Body; } emo[clsAnnouncement, "Priority"].Value = enumPriority.Id; emo[clsAnnouncement, "ExpirationDate"].Value = _ExpirationDate; emo.Commit(); if (_passThru) { WriteObject(ServiceManagerObjectHelper.AdaptManagementObject(this, _mg.EntityObjects.GetObject <EnterpriseManagementObject>(emo.Id, ObjectQueryOptions.Default))); } } catch (Exception) { } }
public static ManagementPackEnumeration GetManagementPackEnummerationByName(string strManagementPackEnumerationName, string strManagementPackName, EnterpriseManagementGroup emg) { ManagementPackEnumeration mpeToReturn = null; ManagementPackEnumerationCriteria mpec = new ManagementPackEnumerationCriteria(String.Format("Name = '{0}'", strManagementPackEnumerationName)); foreach (ManagementPackEnumeration mpe in emg.EntityTypes.GetEnumerations(mpec)) { if (mpe.GetManagementPack().Name == strManagementPackName) { mpeToReturn = mpe; } } return(mpeToReturn); }
private void TestGettingIncidentsByEnumCriteria() { EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtServerName.Text); ManagementPack mpIncidentLibrary = Helper.GetManagementPackByName("System.WorkItem.Incident.Library", emg); ManagementPackClass mpcIncident = Helper.GetClassByName("System.WorkItem.Incident", emg); ManagementPackProperty mppClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Incident", "Classification", emg); ManagementPackTypeProjection mptpIncident = Helper.GetTypeProjectionByName("System.WorkItem.Incident.View.ProjectionType", emg); ManagementPackEnumeration mpeClassificationEnterpriseApp = Helper.GetEnumerationByName("IncidentClassificationEnum.EnterpriseApplications", emg); string strCriteria = Helper.SearchObjectByEnumerationCriteriaXml(mpeClassificationEnterpriseApp, mpcIncident, mppClassification); IObjectProjectionReader <EnterpriseManagementObject> reader = Helper.GetBufferedObjectProjectionReader(strCriteria, 40, mptpIncident, emg); MessageBox.Show(reader.Count.ToString()); }
private static void DoSomeServiceRequestWork() { DateTime dtServiceRequestWorkStart = DateTime.Now; int intRandomAreaEnum = Helper.GetRandomNumber(0, listSRAreaEnums.Count); ManagementPackEnumeration mpeRadomArea = listSRAreaEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomAreaEnum); string strCriteria = Helper.SearchObjectByEnumerationCriteriaXml(mpeRadomArea, mpcServiceRequest, mppServiceRequestArea); IObjectProjectionReader <EnterpriseManagementObject> oprServiceRequestsView = Helper.GetBufferedObjectProjectionReader(strCriteria, intNumberOfWorkItemsToGet, mptpServiceRequestView, emg); if (oprServiceRequestsView == null) { Console.WriteLine("No objects to retrieve given the criteria"); } else { //Get a particular service request (full projection) and update it by adding an action log entry and string strServiceRequestId = null; if (oprServiceRequestsView.Count > 0) { strServiceRequestId = oprServiceRequestsView.ElementAtOrDefault <EnterpriseManagementObjectProjection>(Helper.GetRandomNumber(0, oprServiceRequestsView.Count - 1)).Object[mpcServiceRequest, "Id"].Value.ToString(); } if (strServiceRequestId != null) { string strCriteriaXml = Helper.SearchWorkItemByIDCriteriaXml(strServiceRequestId, mpSystemWorkItemLibrary.Name, mpSystemWorkItemLibrary.Version.ToString(), mpSystemWorkItemLibrary.KeyToken, "System.WorkItem"); ObjectProjectionCriteria opServiceRequestFull = new ObjectProjectionCriteria(strCriteriaXml, mptpServiceRequestFull, emg); IObjectProjectionReader <EnterpriseManagementObject> oprServiceRequestFull = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opServiceRequestFull, ObjectQueryOptions.Default); EnterpriseManagementObjectProjection emopServiceRequestFull = oprServiceRequestFull.First <EnterpriseManagementObjectProjection>(); if (bSimulateHumanWaitTime) { Thread.Sleep(intDoWorkPause); } emopServiceRequestFull.Object[mpcServiceRequest, "Description"].Value = Guid.NewGuid().ToString(); int intRandomEnumId = Helper.GetRandomNumber(0, listSRAreaEnums.Count); ManagementPackEnumeration mpeArea = listSRAreaEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomEnumId); emopServiceRequestFull.Object[mpcServiceRequestExtension, "Area"].Value = mpeArea; emopServiceRequestFull.Overwrite(); DateTime dtServiceRequestWorkEnd = DateTime.Now; TimeSpan tsServiceRequestWork = dtServiceRequestWorkEnd - dtServiceRequestWorkStart; pcServiceRequestWork.RawValue = (long)tsServiceRequestWork.TotalSeconds; Console.WriteLine("Service request work completed (seconds): " + tsServiceRequestWork.TotalSeconds); } } }
//Add action log relationship to passed emo private bool AddActionLogEntry( EnterpriseManagementGroup emg, EnterpriseManagementObject emoIncident, string strTitle, string strDescription ) { try { //Get the System.WorkItem.Library mp ManagementPack mpWorkItemLibrary = emg.ManagementPacks.GetManagementPack(new Guid("405D5590-B45F-1C97-024F-24338290453E")); //Get the actionlog class ManagementPackClass typeActionLog = emg.EntityTypes.GetClass("System.WorkItem.TroubleTicket.ActionLog", mpWorkItemLibrary); //Create a new action log entry CreatableEnterpriseManagementObject objectActionLog = new CreatableEnterpriseManagementObject(emg, typeActionLog); //Setup the action log entry objectActionLog[typeActionLog, "Id"].Value = Guid.NewGuid().ToString(); objectActionLog[typeActionLog, "Description"].Value = strDescription + "\n"; objectActionLog[typeActionLog, "Title"].Value = strTitle; objectActionLog[typeActionLog, "EnteredBy"].Value = UserPrincipal.Current.DisplayName; objectActionLog[typeActionLog, "EnteredDate"].Value = DateTime.Now.ToUniversalTime(); //Get the enumeration and relationship for the actionlog entry ManagementPackEnumeration enumActionLog = mpWorkItemLibrary.GetEnumerations().GetItem("System.WorkItem.ActionLogEnum.TaskExecuted"); objectActionLog[typeActionLog, "ActionType"].Value = enumActionLog; ManagementPackRelationship relActionLog = emg.EntityTypes.GetRelationshipClass("System.WorkItem.TroubleTicketHasActionLog", mpWorkItemLibrary); //Get the projection for the incident from the emo EnterpriseManagementObjectProjection emopIncident = new EnterpriseManagementObjectProjection(emoIncident); //Add relationship and save emopIncident.Add(objectActionLog, relActionLog.Target); emopIncident.Commit(); return(true); } catch { return(false); } }
private void btnStart_Click(object sender, EventArgs e) { iNumberOfLevelsCreated = 0; iNumberOfEnumsCreated = 0; EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtSCSMServerName.Text); ManagementPackEnumeration mpeBase = Helper.GetEnumerationByName(txtBaseEnumName.Text, emg); ManagementPack mpNew = new ManagementPack(txtNewMPName.Text, txtNewMPName.Text, new Version("1.0.0.0"), emg); iNumberOfLevels = (int)nudNumberOfLevelsToCreate.Value; iNumberOfEnumsPerLevel = (int)nudNumberOfEnumsToCreatePerLevel.Value; CreateEnumerationsAtALevel("Enum", ref mpeBase, ref mpNew, iNumberOfEnumsPerLevel); DialogResult dr = MessageBox.Show(String.Format("Number of enums to be created: {0}", iNumberOfEnumsCreated.ToString()), "Write to MP XML file?", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { mpNew.AcceptChanges(); ManagementPackXmlWriter mpxw = new ManagementPackXmlWriter(txtFolderToWriteFileTo.Text); mpxw.WriteManagementPack(mpNew); } }
public static ManagementPack CreateNewManagementPackInMemory(string strName, string strVersion, string strInternalName, string strDisplayName, EnterpriseManagementGroup emg, Boolean bAddSMCategory) { StringReader sr = new StringReader(String.Format("<ManagementPack xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" ContentReadable=\"true\" SchemaVersion=\"2.0\" OriginalSchemaVersion=\"1.1\">" + "<Manifest>" + "<Identity>" + "<ID>{0}</ID>" + "<Version>{1}</Version>" + "</Identity>" + "<Name>{2}</Name>" + "<References/>" + "</Manifest>" + "<LanguagePacks>" + "<LanguagePack ID=\"ENU\" IsDefault=\"true\">" + "<DisplayStrings>" + "<DisplayString ElementID=\"{0}\">" + "<Name>{3}</Name>" + "</DisplayString>" + "</DisplayStrings>" + "</LanguagePack>" + "</LanguagePacks>" + "</ManagementPack>", strName, strVersion, strInternalName, strDisplayName)); ManagementPack mp = new ManagementPack(sr, emg); if (bAddSMCategory) { ManagementPackEnumeration mpeSMMP = GetEnumerationByName("Microsoft.EnterpriseManagement.ServiceManager.ManagementPack", emg); ManagementPackCategory mpcatSMMP = new ManagementPackCategory(mp, String.Format("Category.{0}", MakeMPElementSafeName(Guid.NewGuid().ToString()))); mpcatSMMP.Value = mpeSMMP; mpcatSMMP.ManagementPackName = strName; mpcatSMMP.ManagementPackVersion = strVersion; mpcatSMMP.Status = ManagementPackElementStatus.PendingAdd; mp.AcceptChanges(); } return(mp); }
private void UpdateScsmObject(string strPropertyName, object value) { if (_dataItem == null && _emoActivity == null) { throw new NullReferenceException("Both the idataitem and EnterpriseManagementObject cannot be null"); } if (value == null || value is string || value is int || value is Guid || value is DateTime) { if (_dataItem != null) { _dataItem[strPropertyName] = value; } if (_emoActivity != null) { _emoActivity[null, strPropertyName].Value = value; } } else if (value is ManagementPackEnumeration) { ManagementPackEnumeration enumValue = value as ManagementPackEnumeration; if (_dataItem != null) { _dataItem[strPropertyName] = value; } if (_emoActivity != null) { _emoActivity[null, strPropertyName].Value = enumValue.Id; } } else { throw new InvalidCastException("Unknown value type to update"); } }
public static ManagementPackEnumeration GetEnumerationFromGuid(Guid guid) { if (guid == Guid.Empty) { return(null); } if (_lstCachedEnumerations == null) { _lstCachedEnumerations = new ConcurrentBag <ManagementPackEnumeration>(); } ManagementPackEnumeration thisEnum = _lstCachedEnumerations.FirstOrDefault(x => x.Id == guid); if (thisEnum != null) { return(thisEnum); } var emg = Common.GetManagementGroup(); try { thisEnum = emg.EntityTypes.GetEnumeration(guid); } catch (Exception ex) { Console.WriteLine("Unable to get enumeration with GUID " + guid.ToString() + ". Exception: " + ex.Message); } if (thisEnum != null) { _lstCachedEnumerations.Add(thisEnum); return(thisEnum); } return(null); }
private void CreateEnumerationsAtALevel(string strBaseEnumName, ref ManagementPackEnumeration mpeBase, ref ManagementPack mpNew, int iNumberOfEnums) { int i = 0; do { //Create an enumeration ManagementPackEnumeration mpe = CreateEnumeration(String.Format("{0}.{1}", strBaseEnumName, (i + 1).ToString()), ref mpeBase, ref mpNew); //If you haven't already reached the bottom of the levels, create the children of this enumeration if (iNumberOfLevelsCreated < iNumberOfLevels - 1) { iNumberOfLevelsCreated++; CreateEnumerationsAtALevel(mpe.Name, ref mpe, ref mpNew, iNumberOfEnumsPerLevel); } i++; //If we are all done creating enums at this level then go back up a level. if (i == iNumberOfEnums) { iNumberOfLevelsCreated--; } } while (i < iNumberOfEnums); }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { try { // Obtain the MG object from the SCSM Workflow framework emg = ServerContextHelper.Instance.ManagementGroup; // Get class and enum definitions to correctly process the activity mpcWebhookActivity = emg.EntityTypes.GetClass(new Guid("80bc2a93-1ce0-9773-c37d-f7c59fe7c963")); mpeActivityCompleted = emg.EntityTypes.GetEnumeration(new Guid("9de908a1-d8f1-477e-c6a2-62697042b8d9")); mpeActivityFailed = emg.EntityTypes.GetEnumeration(new Guid("144bcd52-a710-2778-2a6e-c62e0c8aae74")); // Retrieve the Activity from the SDK emoWebhookActivity = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(InstanceId), ObjectQueryOptions.Default); // NameValueCollection is an alternative of using JSON, but it would post plaintext data to the webhook instead of a defined structure. This would make it harder to parse the data in the runbook. NameValueCollection nvcParameters = new NameValueCollection(); // Setup the JSON Writer: http://www.newtonsoft.com/json/help/html/ReadingWritingJSON.htm StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonWriter jw = new JsonTextWriter(sw); jw.WriteStartObject(); for (int i = 1; i <= 10; i++) { // Capture all Activity Parameter Name/Value sets that are not null and put them in the JSON array if (emoWebhookActivity[mpcWebhookActivity, "ParameterName" + i].Value != null) { string parameter = emoWebhookActivity[mpcWebhookActivity, "ParameterName" + i].Value.ToString(); string value = emoWebhookActivity[mpcWebhookActivity, "ParameterValue" + i].Value.ToString(); nvcParameters.Add(parameter, value); jw.WritePropertyName(parameter); jw.WriteValue(value); } } // If specified in the activity, add the activity id in there too if ((bool)emoWebhookActivity[mpcWebhookActivity, "IncludeActivityId"].Value == true) { string parameter = emoWebhookActivity[mpcWebhookActivity, "ActivityIdParameterName"].Value.ToString(); string value = emoWebhookActivity.Id.ToString(); nvcParameters.Add(parameter, value); jw.WritePropertyName(parameter); jw.WriteValue(value); } jw.WriteEndObject(); // Submit the data to the webhook using a WebClient Uri uri = new Uri(emoWebhookActivity[mpcWebhookActivity, "URL"].Value.ToString()); UTF8Encoding _encoding = new UTF8Encoding(); using (WebClient wc = new WebClient()) { var response = wc.UploadString(uri, "POST", sb.ToString()); //var stringResponse = _encoding.GetString(response); var matches = Regex.Match(response, Regex.Escape("{") + "\"JobIds\"" + Regex.Escape(":") + Regex.Escape("[") + "\"([^\"]+)\"" + Regex.Escape("]") + Regex.Escape("}")); if (matches.Captures.Count < 1) { throw new InvalidOperationException("Unknown Webhook failure"); } else { var jobId = matches.Captures[0]; bool ok = false; int retry = 5; // obsolete code to prevent colission issues, not needed anymore as the bug was fixed in the workflow MP while (!ok && retry > 0) { try { // Update the activity with the job info returned from the webhook call emoWebhookActivity[mpcWebhookActivity, "StatusText"].Value = "Webhook Triggered with Job ID '" + jobId + "'"; ok = true; } catch (Microsoft.EnterpriseManagement.Common.DiscoveryDataModificationCollisionException ex) { retry--; emoWebhookActivity = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(InstanceId), ObjectQueryOptions.Default); } } } } // If the activity must wait for the runbook to update it, end here. Else, set the activity to completed. if (!(bool)emoWebhookActivity[mpcWebhookActivity, "WaitForCallBack"].Value) { emoWebhookActivity[mpcWebhookActivity, "Status"].Value = mpeActivityCompleted; } return(ActivityExecutionStatus.Closed); } catch (Exception ex) { // in case of troubles, update the activity accordingly emoWebhookActivity[mpcWebhookActivity, "StatusText"].Value = ex.Message; emoWebhookActivity[mpcWebhookActivity, "Status"].Value = mpeActivityFailed; return(ActivityExecutionStatus.Closed); } finally { // in both OK and NOK situations, save the status info back to the activity emoWebhookActivity.Commit(); } }
static void Main(string[] args) { string strServerName = args[0]; string strWorkItemTypeToCreate = args[1]; int intIncidnetsPerDay = Int32.Parse(args[2]); int intIncidnetsToCreate = Int32.Parse(args[3]); int intChangeRequestsPerDay = Int32.Parse(args[4]); int intChangeRequestsToCreate = Int32.Parse(args[5]); int intServiceRequestsPerDay = Int32.Parse(args[6]); int intServiceRequestsToCreate = Int32.Parse(args[7]); int intProblemsPerDay = Int32.Parse(args[8]); int intProblemsToCreate = Int32.Parse(args[9]); int intReleasesPerDay = Int32.Parse(args[10]); int intReleasesToCreate = Int32.Parse(args[11]); int intNumberOfWorkingHoursPerDay = Int32.Parse(args[12]); intRateOfWorkItemQueryAndUpdates = Int32.Parse(args[13]); intDoWorkPause = Int32.Parse(args[14]); intNumberOfWorkItemsToGet = Int32.Parse(args[15]); DateTime dtCreatingManagementGroupStart = DateTime.Now; emg = new EnterpriseManagementGroup(strServerName); DateTime dtCreatingManagementGroupEnd = DateTime.Now; TimeSpan tsCreatingManagementGroup = dtCreatingManagementGroupEnd - dtCreatingManagementGroupStart; pcManagementGroupCreate.RawValue = (long)tsCreatingManagementGroup.TotalSeconds; Console.WriteLine(String.Format("Process user: {0}\\{1}", Environment.UserDomainName, Environment.UserName)); Console.WriteLine("Creating Management Group (seconds): " + tsCreatingManagementGroup.TotalSeconds); //For debugging so you can catch the process and put it in the debugger //Console.WriteLine("Sleeping for 10 seconds"); //Thread.Sleep(10000); DateTime dtCachingStart = DateTime.Now; //Get the current user and the user's associated group enum strUserName = Environment.UserName; strUserDomainName = Environment.UserDomainName; mpcUser = Helper.GetClassByName("System.Domain.User", emg); EnterpriseManagementObjectCriteria emocUser = new EnterpriseManagementObjectCriteria(String.Format("UserName = '******' AND Domain ='{1}'", strUserName, strUserDomainName), mpcUser); IObjectReader <EnterpriseManagementObject> orUser = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emocUser, ObjectQueryOptions.Default); if (orUser.Count > 0) { emoUser = orUser.First <EnterpriseManagementObject>(); } else { Console.WriteLine(String.Format("Logged in user: {0}\\{1} doesnt exist in the SCSM database.", strUserDomainName, strUserName)); } //Classes mpcIncident = Helper.GetClassByName("System.WorkItem.Incident", emg); mpcAnalystComment = Helper.GetClassByName("System.WorkItem.TroubleTicket.AnalystCommentLog", emg); mpcChangeRequest = Helper.GetClassByName("System.WorkItem.ChangeRequest", emg); mpcServiceRequest = Helper.GetClassByName("System.WorkItem.ServiceRequest", emg); mpcProblem = Helper.GetClassByName("System.WorkItem.Problem", emg); mpcComputer = Helper.GetClassByName("Microsoft.Windows.Computer", emg); mpcChangeRequestExtension = Helper.GetClassByName(Constants.CLASS_CHANGEREQUEST_EXTENSION, emg); mpcProblemExtension = Helper.GetClassByName(Constants.CLASS_PROBLEM_EXTENSION, emg); mpcServiceRequestExtension = Helper.GetClassByName(Constants.CLASS_SERVICEREQUEST_EXTENSION, emg); //Type Projections mptpIncidentView = Helper.GetTypeProjectionByName("System.WorkItem.Incident.View.ProjectionType", emg); mptpIncidentFull = Helper.GetTypeProjectionByName("System.WorkItem.Incident.ProjectionType", emg); mptpChangeRequestView = Helper.GetTypeProjectionByName("System.WorkItem.ChangeRequestViewProjection", emg); mptpChangeRequestFull = Helper.GetTypeProjectionByName("System.WorkItem.ChangeRequestProjection", emg); mptpServiceRequestView = Helper.GetTypeProjectionByName("System.WorkItem.ServiceRequestViewProjection", emg); mptpServiceRequestFull = Helper.GetTypeProjectionByName("System.WorkItem.ServiceRequestProjection", emg); mptpProblemView = Helper.GetTypeProjectionByName("System.WorkItem.ProblemViewProjection", emg); mptpProblemFull = Helper.GetTypeProjectionByName("System.WorkItem.Problem.ProjectionType", emg); //Relationships mprAnalystComment = Helper.GetRelationshipByName("System.WorkItem.TroubleTicketHasAnalystComment", emg); mprWorkItemAssignedToUser = Helper.GetRelationshipByName("System.WorkItemAssignedToUser", emg); mprAffectedCI = Helper.GetRelationshipByName("System.WorkItemAboutConfigItem", emg); mprRelatedCI = Helper.GetRelationshipByName("System.WorkItemRelatesToConfigItem", emg); //Management Packs mpSystemWorkItemLibrary = Helper.GetManagementPackByName("System.WorkItem.Library", emg); mpIncidentLibrary = Helper.GetManagementPackByName("System.WorkItem.Incident.Library", emg); mpServiceRequestLibrary = Helper.GetManagementPackByName("System.WorkItem.ServiceRequest.Library", emg); mpChangeRequestLibrary = Helper.GetManagementPackByName("System.WorkItem.ChangeRequest.Library", emg); mpProblemLibrary = Helper.GetManagementPackByName("System.WorkItem.Problem.Library", emg); //Properties mppIncidentClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Incident", "Classification", emg); mppServiceRequestArea = Helper.GetManagementPackClassPropertyByName("System.WorkItem.ServiceRequest", "Area", emg); mppChangeRequestArea = Helper.GetManagementPackClassPropertyByName("System.WorkItem.ChangeRequest", "Area", emg); mppProblemClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Problem", "Classification", emg); ManagementPackEnumeration mpeSRAreaBase = Helper.GetEnumerationByName("ServiceRequestAreaEnum", emg); ManagementPackEnumeration mpeCRAreaBase = Helper.GetEnumerationByName("ChangeAreaEnum", emg); ManagementPackEnumeration mpeProblemClassificationBase = Helper.GetEnumerationByName("ProblemClassificationEnum", emg); ManagementPackEnumeration mpeIncidentClassificationBase = Helper.GetEnumerationByName("IncidentClassificationEnum", emg); listSRAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeSRAreaBase.Id, TraversalDepth.Recursive); listCRAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeCRAreaBase.Id, TraversalDepth.Recursive); listProblemClassificationEnums = emg.EntityTypes.GetChildEnumerations(mpeProblemClassificationBase.Id, TraversalDepth.Recursive); listIncidentClassificationEnums = emg.EntityTypes.GetChildEnumerations(mpeIncidentClassificationBase.Id, TraversalDepth.Recursive); DateTime dtCachingEnd = DateTime.Now; TimeSpan tsCaching = dtCachingEnd - dtCachingStart; pcCaching.RawValue = (long)tsCaching.TotalSeconds; Console.WriteLine("Caching (seconds): " + tsCaching.TotalSeconds); Console.WriteLine("Worker work item class to create: " + strWorkItemTypeToCreate); switch (strWorkItemTypeToCreate) { case "Incident": CreateIncidents(intIncidnetsToCreate, intIncidnetsPerDay, intNumberOfWorkingHoursPerDay); break; case "ChangeRequest": CreateChangeRequests(intChangeRequestsToCreate, intChangeRequestsPerDay, intNumberOfWorkingHoursPerDay); break; case "ServiceRequest": CreateServiceRequests(intServiceRequestsToCreate, intServiceRequestsPerDay, intNumberOfWorkingHoursPerDay); break; case "Problem": CreateProblems(intProblemsToCreate, intProblemsPerDay, intNumberOfWorkingHoursPerDay); break; case "Release": CreateReleases(intReleasesToCreate, intReleasesPerDay, intNumberOfWorkingHoursPerDay); break; default: break; } System.Timers.Timer timerWorkItemQueryUpdate = new System.Timers.Timer((double)intRateOfWorkItemQueryAndUpdates); timerWorkItemQueryUpdate.Elapsed += new ElapsedEventHandler(WorkItemQueryUpdate); timerWorkItemQueryUpdate.Enabled = true; while (Console.Read() != 'q') { ; } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Used for idataitem (form mode, 1=new form, 2=edit form); int iMode = 0; //Set title for messageboxes string sAppTitle = "Assign Incident Directly To Analyst"; //Connect to MG IServiceContainer isContainer = (IServiceContainer)FrameworkServices.GetService(typeof(IServiceContainer)); IManagementGroupSession imgSession = (IManagementGroupSession)isContainer.GetService(typeof(IManagementGroupSession)); if (imgSession == null) { MessageBox.Show("Failed to connect to the current session", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } EnterpriseManagementGroup emg = imgSession.ManagementGroup; //Get the incident class (System.WorkItem.Incident) ManagementPackClass classIncident = emg.EntityTypes.GetClass(new Guid("A604B942-4C7B-2FB2-28DC-61DC6F465C68")); //Microsoft.Windows.Library ManagementPack mpWindows = emg.ManagementPacks.GetManagementPack(new Guid("545131F0-58DE-1914-3A82-4FCAC9100A33")); //Get the Microsoft.AD.User class ManagementPackClass mpcADUser = emg.EntityTypes.GetClass("Microsoft.AD.User", mpWindows); //Return the currently selected incident reference NavigationModelNodeBase selincident = nodes[0]; //Form mode (not new)? if (selincident.Location.AbsoluteUri.IndexOf("FormDisplay", 0) > 0) { iMode = 2; } //Get objects EnterpriseManagementObject emoSelIncident = null; IDataItem i = ConsoleContextHelper.Instance.GetFormDataContext(nodes[0]); //Get the analyst settings class and MP ManagementPack mpSetting = emg.ManagementPacks.GetManagementPack(new Guid("56d5c2d6-7e19-59ff-7a81-ac8a331fcb3f")); ManagementPackClass classSettings = mpSetting.GetClass("AssignSettingsClass"); //Get the emo for the settings EnterpriseManagementObject emoSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(classSettings.Id, ObjectQueryOptions.Default); //TP names string sAssignedTo = "AssignedUser"; string sActionLog = "ActionLogs"; if (emoSettings[classSettings, "AssignedUserAlias"].Value != null) { sAssignedTo = emoSettings[classSettings, "AssignedUserAlias"].Value.ToString(); } if (emoSettings[classSettings, "ActionLogAlias"].Value != null) { sActionLog = emoSettings[classSettings, "ActionLogAlias"].Value.ToString(); } //Check if new if (!(bool)i["$IsNew$"]) { //Now get the guid of the selected workitem. Depending on the view type, the return will be different, so take it after the last "." //There are lots of ways of doing this, this is not the best way but it was the first I learnt and it works string strGuid = selincident.GetId().Substring(selincident.GetId().LastIndexOf('.') + 1); //Get the emo of the workitem via it's guid emoSelIncident = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strGuid), ObjectQueryOptions.Default); } //Creating new incident else { iMode = 1; } //Was task was run from an workitem opened for editing, as opposed to a list or view? if (selincident.Location.AbsoluteUri.IndexOf("FormDisplay", 0) != -1) { iMode = 2; } //Get the status guid Guid gStatus = Guid.NewGuid(); try { //"New" status will throw an exception to must catch here if (i["Status"] != null) { gStatus = (Guid)(i["Status"] as IDataItem)["Id"]; } } catch { } //Get the incident class (System.WorkItem.Incident) ManagementPackClass mpcIncident = emg.EntityTypes.GetClass(new Guid("a604b942-4c7b-2fb2-28dc-61dc6f465c68")); //Check if the incident is closed if (gStatus == new Guid("bd0ae7c4-3315-2eb3-7933-82dfc482dbaf")) { MessageBox.Show("This incident cannot be reassigned as it has been closed.", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //Note - we are alllowing resolved incidents to be re-assigned, to prevent this, uncomment the following block: /*else if (gStatus == new Guid("2b8830b6-59f0-f574-9c2a-f4b4682f1681")) * { * MessageBox.Show("This incident cannot be reassigned as it has been resolved.", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); * return; * } */ //Current assignee and Id string sId = ""; string sUser = ""; string sTierGuid = ""; if (iMode == 0) { //View mode sUser = this.GetProperty(ref emg, emoSelIncident, ref mpcADUser, "DisplayName"); sId = emoSelIncident[mpcIncident, "Id"].Value.ToString(); if (emoSelIncident[mpcIncident, "TierQueue"].Value != null) { sTierGuid = ((ManagementPackEnumeration)emoSelIncident[mpcIncident, "TierQueue"].Value).Id.ToString(); } } else { //New or edit form mode try { //Get display name of current assignee if (i[sAssignedTo] == null) { sUser = "******"; } else { sUser = (string)(i[sAssignedTo] as IDataItem)["DisplayName"]; } } catch { //Set no assignee sUser = "******"; } sId = (string)i["Id"]; try { //Check current tier queue enum value if (i["TierQueue"] != null) { sTierGuid = ((Guid)(i["TierQueue"] as IDataItem)["Id"]).ToString(); } } catch { } } //Create a new instance of the form and set it up AssignForm af = new AssignForm(); af.sTierGuid = sTierGuid; af.Text = "Assign incident " + sId + " directly to Analyst - currently assigned to " + sUser; af.textDefault.Text = sUser; af.emg = emg; //Show the analyst/tier selection form DialogResult dr = af.ShowDialog(); if (dr != DialogResult.Cancel) { //Get the samaccountname from the right hand part of the combobox.text after the ! string sADUserName = af.comboAnalysts.Text.Substring(af.comboAnalysts.Text.LastIndexOf("(") + 1); //Remove last ) sADUserName = sADUserName.Substring(0, sADUserName.Length - 1); //Format to get the display name only from the left part - this is used for the actionlog entry string sADUserDisplayName = af.comboAnalysts.Text.Substring(0, af.comboAnalysts.Text.LastIndexOf("(")).Trim(); try { //Set the query for the user - note - usernames are assumed unique across configured domains //If this is not the case, you need to customise these criteria to include a domain string sADUserCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""Microsoft.Windows.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""MSWinLib"" /> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='MSWinLib!Microsoft.AD.User']/UserName$</Property> </ValueExpressionLeft> <Operator>Equal</Operator> <ValueExpressionRight> <Value>" + sADUserName + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> </Criteria> ", mpWindows.KeyToken, mpWindows.Version.ToString()); //Object query options ObjectQueryOptions objQueryOpts = new ObjectQueryOptions(); objQueryOpts.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered; objQueryOpts.DefaultPropertyRetrievalBehavior = ObjectPropertyRetrievalBehavior.All; //We are searching via samAccountName so there will be only 1 item objQueryOpts.MaxResultCount = 1; //Get the AD User CI object EnterpriseManagementObjectCriteria emocADUser = new EnterpriseManagementObjectCriteria(sADUserCriteria, mpcADUser, emg); IObjectReader <EnterpriseManagementObject> orADUser = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emocADUser, objQueryOpts); EnterpriseManagementObject emoAssignToUser = orADUser.ElementAt(0); if (iMode == 0) { //View mode - create a new assigned to user relationship ManagementPackRelationship relAssignedToUser = emg.EntityTypes.GetRelationshipClass(new Guid("15e577a3-6bf9-6713-4eac-ba5a5b7c4722")); CreatableEnterpriseManagementRelationshipObject cemroAssignedToUser = new CreatableEnterpriseManagementRelationshipObject(emg, relAssignedToUser); //Set the source and target... cemroAssignedToUser.SetSource(emoSelIncident); cemroAssignedToUser.SetTarget(emoAssignToUser); //Save cemroAssignedToUser.Commit(); //Add a new comment this.AddActionLogEntry(emg, emoSelIncident, "Incident was assigned to " + sADUserDisplayName, af.textComment.Text); //Check tier if (af.bShowTier) { if (af.comboTier.Text == "") { emoSelIncident[classIncident, "TierQueue"].Value = null; } else { ManagementPackEnumeration mpeTier = emg.EntityTypes.GetEnumeration(new Guid(af.comboTierGuids.Items[af.comboTier.SelectedIndex].ToString())); emoSelIncident[classIncident, "TierQueue"].Value = mpeTier; } emoSelIncident.Commit(); } //Refresh the current incident view this.RequestViewRefresh(); } else { //Note - IDataItem property names depend on the type projection being used and may differ from these //Form mode, create a proxy to the emo user object to set on the form EnterpriseManagementObjectDataType dataType = new EnterpriseManagementObjectDataType(mpcADUser); IDataItem iUser = dataType.CreateProxyInstance(emoAssignToUser); i[sAssignedTo] = iUser; //Check tier if (af.bShowTier) { if (af.comboTier.Text == "") { //Remove tier i["TierQueue"] = null; } else { //Set tier, get enum first ManagementPackEnumeration mpeTier = emg.EntityTypes.GetEnumeration(new Guid(af.comboTierGuids.Items[af.comboTier.SelectedIndex].ToString())); i["TierQueue"] = mpeTier; } } //Uncommenting this will cause the IDataItem to be saved and thus update the actual object in the database, normally you don't want to do this //as you want the user to click OK or cancel on the form instead //EnterpriseManagementObjectProjectionDataType.UpdateDataItem(i); //IDataItem Action log // //Get the System.WorkItem.Library mp ManagementPack mpWorkItemLibrary = emg.ManagementPacks.GetManagementPack(new Guid("405D5590-B45F-1C97-024F-24338290453E")); //Get the actionlog class ManagementPackClass mpcActionLog = emg.EntityTypes.GetClass("System.WorkItem.TroubleTicket.ActionLog", mpWorkItemLibrary); //Create a new action log entry as an idataitem CreatableEnterpriseManagementObject cemoActionLog = new CreatableEnterpriseManagementObject(emg, mpcActionLog); EnterpriseManagementObjectDataType dataTypeLog = new EnterpriseManagementObjectDataType(mpcActionLog); IDataItem iLog = dataTypeLog.CreateProxyInstance(cemoActionLog); //Setup the new action log entry iLog["Id"] = Guid.NewGuid().ToString(); iLog["Description"] = af.textComment.Text; iLog["Title"] = "Reassignment Comment"; iLog["EnteredBy"] = UserPrincipal.Current.DisplayName; iLog["EnteredDate"] = DateTime.Now.ToUniversalTime(); //Set action type (this also adds the icon and is required) ManagementPackEnumeration enumActionLog = mpWorkItemLibrary.GetEnumerations().GetItem("System.WorkItem.ActionLogEnum.TaskExecuted"); iLog["ActionType"] = enumActionLog; //This adds the new idataitem log entry to the entries displayed on the form, it does not over-write the existing entries i[sActionLog] = iLog; } } catch (System.Exception e) { //Oops MessageBox.Show(e.Message + "\n\n" + e.StackTrace, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } }
public String Copy() { string strWorkItemID = null; #region MPVariables ManagementPack mpIncidentLibrary = Common.GetManagementPackByName(Constants.strManagementPackIncidentLibrary, this.EMG); ManagementPackTypeProjection mptpIncident = Common.GetManagementPackTypeProjectionByName(Constants.strTypeProjectionIncident, Constants.strManagementPackIncidentManagementLibrary, this.EMG); ManagementPackClass mpcIncident = Common.GetManagementPackClassByName(Constants.strClassIncident, Constants.strManagementPackIncidentLibrary, this.EMG); ManagementPackRelationship mprCreatedByUser = Common.GetManagementPackRelationshipByName(Constants.strRelationshipCreatedByUser, Constants.strManagementPackWorkItemLibrary, this.EMG); ManagementPackEnumeration mpeIncidentStatusActive = Common.GetManagementPackEnummerationByName(Constants.strEnumerationIncidentStatusActive, Constants.strManagementPackIncidentLibrary, this.EMG); ManagementPackRelationship mprWorkItemRelatesToWorkItem = Common.GetManagementPackRelationshipByName(Constants.strRelationshipWorkItemRelatesToWorkItem, Constants.strManagementPackWorkItemLibrary, this.EMG); #endregion string strIncidentIDPrefix = GetIncidentIDPrefix(); //Create the criteria to get the object by the Work Item ID passed in String strIncidentByIDCriteria = String.Format(@"<Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/"">" + "<Expression>" + "<SimpleExpression>" + "<ValueExpressionLeft>" + "<Property>$Target/Property[Type='System.WorkItem.Incident']/Id$</Property>" + "</ValueExpressionLeft>" + "<Operator>Equal</Operator>" + "<ValueExpressionRight>" + "<Value>{0}</Value>" + "</ValueExpressionRight>" + "</SimpleExpression>" + "</Expression>" + "</Criteria>", this.IDToCopy); ObjectProjectionCriteria opcIncidentByID = new ObjectProjectionCriteria(strIncidentByIDCriteria, mptpIncident, mpIncidentLibrary, this.EMG); //Get the incident type projection by ID IObjectProjectionReader <EnterpriseManagementObject> emopIncidents = this.EMG.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opcIncidentByID, ObjectQueryOptions.Default); foreach (EnterpriseManagementObjectProjection emopIncident in emopIncidents) { //Note: We are using foreach here but there will be only one since we are searching by the work item ID if (this.PropertiesToExclude.Length == 0) { //A list of Properties to exclude was not passed in so we are going to go with a default list. this.PropertiesToExclude = new string[] { Constants.strPropertyId, Constants.strPropertyCreatedDate, Constants.strPropertyStatus, Constants.strPropertyTargetResolutionTime, Constants.strPropertyResolutionCategory, Constants.strPropertyResolutionDescription, Constants.strPropertyClosedDate, Constants.strPropertyDisplayName }; } //Copy all the properties (including extended properties, except for those specified EnterpriseManagementObjectProjection emopNewIncident = Common.CreateNewObjectProjectionFromExistingObjectProjection(emopIncident, mpcIncident, this.PropertiesToExclude, this.EMG); //Set the ID, DisplayName, Status, and CreatedDate properties emopNewIncident.Object[mpcIncident, Constants.strPropertyStatus].Value = mpeIncidentStatusActive; emopNewIncident.Object[mpcIncident, Constants.strPropertyId].Value = String.Format("{0}{1}", strIncidentIDPrefix, "{0}"); emopNewIncident.Object[mpcIncident, Constants.strPropertyCreatedDate].Value = DateTime.Now.ToUniversalTime(); emopNewIncident.Object[mpcIncident, Constants.strPropertyDisplayName].Value = String.Format("{0} - {1}", emopNewIncident.Object[mpcIncident, Constants.strPropertyId].Value, emopNewIncident.Object[mpcIncident, Constants.strPropertyTitle].Value); if (this.RelationshipAliasesToExclude.Length == 0) { //A list of Relationships to exclude was not passed in so we are going to go with a default list. this.RelationshipAliasesToExclude = new string[] { Constants.strAliasCreatedByUser, Constants.strAliasClosedByUser, Constants.strAliasResolvedByUser, Constants.strAliasActionLogs, Constants.strAliasUserComments, Constants.strAliasAnalystComments, Constants.strAliasSMTPNotifications, Constants.strAliasActivities, Constants.strAliasFileAttachments }; } //Copy all the relationships defined in the type projection, except for those specified Common.CopyRelationships(emopIncident, ref emopNewIncident, mptpIncident, this.RelationshipAliasesToExclude); //Set CreatedByUser to be the user that is logged in EnterpriseManagementObject emoCreatedByUser = Common.GetLoggedInUserAsObject(this.EMG); if (emoCreatedByUser != null) { emopNewIncident.Add(emoCreatedByUser, mprCreatedByUser.Target); } //Relate the original incident to the new one emopNewIncident.Add(emopIncident.Object, mprWorkItemRelatesToWorkItem.Target); //And finally submit... emopNewIncident.Commit(); strWorkItemID = emopNewIncident.Object[mpcIncident, Constants.strPropertyId].Value.ToString(); } return(strWorkItemID); }
private static void DoSomeChangeRequestWork() { DateTime dtChangeRequestWorkStart = DateTime.Now; //Query and get some change requests using just the view type projection int intRandomAreaEnum = Helper.GetRandomNumber(0, listCRAreaEnums.Count); ManagementPackEnumeration mpeRandomArea = listCRAreaEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomAreaEnum); string strCriteria = Helper.SearchObjectByEnumerationCriteriaXml(mpeRandomArea, mpcChangeRequest, mppChangeRequestArea); IObjectProjectionReader <EnterpriseManagementObject> oprChangeRequestView = Helper.GetBufferedObjectProjectionReader(strCriteria, intNumberOfWorkItemsToGet, mptpChangeRequestView, emg); if (oprChangeRequestView == null) { Console.WriteLine("No objects to retrieve given the criteria"); } else { //Get a particular incident (full projection) and update it by adding an action log entry and string strChangeRequestId = null; if (oprChangeRequestView.Count > 0) { strChangeRequestId = oprChangeRequestView.ElementAtOrDefault <EnterpriseManagementObjectProjection>(Helper.GetRandomNumber(0, oprChangeRequestView.Count - 1)).Object[mpcChangeRequest, "Id"].Value.ToString(); } if (strChangeRequestId != null) { //Get the change request to update string strCriteriaXml = Helper.SearchWorkItemByIDCriteriaXml(strChangeRequestId, mpSystemWorkItemLibrary.Name, mpSystemWorkItemLibrary.Version.ToString(), mpSystemWorkItemLibrary.KeyToken, "System.WorkItem"); ObjectProjectionCriteria opcChangeRequestFull = new ObjectProjectionCriteria(strCriteriaXml, mptpChangeRequestFull, emg); IObjectProjectionReader <EnterpriseManagementObject> oprChangeRequestFull = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opcChangeRequestFull, ObjectQueryOptions.Default); EnterpriseManagementObjectProjection emopChangeRequestFull = oprChangeRequestFull.First <EnterpriseManagementObjectProjection>(); if (bSimulateHumanWaitTime) { Thread.Sleep(intDoWorkPause); } //Update a couple of properties on the change request emopChangeRequestFull.Object[mpcChangeRequest, "Description"].Value = Guid.NewGuid().ToString(); int intRandomEnumID = Helper.GetRandomNumber(0, listCRAreaEnums.Count); ManagementPackEnumeration mpeArea = listCRAreaEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomEnumID); emopChangeRequestFull.Object[mpcChangeRequestExtension, "Area"].Value = mpeArea; //Add the current user as an affected CI emopChangeRequestFull.Add(emoUser, mprAffectedCI.Target); if (bSimulateHumanWaitTime) { Thread.Sleep(intDoWorkPause); } //Commit the changes to the DB emopChangeRequestFull.Overwrite(); foreach (IComposableProjection icpRelatedCI in emopChangeRequestFull[mprRelatedCI.Target]) { icpRelatedCI.Remove(); } emopChangeRequestFull.Overwrite(); DateTime dtChangeRequestWorkEnd = DateTime.Now; TimeSpan tsChangeRequestWork = dtChangeRequestWorkEnd - dtChangeRequestWorkStart; pcChangeRequestWork.RawValue = (long)tsChangeRequestWork.TotalSeconds; Console.WriteLine("Change request work completed (seconds): " + tsChangeRequestWork.TotalSeconds); } } }
protected override void ProcessRecord() { ManagementPackClass clsIncident = SMHelpers.GetManagementPackClass(ClassTypes.System_WorkItem_Incident, SMHelpers.GetManagementPack(ManagementPacks.System_WorkItem_Incident_Library, _mg), _mg); ManagementPack incidentProjectionMp = SMHelpers.GetManagementPack(ManagementPacks.ServiceManager_IncidentManagement_Library, _mg); ManagementPackTypeProjection incidentTypeProjection = SMHelpers.GetManagementPackTypeProjection(TypeProjections.System_WorkItem_Incident_ProjectionType, incidentProjectionMp, _mg); WriteVerbose("Starting to build search criteria..."); List <string> criterias = new List <string>(); bool haveCriteria = false; // Define the query criteria string. // This is XML that validates against the Microsoft.EnterpriseManagement.Core.Criteria schema. StringBuilder incidentCriteria = new StringBuilder(String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""System.WorkItem.Incident.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""WorkItem"" /> <Expression>", incidentMp.KeyToken, incidentMp.Version.ToString())); if (this._ID != null) { haveCriteria = true; WriteVerbose(string.Format("Adding \"ID equal {0}\" to search criteria", this.ID)); criterias.Add(String.Format(criteriaString, "Id", "Equal", _ID)); } if (this._Title != null) { haveCriteria = true; WriteVerbose(string.Format("Adding \"Title like {0}\" to search criteria", this.Title)); criterias.Add(String.Format(criteriaString, "Title", "Like", _Title)); } if (this.Impact != null) { haveCriteria = true; ManagementPackEnumeration impEnum = SMHelpers.GetEnum(this.Impact, impactBase); WriteVerbose(string.Format("Adding \"Impact equal {0}({1})\" to search criteria", impEnum.DisplayName, impEnum.Id)); criterias.Add(String.Format(criteriaString, "Impact", "Equal", impEnum.Id)); } if (this.Urgency != null) { haveCriteria = true; ManagementPackEnumeration urgEnum = SMHelpers.GetEnum(this.Urgency, urgencyBase); WriteVerbose(string.Format("Adding \"Urgency equal {0}({1})\" to search criteria", urgEnum.DisplayName, urgEnum.Id)); criterias.Add(String.Format(criteriaString, "Urgency", "Equal", urgEnum.Id)); } if (this.Status != null) { haveCriteria = true; ManagementPackEnumeration statEnum = SMHelpers.GetEnum(this.Status, statusBase); WriteVerbose(string.Format("Adding \"Status equal {0}({1})\" to search criteria", statEnum.DisplayName, statEnum.Id)); criterias.Add(String.Format(criteriaString, "Status", "Equal", statEnum.Id)); } if (this.Classification != null) { haveCriteria = true; ManagementPackEnumeration classificationEnum = SMHelpers.GetEnum(this.Classification, classificationBase); WriteVerbose(string.Format("Adding \"Classification equal {0}({1})\" to search criteria", classificationEnum.DisplayName, classificationEnum.Id)); criterias.Add(String.Format(criteriaString, "Classification", "Equal", classificationEnum.Id)); } if (this.CreatedBefore != DateTime.MinValue) { haveCriteria = true; CultureInfo enUsInfo = new CultureInfo("en-US"); WriteVerbose(string.Format("Adding \"CreatedDate less than {0}\" to search criteria", this.CreatedBefore.ToString())); criterias.Add(String.Format(criteriaString, "CreatedDate", "Less", CreatedBefore.ToUniversalTime())); } if (this.CreatedAfter != DateTime.MinValue) { haveCriteria = true; CultureInfo enUsInfo = new CultureInfo("en-US"); WriteVerbose(string.Format("Adding \"CreatedDate greater than {0}\" to search criteria", this.CreatedAfter.ToString())); criterias.Add(String.Format(criteriaString, "CreatedDate", "Greater", this.CreatedAfter.ToUniversalTime())); } if (criterias.Count > 1) { haveCriteria = true; for (int i = 0; i < criterias.Count; i++) { criterias[i] = "<Expression>" + criterias[i] + "</Expression>"; } } if (criterias.Count > 1) { incidentCriteria.AppendLine("<And>"); } foreach (var item in criterias) { incidentCriteria.AppendLine(item); } if (criterias.Count > 1) { incidentCriteria.AppendLine("</And>"); } incidentCriteria.AppendLine(@"</Expression> </Criteria>"); WriteDebug("Search criteria: " + incidentCriteria.ToString()); ObjectProjectionCriteria criteria = null; if (haveCriteria) { // Define the criteria object by using one of the criteria strings. criteria = new ObjectProjectionCriteria(incidentCriteria.ToString(), incidentTypeProjection, _mg); WriteVerbose("Criteria is: " + incidentCriteria.ToString()); } else { criteria = new ObjectProjectionCriteria(incidentTypeProjection); WriteVerbose("Criteria is Projection"); } string[] EnumPropertiesToAdapt = { "Urgency", "Impact", "TierQueue", "Classification", "Status" }; // For each retrieved type projection, display the properties. List <EnterpriseManagementObjectProjection> result = new List <EnterpriseManagementObjectProjection>(); foreach (EnterpriseManagementObjectProjection projection in _mg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(criteria, ObjectQueryOptions.Default)) { if (this.InactiveFor == TimeSpan.Zero || projection.Object.LastModified.Add(this.InactiveFor) < DateTime.UtcNow) { //if (this.OlderThan == TimeSpan.Zero || projection.Object.TimeAdded.Add(this.OlderThan) < DateTime.UtcNow) //{ //result.Add(projection); WriteVerbose(String.Format("Adding incident \"{0}\" to the pipeline", projection.Object.Name)); // WriteObject(projection, false); PSObject o = new PSObject(); o.Members.Add(new PSNoteProperty("__base", projection)); o.Members.Add(new PSScriptMethod("GetAsXml", ScriptBlock.Create("[xml]($this.__base.CreateNavigator().OuterXml)"))); o.Members.Add(new PSNoteProperty("Object", ServiceManagerObjectHelper.AdaptManagementObject(this, projection.Object))); o.Members.Add(new PSNoteProperty("ID", projection.Object[null, "Id"])); o.Members.Add(new PSNoteProperty("Title", projection.Object[null, "Title"])); o.Members.Add(new PSNoteProperty("Description", projection.Object[null, "Description"])); o.Members.Add(new PSNoteProperty("DisplayName", projection.Object[null, "DisplayName"])); o.Members.Add(new PSNoteProperty("Priority", projection.Object[null, "Priority"])); foreach (string s in EnumPropertiesToAdapt) { o.Members.Add(new PSNoteProperty(s, GetEnumerationDisplayString(projection.Object[null, s]))); } o.Members.Add(new PSNoteProperty("CreatedDate", projection.Object[null, "CreatedDate"])); o.Members.Add(new PSNoteProperty("LastModified", projection.Object.LastModified.ToLocalTime())); // add the relationship values foreach (KeyValuePair <ManagementPackRelationshipEndpoint, IComposableProjection> helper in projection) { // EnterpriseManagementObject myEMO = (EnterpriseManagementObject)helper.Value.Object; WriteVerbose("Adapting relationship objects: " + helper.Key.Name); String myName = helper.Key.Name; PSObject adaptedEMO = ServiceManagerObjectHelper.AdaptManagementObject(this, helper.Value.Object); if (helper.Key.MaxCardinality > 1) { // OK, this is a collection, so add the critter // This is so much easier in PowerShell if (o.Properties[myName] == null) { o.Members.Add(new PSNoteProperty(myName, new ArrayList())); } ((ArrayList)o.Properties[myName].Value).Add(adaptedEMO); } else { try { o.Members.Add(new PSNoteProperty(helper.Key.Name, adaptedEMO)); } catch (ExtendedTypeSystemException e) { WriteVerbose("Readapting relationship object -> collection :" + e.Message); // We should really only get this exception if we // try to add a create a new property which already exists Object currentPropertyValue = o.Properties[myName].Value; ArrayList newValue = new ArrayList(); newValue.Add(currentPropertyValue); newValue.Add(adaptedEMO); o.Properties[myName].Value = newValue; // WriteError(new ErrorRecord(e, "AddAssociatedObject", ErrorCategory.InvalidOperation, p)); } } } o.TypeNames[0] = String.Format(CultureInfo.CurrentCulture, "EnterpriseManagementObjectProjection#{0}", incidentTypeProjection.Name); WriteObject(o); //} } } }
private void btnCreate_Click(object sender, EventArgs e) { EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtManagementServer.Text); ManagementPackEnumeration mpeSRAreaBase = Helper.GetEnumerationByName("ServiceRequestAreaEnum", emg); ManagementPackEnumeration mpeCRAreaBase = Helper.GetEnumerationByName("ChangeAreaEnum", emg); ManagementPackEnumeration mpeProblemClassificationBase = Helper.GetEnumerationByName("ProblemClassificationEnum", emg); ManagementPackEnumeration mpeIncidentClassificationBase = Helper.GetEnumerationByName("IncidentClassificationEnum", emg); IList <ManagementPackEnumeration> listSRAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeSRAreaBase.Id, TraversalDepth.Recursive); IList <ManagementPackEnumeration> listCRAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeCRAreaBase.Id, TraversalDepth.Recursive); IList <ManagementPackEnumeration> listProblemAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeProblemClassificationBase.Id, TraversalDepth.Recursive); IList <ManagementPackEnumeration> listIncidentAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeIncidentClassificationBase.Id, TraversalDepth.Recursive); ManagementPackClass mpcServiceRequest = Helper.GetClassByName("System.WorkItem.ServiceRequest", emg); ManagementPackClass mpcChangeRequest = Helper.GetClassByName("System.WorkItem.ChangeRequest", emg); ManagementPackClass mpcProblem = Helper.GetClassByName("System.WorkItem.Problem", emg); ManagementPackClass mpcIncident = Helper.GetClassByName("System.WorkItem.Incident", emg); ManagementPack mpServiceRequest = Helper.GetManagementPackByName("System.WorkItem.ServiceRequest.Library", emg); ManagementPack mpChangeRequest = Helper.GetManagementPackByName("System.WorkItem.ChangeRequest.Library", emg); ManagementPack mpProblem = Helper.GetManagementPackByName("System.WorkItem.Problem.Library", emg); ManagementPack mpIncident = Helper.GetManagementPackByName("System.WorkItem.Incident.Library", emg); ManagementPackReference mprServiceRequest = new ManagementPackReference(mpServiceRequest); ManagementPackReference mprChangeRequest = new ManagementPackReference(mpChangeRequest); ManagementPackReference mprProblem = new ManagementPackReference(mpProblem); ManagementPackReference mprIncident = new ManagementPackReference(mpIncident); ManagementPack mp = Helper.CreateNewManagementPackInMemory("NotificationRules", "1.0.0.0", "NotificationRules", "NOTIFICATION_RULES", emg, true); string strMPAliasServiceRequestLibrary = Helper.MakeMPElementSafeName(mpServiceRequest.Name); string strMPAliasChangeRequestLibrary = Helper.MakeMPElementSafeName(mpChangeRequest.Name); string strMPAliasProblemLibrary = Helper.MakeMPElementSafeName(mpProblem.Name); string strMPAliasIncidentLibrary = Helper.MakeMPElementSafeName(mpIncident.Name); mp.References.Add(strMPAliasServiceRequestLibrary, mprServiceRequest); mp.References.Add(strMPAliasChangeRequestLibrary, mprChangeRequest); mp.References.Add(strMPAliasProblemLibrary, mprProblem); mp.References.Add(strMPAliasIncidentLibrary, mprIncident); ManagementPackObjectTemplate mpotNewIncident = Helper.GetObjectTemplateByName(txtNewIncidentTemplate.Text, emg); ManagementPackObjectTemplate mpotUpdateIncident = Helper.GetObjectTemplateByName(txtUpdateIncidentTemplate.Text, emg); ManagementPackObjectTemplate mpotNewServiceRequest = Helper.GetObjectTemplateByName(txtNewServiceRequestTemplate.Text, emg); ManagementPackObjectTemplate mpotUpdateServiceRequest = Helper.GetObjectTemplateByName(txtUpdateServiceRequestTemplate.Text, emg); ManagementPackObjectTemplate mpotNewChangeRequest = Helper.GetObjectTemplateByName(txtNewChangeRequestTemplate.Text, emg); ManagementPackObjectTemplate mpotUpdateChangeRequest = Helper.GetObjectTemplateByName(txtUpdateChangeRequestTemplate.Text, emg); ManagementPackObjectTemplate mpotNewProblem = Helper.GetObjectTemplateByName(txtNewProblemTemplate.Text, emg); ManagementPackObjectTemplate mpotUpdateProblem = Helper.GetObjectTemplateByName(txtUpdateProblemTemplate.Text, emg); EnterpriseManagementObject emoUser = Helper.GetUserFromEmailAddress(txtEmailAddress.Text, emg); double dRulesToCreate = listSRAreaEnums.Count + listCRAreaEnums.Count + listProblemAreaEnums.Count + listIncidentAreaEnums.Count; pbProgress.Show(); pbProgress.Value = 0; double i = 0; ManagementPackProperty mppSRArea = Helper.GetManagementPackClassPropertyByName("System.WorkItem.ServiceRequest", "Area", emg); ManagementPackProperty mppCRArea = Helper.GetManagementPackClassPropertyByName("System.WorkItem.ChangeRequest", "Area", emg); ManagementPackProperty mppProblemClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Problem", "Classification", emg); ManagementPackProperty mppIncidentClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Incident", "Classification", emg); foreach (ManagementPackEnumeration mpeSRArea in listSRAreaEnums) { i++; CreateAddNotificationRule(mpcServiceRequest, mpeSRArea, strMPAliasServiceRequestLibrary, mppSRArea, ref mp, emoUser, mpotNewServiceRequest, emg); pbProgress.Value = (int)(i / dRulesToCreate * 100); } CreateUpdateNotificationRule(mpcServiceRequest, strMPAliasServiceRequestLibrary, mppSRArea, ref mp, emoUser, mpotUpdateServiceRequest, emg); foreach (ManagementPackEnumeration mpeCRArea in listCRAreaEnums) { i++; CreateAddNotificationRule(mpcChangeRequest, mpeCRArea, strMPAliasChangeRequestLibrary, mppCRArea, ref mp, emoUser, mpotNewChangeRequest, emg); pbProgress.Value = (int)(i / dRulesToCreate * 100); } CreateUpdateNotificationRule(mpcChangeRequest, strMPAliasChangeRequestLibrary, mppCRArea, ref mp, emoUser, mpotUpdateChangeRequest, emg); foreach (ManagementPackEnumeration mpeProblemClassification in listProblemAreaEnums) { i++; CreateAddNotificationRule(mpcProblem, mpeProblemClassification, strMPAliasProblemLibrary, mppProblemClassification, ref mp, emoUser, mpotNewProblem, emg); pbProgress.Value = (int)(i / dRulesToCreate * 100); } CreateUpdateNotificationRule(mpcProblem, strMPAliasProblemLibrary, mppProblemClassification, ref mp, emoUser, mpotUpdateProblem, emg); foreach (ManagementPackEnumeration mpeIncidentClassification in listIncidentAreaEnums) { i++; CreateAddNotificationRule(mpcIncident, mpeIncidentClassification, strMPAliasIncidentLibrary, mppIncidentClassification, ref mp, emoUser, mpotNewIncident, emg); pbProgress.Value = (int)(i / dRulesToCreate * 100); } CreateUpdateNotificationRule(mpcIncident, strMPAliasIncidentLibrary, mppIncidentClassification, ref mp, emoUser, mpotUpdateIncident, emg); emg.ManagementPacks.ImportManagementPack(mp); }
private static string ConstructAddCriteria(string strMPAlias, ManagementPackClass mpc, ManagementPackProperty mpp, ManagementPackEnumeration mpe) { StringBuilder sb = new StringBuilder(); sb.Append("<AddInstance>"); sb.Append("<Criteria>"); sb.Append("<Expression>"); sb.Append("<SimpleExpression>"); sb.Append("<ValueExpression>"); sb.Append(String.Format("<Property State=\"Post\">$Context/Property[Type='{0}!{1}']/{2}$</Property>", strMPAlias, mpc.Name, mpp.Name)); sb.Append("</ValueExpression>"); sb.Append("<Operator>Equal</Operator>"); sb.Append("<ValueExpression>"); sb.Append(String.Format("<Value>{{{0}}}</Value>", mpe.Id.ToString())); sb.Append("</ValueExpression>"); sb.Append("</SimpleExpression>"); sb.Append("</Expression>"); sb.Append("</Criteria>"); sb.Append("</AddInstance>"); return(sb.ToString()); }
private void btnCreate_Click(object sender, EventArgs e) { EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtManagementServer.Text); ManagementPackEnumeration mpeSRAreaBase = Helper.GetEnumerationByName("ServiceRequestAreaEnum", emg); ManagementPackEnumeration mpeCRAreaBase = Helper.GetEnumerationByName("ChangeAreaEnum", emg); ManagementPackEnumeration mpeProblemAreaBase = Helper.GetEnumerationByName("ProblemClassificationEnum", emg); ManagementPackEnumeration mpeIncidentAreaBase = Helper.GetEnumerationByName("IncidentClassificationEnum", emg); IList <ManagementPackEnumeration> listSRAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeSRAreaBase.Id, TraversalDepth.Recursive); IList <ManagementPackEnumeration> listCRAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeCRAreaBase.Id, TraversalDepth.Recursive); IList <ManagementPackEnumeration> listProblemAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeProblemAreaBase.Id, TraversalDepth.Recursive); IList <ManagementPackEnumeration> listIncidentAreaEnums = emg.EntityTypes.GetChildEnumerations(mpeIncidentAreaBase.Id, TraversalDepth.Recursive); ManagementPackClass mpcServiceRequest = Helper.GetClassByName("System.WorkItem.ServiceRequest", emg); ManagementPackClass mpcChangeRequest = Helper.GetClassByName("System.WorkItem.ChangeRequest", emg); ManagementPackClass mpcProblem = Helper.GetClassByName("System.WorkItem.Problem", emg); ManagementPackClass mpcIncident = Helper.GetClassByName("System.WorkItem.Incident", emg); ManagementPack mpServiceRequest = Helper.GetManagementPackByName("System.WorkItem.ServiceRequest.Library", emg); ManagementPack mpChangeRequest = Helper.GetManagementPackByName("System.WorkItem.ChangeRequest.Library", emg); ManagementPack mpProblem = Helper.GetManagementPackByName("System.WorkItem.Problem.Library", emg); ManagementPack mpIncident = Helper.GetManagementPackByName("System.WorkItem.Incident.Library", emg); ManagementPackReference mprServiceRequest = new ManagementPackReference(mpServiceRequest); ManagementPackReference mprChangeRequest = new ManagementPackReference(mpChangeRequest); ManagementPackReference mprProblem = new ManagementPackReference(mpProblem); ManagementPackReference mprIncident = new ManagementPackReference(mpIncident); ManagementPack mp = Helper.CreateNewManagementPackInMemory("Queues", "1.0.0.0", "Queues", "QUEUES", emg, true); string strMPAliasServiceRequestLibrary = Helper.MakeMPElementSafeName(mpServiceRequest.Name); string strMPAliasChangeRequestLibrary = Helper.MakeMPElementSafeName(mpChangeRequest.Name); string strMPAliasProblemLibrary = Helper.MakeMPElementSafeName(mpProblem.Name); string strMPAliasIncidentLibrary = Helper.MakeMPElementSafeName(mpIncident.Name); mp.References.Add(strMPAliasServiceRequestLibrary, mprServiceRequest); mp.References.Add(strMPAliasChangeRequestLibrary, mprChangeRequest); mp.References.Add(strMPAliasProblemLibrary, mprProblem); mp.References.Add(strMPAliasIncidentLibrary, mprIncident); double dQueuesToCreate = listSRAreaEnums.Count + listCRAreaEnums.Count + listProblemAreaEnums.Count + listIncidentAreaEnums.Count; pbProgress.Show(); pbProgress.Value = 0; double i = 0; foreach (ManagementPackEnumeration mpeSRArea in listSRAreaEnums) { i++; ManagementPackProperty mppArea = Helper.GetManagementPackClassPropertyByName("System.WorkItem.ServiceRequest", "Area", emg); CreateQueue(mpcServiceRequest, mpeSRArea, strMPAliasServiceRequestLibrary, mppArea, ref mp, emg); pbProgress.Value = (int)(i / dQueuesToCreate * 100); } foreach (ManagementPackEnumeration mpeCRArea in listCRAreaEnums) { i++; ManagementPackProperty mppArea = Helper.GetManagementPackClassPropertyByName("System.WorkItem.ChangeRequest", "Area", emg); CreateQueue(mpcChangeRequest, mpeCRArea, strMPAliasChangeRequestLibrary, mppArea, ref mp, emg); pbProgress.Value = (int)(i / dQueuesToCreate * 100); } foreach (ManagementPackEnumeration mpeProblemClassification in listProblemAreaEnums) { i++; ManagementPackProperty mppClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Problem", "Classification", emg); CreateQueue(mpcProblem, mpeProblemClassification, strMPAliasProblemLibrary, mppClassification, ref mp, emg); pbProgress.Value = (int)(i / dQueuesToCreate * 100); } foreach (ManagementPackEnumeration mpeIncidentClassification in listIncidentAreaEnums) { i++; ManagementPackProperty mppClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Incident", "Classification", emg); CreateQueue(mpcIncident, mpeIncidentClassification, strMPAliasIncidentLibrary, mppClassification, ref mp, emg); pbProgress.Value = (int)(i / dQueuesToCreate * 100); } lblStatus.Text = "Importing Manamgeent Pack..."; emg.ManagementPacks.ImportManagementPack(mp); lblStatus.Text = "Importing Manamgeent Pack...DONE!"; }
public ManagementPackEnumerationDisplayWrapper(ManagementPackEnumeration mpEnum) { ManagementPackEnumeration = mpEnum; }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { // getting the Management Group Connection that is used by the Console (as it should already be open) ConsoleSdkConnection.IManagementGroupSession session = FrameworkServices.GetService <ConsoleSdkConnection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; // verifying if the MG Connection is closed and reconnecting if needed if (!emg.IsConnected) { emg.Reconnect(); } // getting some types we need and which we are going to use further in our code in the actual processing ManagementPack incidentMp = emg.GetManagementPack(ManagementPacks.incidentLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPack wiLibraryMp = emg.GetManagementPack(ManagementPacks.workItemLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPack incidentSettingsMp = emg.GetManagementPack(ManagementPacks.incidentManagementLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPack activityLibMp = emg.GetManagementPack(ManagementPacks.activityLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPackClass incidentClass = emg.EntityTypes.GetClass(ClassTypes.incident, incidentMp); ManagementPackClass analystCommentClass = emg.EntityTypes.GetClass(ClassTypes.analystCommentLog, wiLibraryMp); ManagementPackEnumerationCriteria incidentClosedEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", EnumTypes.incidentStatusClosed)); ManagementPackEnumeration incidentClosedStatus = emg.EntityTypes.GetEnumerations(incidentClosedEnumCriteria).FirstOrDefault(); ManagementPackTypeProjection incidentProjection = emg.EntityTypes.GetTypeProjection(TypeProjections.incidentAdvanced, incidentSettingsMp); // this is needed in order to know which Activities map to which Activity Profix types // this is the case because each Activity can have a different type, but the Prefix used is saved in the same class-object (System.GlobalSetting.ActivitySettings) IDictionary <string, string> activityPrefixMapping = new Dictionary <string, string> { { ActivityTypes.dependent, ActivityPrefixes.dependent }, { ActivityTypes.manual, ActivityPrefixes.manual }, { ActivityTypes.parallel, ActivityPrefixes.parallel }, { ActivityTypes.review, ActivityPrefixes.review }, { ActivityTypes.sequential, ActivityPrefixes.sequential }, { ActivityTypes.runbook, ActivityPrefixes.runbook } }; // setting up the (string) variables which we are going to use to decide what type of WorkItem we are going to create and different options/aspects of it string workItemClassName = string.Empty; string workItemMpName = string.Empty; string workItemSettingClassName = string.Empty; string workItemSettingPrefixName = string.Empty; string workItemSettingMpName = string.Empty; string workItemTemplateName = string.Empty; string workItemStatusName = string.Empty; string workItemUrgencyName = string.Empty; string workItemImpactName = string.Empty; string workItemCategoryName = string.Empty; // if/elseif code to set the variables that define the differences between what WorkItem type we need to create based on the parameter passed by the Task if (parameters.Contains(TaskActions.Service)) { workItemClassName = ClassTypes.service; workItemMpName = ManagementPacks.serviceLibrary; workItemSettingClassName = WorkItemSettings.service; workItemSettingPrefixName = WorkItemPrefixes.service; workItemSettingMpName = ManagementPacks.serviceManagementLibrary; workItemTemplateName = WorkItemTemplates.service; workItemStatusName = EnumTypes.serviceStatusNew; } else if (parameters.Contains(TaskActions.Change)) { workItemClassName = ClassTypes.change; workItemMpName = ManagementPacks.changeLibrary; workItemSettingClassName = WorkItemSettings.change; workItemSettingPrefixName = WorkItemPrefixes.change; workItemSettingMpName = ManagementPacks.changeManagementLibrary; workItemTemplateName = WorkItemTemplates.change; workItemStatusName = EnumTypes.changeStatusNew; } else if (parameters.Contains(TaskActions.Problem)) { workItemClassName = ClassTypes.problem; workItemMpName = ManagementPacks.problemLibrary; workItemSettingClassName = WorkItemSettings.problem; workItemSettingPrefixName = WorkItemPrefixes.problem; workItemSettingMpName = ManagementPacks.problemLibrary; workItemTemplateName = WorkItemTemplates.problem; workItemStatusName = EnumTypes.problemStatusActive; workItemUrgencyName = EnumTypes.problemUrgencyLow; workItemImpactName = EnumTypes.problemImpactLow; workItemCategoryName = EnumTypes.problemCategoryDefault; } else if (parameters.Contains(TaskActions.Release)) { workItemClassName = ClassTypes.release; workItemMpName = ManagementPacks.releaseLibrary; workItemSettingClassName = WorkItemSettings.release; workItemSettingPrefixName = WorkItemPrefixes.release; workItemSettingMpName = ManagementPacks.releaseManagementLibrary; workItemTemplateName = WorkItemTemplates.release; workItemStatusName = EnumTypes.releaseStatusNew; } // here is the code that does the actual work // we wrap this around a try/catch block to handle any exception that may happen and display it in case of failure try { // getting the types we need based on the string variables we have filled earlier based on the WorkItem type we need to create ManagementPack workItemMp = emg.GetManagementPack(workItemMpName, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPack mpSettings = emg.GetManagementPack(workItemSettingMpName, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPack knowledgeLibraryMp = emg.GetManagementPack(ManagementPacks.knowledgeLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPackClass workItemClass = emg.EntityTypes.GetClass(workItemClassName, workItemMp); ManagementPackClass workItemClassSetting = emg.EntityTypes.GetClass(workItemSettingClassName, mpSettings); EnterpriseManagementObject generalSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(workItemClassSetting.Id, ObjectQueryOptions.Default); // here is the foreach loop that processes each class-object (in this case Incident) that was multi-selected in the view before executing the Task foreach (NavigationModelNodeBase node in nodes) { // we need to setup an IList which contains only 1 GUID that correspons to the Incident we are currently working on (node["Id"]) // this is needed because we are using the IObjectProjectionReader.GetData(...) which gets an IList<Guid> as parameter in order to retreive the class-objects we want from the db IList <Guid> bmeIdsList = new List <Guid>(); bmeIdsList.Add(new Guid(node[Constants.nodePropertyId].ToString())); // we are setting up the ObjectProjectionCriteria using the "System.WorkItem.Incident.ProjectionType" Type Projection as we need to get all the Relationships of the Incident // we will use ObjectRetrievalOptions.Buffered so that we don't get any data from the db which we don't need - we will only get the data one we call the IObjectProjectionReader.GetData(...) method // we are getting the data reader object using GetObjectProjectionReader(...) and setting its PageSize to 1 because we only need 1 object retrieved here ObjectProjectionCriteria incidentObjectProjection = new ObjectProjectionCriteria(incidentProjection); ObjectQueryOptions queryOptions = new ObjectQueryOptions(ObjectPropertyRetrievalBehavior.All); queryOptions.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered; IObjectProjectionReader <EnterpriseManagementObject> incidentReader = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(incidentObjectProjection, queryOptions); incidentReader.PageSize = 1; // we are using EnterpriseManagementObjectProjection for the Incident we are getting from the db instead of EnterpriseManagementObject // this is because we are getting a (Type) Projection object (class-object together with its Relationships & relationship class-objects EnterpriseManagementObjectProjection incident = incidentReader.GetData(bmeIdsList).FirstOrDefault(); // we are doing the same for the new WorkItem class-object we are creating because we want to add Relationships (with their relationship class-objects from the Incident) here as well // if we would only have created the new WorkItem class and nothing else with it (no Relationships), we could have used the CreatableEnterpriseManagementObject class (which needs to be used when a new class-object is getting created) EnterpriseManagementObjectProjection workItem = new EnterpriseManagementObjectProjection(emg, workItemClass); // now we need to assign some Template to the new WorkItem (if a default/standard Template exists) in order to already have some Activities created // the Activities and all other Properties of the new WorkItem can be adjusted by modifying the default/standard Template for each WorkItem type if (!string.IsNullOrEmpty(workItemTemplateName)) { ManagementPackObjectTemplateCriteria templateCriteria = new ManagementPackObjectTemplateCriteria(string.Format("Name = '{0}'", workItemTemplateName)); ManagementPackObjectTemplate template = emg.Templates.GetObjectTemplates(templateCriteria).FirstOrDefault(); if (template != null) { // if a Template with this name exists, we apply it to the new WorkItem by calling ApplyTemplate(...) on it workItem.ApplyTemplate(template); // if we have a Template, we also need to process each Activity that it contains in order to set the Prefix for each Activity (based on its type) // we are using the activityPrefixMapping variable we defined above in oder to map each Prefix based on each Activity class-type ManagementPack activityManagementMp = emg.GetManagementPack(ManagementPacks.activityManagementLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPackRelationship workItemContainsActivityRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemContainsActivity, activityLibMp); ManagementPackClass activitySettingsClass = emg.EntityTypes.GetClass(ClassTypes.activitySettings, activityManagementMp); EnterpriseManagementObject activitySettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(activitySettingsClass.Id, ObjectQueryOptions.Default); // for each Activity that exists in the Template we applied, we are going to get its Prefix setting and apply it to its ID in the format: "PREFIX{0}" // "{0}" is the string pattern we need to set for any new WorkItem (including Activity) class-object we are creating as this will be replaced by the next ID available for the new WorkItem foreach (IComposableProjection activity in workItem[workItemContainsActivityRelationshipClass.Target]) { ManagementPackClass activityClass = activity.Object.GetClasses(BaseClassTraversalDepth.None).FirstOrDefault(); string prefix = activitySettings[null, activityPrefixMapping[activityClass.Name]].Value as string; activity.Object[null, ActivityProperties.Id].Value = string.Format("{0}{1}", prefix, Constants.workItemPrefixPattern); } } } // we are setting the Properties for the new WorkItem class-object here from some Properties of the inital Incident (add more as needed) // it is of highest importance that we also set its status to New/Active (depending on WorkItem class-type) in order for it to be properly processed by the internal workflows on creation // if we don't set the the correct "creation" Status here, it will never be able to progress into a working state and will remain stuck in a "pending" state ManagementPackEnumerationCriteria workItemStatusNewEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemStatusName)); ManagementPackEnumeration workItemStatusNew = emg.EntityTypes.GetEnumerations(workItemStatusNewEnumCriteria).FirstOrDefault(); workItem.Object[workItemClass, WorkItemProperties.Id].Value = string.Format("{0}{1}", generalSetting[workItemClassSetting, workItemSettingPrefixName], Constants.workItemPrefixPattern); workItem.Object[workItemClass, WorkItemProperties.Title].Value = string.Format("{0} ({1})", incident.Object[incidentClass, WorkItemProperties.Title].Value, incident.Object[incidentClass, WorkItemProperties.Id].Value); workItem.Object[workItemClass, WorkItemProperties.Description].Value = incident.Object[incidentClass, WorkItemProperties.Description].Value; workItem.Object[workItemClass, WorkItemProperties.Status].Value = workItemStatusNew.Id; // due to the fact that the Problem WorkItem does not have any Template we can use to create it, we need to handle this special case // we need to populate all the required fields when creating the Problem WorkItem, or creating it will fail (Urgency, Impact, Category) if (!string.IsNullOrEmpty(workItemUrgencyName)) { ManagementPackEnumerationCriteria workItemUrgencyEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemUrgencyName)); ManagementPackEnumeration workItemUrgency = emg.EntityTypes.GetEnumerations(workItemUrgencyEnumCriteria).FirstOrDefault(); workItem.Object[workItemClass, WorkItemProperties.Urgency].Value = workItemUrgency.Id; } if (!string.IsNullOrEmpty(workItemImpactName)) { ManagementPackEnumerationCriteria workItemImpactEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemImpactName)); ManagementPackEnumeration workItemImpact = emg.EntityTypes.GetEnumerations(workItemImpactEnumCriteria).FirstOrDefault(); workItem.Object[workItemClass, WorkItemProperties.Impact].Value = workItemImpact.Id; } if (!string.IsNullOrEmpty(workItemCategoryName)) { ManagementPackEnumerationCriteria workItemCategoryEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemCategoryName)); ManagementPackEnumeration workItemCategory = emg.EntityTypes.GetEnumerations(workItemCategoryEnumCriteria).FirstOrDefault(); workItem.Object[workItemClass, WorkItemProperties.Category].Value = workItemCategory.Id; } // we are adding the initial Incident to this new WorkItem as related WorkItem (System.WorkItemRelatesToWorkItem) ManagementPackRelationship workItemToWorkItemRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemRelatesToWorkItem, wiLibraryMp); workItem.Add(incident.Object, workItemToWorkItemRelationshipClass.Target); // we are closing the current Incident by setting its Status to Closed and setting a closed date incident.Object[incidentClass, IncidentProperties.Status].Value = incidentClosedStatus.Id; incident.Object[incidentClass, IncidentProperties.ClosedDate].Value = DateTime.Now.ToUniversalTime(); // we create a new (analyst) comment (System.WorkItem.TroubleTicket.AnalystCommentLog) and we add it to the Incident in oder to comment the fact that it was closed tue to this WorkItem Transfomr Task CreatableEnterpriseManagementObject analystComment = new CreatableEnterpriseManagementObject(emg, analystCommentClass); analystComment[analystCommentClass, AnalystCommentProperties.Id].Value = Guid.NewGuid().ToString(); analystComment[analystCommentClass, AnalystCommentProperties.Comment].Value = string.Format(Constants.incidentClosedComment, workItemClass.Name, workItem.Object.Id.ToString()); analystComment[analystCommentClass, AnalystCommentProperties.EnteredBy].Value = EnterpriseManagementGroup.CurrentUserName; analystComment[analystCommentClass, AnalystCommentProperties.EnteredDate].Value = DateTime.Now.ToUniversalTime(); ManagementPackRelationship incidentHasAnalystCommentRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemHasAnalystComment, wiLibraryMp); incident.Add(analystComment, incidentHasAnalystCommentRelationshipClass.Target); // we create an IList of RelationshipTypes we want to transfer from the Incident to the new WorkItem // this is the place we can add any new/custom RelationshipTypes which we want to transfer // just make sure that the RelationshipType can be transfered from an Incident to any other WorkItem class-type IList <ManagementPackRelationship> relationshipsToAddList = new List <ManagementPackRelationship>() { workItemToWorkItemRelationshipClass, emg.EntityTypes.GetRelationshipClass(RelationshipTypes.createdByUser, wiLibraryMp), emg.EntityTypes.GetRelationshipClass(RelationshipTypes.affectedUser, wiLibraryMp), emg.EntityTypes.GetRelationshipClass(RelationshipTypes.assignedToUser, wiLibraryMp), emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemHasAttachment, wiLibraryMp), emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemAboutConfigItem, wiLibraryMp), emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemRelatesToConfigItem, wiLibraryMp), emg.EntityTypes.GetRelationshipClass(RelationshipTypes.entityToArticle, knowledgeLibraryMp), emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemHasCommentLog, wiLibraryMp), }; // we are getting an instance of the "System.Membership" RelationshipType as we need to handle RelationshipTypes derived from it as a special case // the reason for this, is that Target class-objects of the "System.Membership" RelationshipType are bound to their Source class-objects // being bound, means that Target class-objects of membership relationships cannot belong to 2 different (Source) class-objects // because of this, we need to make a copy (using "CreatableEnterpriseManagementObject" to create a new object and copying the Properties) of the existing Target class-object // and add that to the new WorkItem instead of adding the already existing Target class-object ManagementPack systemLibraryMp = emg.GetManagementPack(ManagementPacks.systemLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version); ManagementPackRelationship membershipRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.membership, systemLibraryMp); // we are going through each Target & Source Relationships of the Incident as defined in the relationshipsToAddList variable and adding them to the new WorkItem // we are handling the Target RelationshipTypes which are derived from "System.Membership" as a special case as explained above // notice that we are also removing these Relationships from the Incident by calling Remove() // we are removing the Relationships from the Incident for performance purposes - in order to have less Relationships (less data) in the db // comment the "itemProjection.Remove();" in order to keep the Relationships to the Incident as well if needed for some reason foreach (ManagementPackRelationship relationship in relationshipsToAddList) { if (incident[relationship.Target].Any()) { foreach (IComposableProjection itemProjection in incident[relationship.Target]) { // create a new Target class-object (CreatableEnterpriseManagementObject) and add it to the projection as it is a member of a Membership RelationshipType (as explained above) // notice that we DON'T remove such a Target class-object Relationship because it will also remove the class-object itself (because it is a Membership RelationshipType object and it cannot exist without this Relationship) // we need it to exist because we are copying data from it and it needs to still exist in the db (ex. Attachments - we still need the binary data to exist in the db when we create the new Attachment object) // we could of course delete it after we create the new WorkItem with its Relationships when calling "workItem.Overwrite()", but I chose not to do it if (relationship.IsSubtypeOf(membershipRelationshipClass)) { CreatableEnterpriseManagementObject instance = new CreatableEnterpriseManagementObject(emg, itemProjection.Object.GetClasses(BaseClassTraversalDepth.None).FirstOrDefault()); foreach (ManagementPackProperty property in itemProjection.Object.GetProperties()) { instance[property.Id].Value = itemProjection.Object[property.Id].Value; } instance[null, Constants.entityId].Value = Guid.NewGuid().ToString(); workItem.Add(instance, relationship.Target); } // just add the existing Target object-class as it is not a member of a Membership RelationshipType (as explained above) else { workItem.Add(itemProjection.Object, relationship.Target); itemProjection.Remove(); } } } if (incident[relationship.Source].Any()) { // we just create the new Relationship of the Source class-object to the new WorkItem because this is not affected by the Membership RelationshipType foreach (IComposableProjection itemProjection in incident[relationship.Source]) { workItem.Add(itemProjection.Object, relationship.Source); itemProjection.Remove(); } } } // this is where we actually save (write) the new data to the db, when calling "Overwrite()" - here saving the Incident we modified (set Status to Closed & deleted Relationships) // before we have just created the new objects and relationships in-memory // this is also the point when almost all of the code validation is being done // if there are any issues really creating/editing/adding these objects/realtionships, this is where we would get the errors incident.Overwrite(); // we are want to handle the error here of saving the new WorkItem and its Relationships because we want to re-open the Incident in case there is an issue when creating the new WorkItem try { // this is where we actually save (write) the new data to the db, when calling "Overwrite()" - here saving the new WorkItem we created with its Relationships we added (from the Incident) workItem.Overwrite(); } catch (Exception ex) { // if we faild to create the new WorkItem with its Relationships, we want to revert to setting the Incident to an Active Status (we re-open the Incident) ManagementPackEnumerationCriteria incidentActiveEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", EnumTypes.incidentStatusActive)); ManagementPackEnumeration incidentActiveStatus = emg.EntityTypes.GetEnumerations(incidentActiveEnumCriteria).FirstOrDefault(); incident.Object[incidentClass, IncidentProperties.Status].Value = incidentActiveStatus.Id; incident.Object[incidentClass, IncidentProperties.ClosedDate].Value = null; // again, after applying the new modifications in memory, we need to actually write them to the db using "Overwrite()" incident.Overwrite(); // no need to show this because we are just passing it (throwing) to the wrapped try/catch block so it will be displayed and handled there throw ex; } } // if everything succeeds, we want to refresh the View (in this case, some View that shows Incidents as this is where we are calling our Task from) // we want to refresh the view to show the new Status of the Incient (as Closed in this case) - if the View only shows non-Closed Incidents, it will dissapear from the View RequestViewRefresh(); } catch (Exception ex) { // we want to handle all Exceptions here so that the Console does not crash // we also want to show a MessageBox window with the Exception details for troubleshooting purposes MessageBox.Show(string.Format("Error: {0}: {1}\n\n{2}", ex.GetType().ToString(), ex.Message, ex.StackTrace)); } }