public static EnterpriseManagementObject GetUserFromEmailAddress(string strEmailAddress, EnterpriseManagementGroup emg) { strEmailAddress = MakeSafeXML(strEmailAddress); ManagementPack mpSystemNotificationsLibrary = GetManagementPackByName("System.Notifications.Library", emg); ManagementPack mpSystemSupportingItemLibrary = GetManagementPackByName("System.SupportingItem.Library", emg); if (mpSystemNotificationsLibrary != null && mpSystemSupportingItemLibrary != null) { EnterpriseManagementObject emoSCSMUser = null; //Criteria to get a user provided the email address string strCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""{0}"" Version=""{1}"" PublicKeyToken=""{2}"" Alias=""NotificationLibrary"" /> <Reference Id=""{3}"" Version=""{4}"" PublicKeyToken=""{5}"" Alias=""SupportingItemLibrary"" /> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Path[Relationship='SupportingItemLibrary!System.UserHasPreference' TypeConstraint='NotificationLibrary!System.Notification.Endpoint']/Property[Type='NotificationLibrary!System.Notification.Endpoint']/TargetAddress$</Property> </ValueExpressionLeft> <Operator>Equal</Operator> <ValueExpressionRight> <Value>{6}</Value> </ValueExpressionRight> </SimpleExpression> </Expression> </Criteria>", mpSystemNotificationsLibrary.Name, mpSystemNotificationsLibrary.Version.ToString(), mpSystemNotificationsLibrary.KeyToken, mpSystemSupportingItemLibrary.Name, mpSystemSupportingItemLibrary.Version.ToString(), mpSystemSupportingItemLibrary.KeyToken, strEmailAddress); ManagementPackTypeProjection mptpUserPreferences = GetTypeProjectionByName("System.User.Preferences.Projection", emg); ObjectProjectionCriteria opcFindNotificationEndPointByEmailAddress = new ObjectProjectionCriteria(strCriteria, mptpUserPreferences, emg); IObjectProjectionReader <EnterpriseManagementObject> readerNotificationEndpoints = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opcFindNotificationEndPointByEmailAddress, ObjectQueryOptions.Default); foreach (EnterpriseManagementObjectProjection emopNotificationEndpointItem in readerNotificationEndpoints) { emoSCSMUser = emopNotificationEndpointItem.Object; } return(emoSCSMUser); } else { return(null); } }
private void UpdateNamedIncident(EnterpriseManagementGroup emg, string id) { // Define the type projection that you want to query for. // This example queries for type projections defined by the System.WorkItem.Incident.ProjectionType // type in the ServiceManager.IncidentManagement.Library management pack. ManagementPackTypeProjection incidentTypeProjection = SMHelpers.GetManagementPackTypeProjection(TypeProjections.System_WorkItem_Incident_ProjectionType, SMHelpers.GetManagementPack(ManagementPacks.ServiceManager_IncidentManagement_Library, emg), emg); // Define the query criteria string. // This is XML that validates against the Microsoft.EnterpriseManagement.Core.Criteria schema. string incidentCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""System.WorkItem.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""WorkItem"" /> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Context/Property[Type='WorkItem!System.WorkItem']/Id$</Property> </ValueExpressionLeft> <Operator>Equal</Operator> <ValueExpressionRight> <Value>" + _ID + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> </Criteria> ", workitemMp.KeyToken, workitemMp.Version.ToString()); WriteDebug(incidentCriteria); // Define the criteria object by using one of the criteria strings. ObjectProjectionCriteria criteria = new ObjectProjectionCriteria(incidentCriteria, incidentTypeProjection, emg); EnterpriseManagementObjectProjection emop = null; // For each retrieved type projection, display the properties. foreach (EnterpriseManagementObjectProjection projection in emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(criteria, ObjectQueryOptions.Default)) { emop = projection; } if (emop != null) { SMHelpers.UpdateIncident(emg, clsIncident, emop, this.Impact, this.Urgency, this.Status, this.Classification, this.Source, this.SupportGroup, this.Comment, this.UserComment, this.Description, this.AttachmentPath); } else { WriteError(new ErrorRecord(new ObjectNotFoundException(_ID), "Incident not found", ErrorCategory.ObjectNotFound, criteria)); return; } }
public static ManagementPackTypeProjection GetManagementPackTypeProjectionByName(string strTypeProjectionName, string strManagementPackName, EnterpriseManagementGroup emg) { ManagementPackTypeProjection mptpToReturn = null; ManagementPackTypeProjectionCriteria mptpc = new ManagementPackTypeProjectionCriteria(String.Format("Name = '{0}'", strTypeProjectionName)); foreach (ManagementPackTypeProjection mptp in emg.EntityTypes.GetTypeProjections(mptpc)) { if (mptp.GetManagementPack().Name == strManagementPackName) { mptpToReturn = mptp; } } return(mptpToReturn); }
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()); }
void processReleaseRecords() { ManagementPackTypeProjection mptpReleaseRecordHasProject = emg.EntityTypes.GetTypeProjection("Cireson.ProjectAutomation.ReleaseRecordHasProject.ProjectionType", mpManagementPacks.First(mp => mp.Name == "Cireson.ProjectAutomation.Library")); ObjectProjectionCriteria opcCriteria = new ObjectProjectionCriteria(xmlReleaseRecordHasProjectCriteria, mptpReleaseRecordHasProject, mpManagementPacks.First(mp => mp.Name == "System.WorkItem.ReleaseRecord.Library"), emg); //get the type projection var releaseRecordProjection = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opcCriteria, ObjectQueryOptions.Default).Where( p => p.Any(e => e.Value.Object.IsInstanceOf(mpcClasses.First(mpc => mpc.Name == "Cireson.ProjectAutomation.Project")))); if (releaseRecordProjection.Count() > 0) { EventLog.WriteEntry(strEventLogTitle, string.Format("{0} Release Records have a Project related and are 'In-Progress' or in 'Editing' mode. Processing Release Records.", releaseRecordProjection.Count())); } else { EventLog.WriteEntry(strEventLogTitle, "No Release Records have a related Project and are 'In-Progress' or in 'Editing' mode."); } foreach (EnterpriseManagementObjectProjection emo in releaseRecordProjection) { try { EnterpriseManagementObject emoReleaseRecord = emo.Object; EnterpriseManagementObject emoProject = emo.FirstOrDefault(e => e.Value.Object.IsInstanceOf(mpcClasses.First(mpc => mpc.Name == "Cireson.ProjectAutomation.Project"))).Value.Object as EnterpriseManagementObject; if (emoProject != null) { //log the found release record relationship EventLog.WriteEntry(strEventLogTitle, string.Format( "The Release Record '{0}' is in '{1}' status. Project '{2}' is the task source. Begining sync of tasks from Project Server to the Release Record...", emoReleaseRecord.DisplayName, releaseStatusEnums.First(e => e == emoReleaseRecord[null, "Status"].Value).DisplayName, emoProject.DisplayName)); buildReleaseRecord(emoReleaseRecord, emoProject); } } catch (EnterpriseManagementException ex) { exceptionsList.Add(new ReleaseRecordProcessingException(string.Format("An error occured while processing '{0}'.", emo.Object.DisplayName), ex)); } } }
private void TestGettingARandomNumberOfIncidents() { EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtServerName.Text); ManagementPackClass mpcIncident = Helper.GetClassByName("System.WorkItem.Incident", emg); ManagementPack mpIncidentLibrary = mpcIncident.GetManagementPack(); ManagementPackTypeProjection mptpIncidentFull = Helper.GetTypeProjectionByName("System.WorkItem.Incident.ProjectionType", emg); string strCriteria = Helper.SearchWorkItemByLikeIDCriteriaXml("2", mpIncidentLibrary.Name, mpIncidentLibrary.Version.ToString(), mpIncidentLibrary.KeyToken, mpcIncident.Name); IObjectProjectionReader <EnterpriseManagementObject> reader = Helper.GetBufferedObjectProjectionReader(strCriteria, 30, mptpIncidentFull, emg); double dIncidentIDSum = 0; foreach (EnterpriseManagementObjectProjection emop in reader) { string strID = emop.Object[mpcIncident, "Id"].Value.ToString(); dIncidentIDSum += (double)Int32.Parse(strID); } MessageBox.Show(dIncidentIDSum.ToString()); }
private void TestGettingIncidentsByGUIDVsWorkItemID() { EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtServerName.Text); ManagementPackClass mpcIncident = Helper.GetClassByName("System.WorkItem.Incident", emg); ManagementPack mpIncidentLibrary = mpcIncident.GetManagementPack(); IObjectReader <EnterpriseManagementObject> readerAllIncidents = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(mpcIncident, ObjectQueryOptions.Default); ManagementPackTypeProjection mptpIncidentFull = Helper.GetTypeProjectionByName("System.WorkItem.Incident.ProjectionType", emg); double dByGUIDElapsedTime = 0; double dByWorkItemIDElapsedTime = 0; double dNumberOfTries = 1000; double i = 0; do { i++; int intRandomIncident = Helper.GetRandomNumber(0, readerAllIncidents.Count); EnterpriseManagementObject emoIncident = readerAllIncidents.ElementAtOrDefault <EnterpriseManagementObject>(intRandomIncident); Guid guidIncidentId = emoIncident.Id; string strWorkItemID = emoIncident[mpcIncident, "Id"].Value.ToString(); DateTime dtByGUIDStart = DateTime.Now; EnterpriseManagementObjectProjection emopIncident = emg.EntityObjects.GetObjectProjectionWithAccessRights <EnterpriseManagementObject>(emoIncident.Id, mptpIncidentFull); DateTime dtByGUIDEnd = DateTime.Now; TimeSpan tsByGUID = dtByGUIDEnd - dtByGUIDStart; dByGUIDElapsedTime += tsByGUID.Milliseconds; DateTime dtByWorkItemIDStart = DateTime.Now; string strCriteria = Helper.SearchWorkItemByIDCriteriaXml(strWorkItemID, mpIncidentLibrary.Name, mpIncidentLibrary.Version.ToString(), mpIncidentLibrary.KeyToken, mpcIncident.Name); IObjectProjectionReader <EnterpriseManagementObject> readerIncident = Helper.GetBufferedObjectProjectionReader(strCriteria, 1, mptpIncidentFull, emg); DateTime dtByWorkItemIDEnd = DateTime.Now; TimeSpan tsByWorkItemID = dtByWorkItemIDEnd - dtByWorkItemIDStart; dByWorkItemIDElapsedTime += tsByWorkItemID.Milliseconds; pbProgress.Value = (int)(i / dNumberOfTries * 100); }while (i < dNumberOfTries); MessageBox.Show(string.Format("By GUID: {0} By Work Item ID: {1}", dByGUIDElapsedTime.ToString(), dByWorkItemIDElapsedTime.ToString())); }
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); //} } } }
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)); } }
public static void CopyRelationships(EnterpriseManagementObjectProjection emopToBeCopiedFrom, ref EnterpriseManagementObjectProjection emopToBeCopiedTo, ManagementPackTypeProjection mptp, string[] strAliasesToExclude) { foreach (ManagementPackTypeProjectionComponent mptpc in mptp.ComponentCollection) { if (Array.IndexOf(strAliasesToExclude, mptpc.Alias) == -1) { foreach (IComposableProjection icp in emopToBeCopiedFrom[mptpc.TargetEndpoint]) { emopToBeCopiedTo.Add(icp.Object, mptpc.TargetEndpoint); } } } }
public static IObjectProjectionReader <EnterpriseManagementObject> GetBufferedObjectProjectionReader(string strCriteria, int intNumberOfItemsToGet, ManagementPackTypeProjection mptp, EnterpriseManagementGroup emg) { if (intNumberOfItemsToGet > 0) { ObjectProjectionCriteria opc = new ObjectProjectionCriteria(strCriteria, mptp, emg); ObjectQueryOptions oqo = new ObjectQueryOptions(); oqo.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered; oqo.MaxResultCount = intNumberOfItemsToGet; oqo.DefaultPropertyRetrievalBehavior = ObjectPropertyRetrievalBehavior.All; IObjectProjectionReader <EnterpriseManagementObject> reader = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opc, oqo); return(reader); } else { return(null); } }
private List <EnterpriseManagementObject> SetSLAStatus(String strQueryCriteria, ManagementPackTypeProjection mptp, EnterpriseManagementGroup emg, String strSLAStatusID) { List <EnterpriseManagementObject> listObjects = new List <EnterpriseManagementObject>(); ObjectProjectionCriteria opc = new ObjectProjectionCriteria(strQueryCriteria, mptp, emg); foreach (EnterpriseManagementObjectProjection emop in emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opc, ObjectQueryOptions.Default)) { if (strSLAStatusID != "") { emop.Object[null, "SLAStatus"].Value = emg.EntityTypes.GetEnumeration(new Guid(strSLAStatusID)).Id; } else { emop.Object[null, "SLAStatus"].Value = null; } emop.Object.Overwrite(); listObjects.Add(emop.Object); } return(listObjects); }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { //TEMPORARY - Used for Debugging only Thread.Sleep(30000); EnterpriseManagementConnectionSettings connSettings; if (!String.IsNullOrEmpty(this.ServerName)) { connSettings = new EnterpriseManagementConnectionSettings(this.ServerName); } else { connSettings = new EnterpriseManagementConnectionSettings("localhost"); } if (!String.IsNullOrEmpty(this.UserName) && !String.IsNullOrEmpty(this.Password)) { connSettings.UserName = this.UserName; connSettings.Password = new System.Security.SecureString(); foreach (var item in this.Password.ToCharArray()) { connSettings.Password.AppendChar(item); } } this.emg = new EnterpriseManagementGroup(connSettings); // References to management packs that contain classes used in this example. ManagementPack mpSystem = emg.ManagementPacks.GetManagementPack(SystemManagementPack.System); ManagementPack mpIncident = emg.ManagementPacks.GetManagementPack("ServiceManager.IncidentManagement.Library", mpSystem.KeyToken, mpSystem.Version); ManagementPackTypeProjection incidentTypeProjection = emg.EntityTypes.GetTypeProjection("System.WorkItem.Incident.ProjectionType", mpIncident); const String INCIDENT_SLA_SETTINGS_OBJECT_GUID = "4AD8DC00-2333-93D6-5EB4-D372A42DEA7B"; const String INCIDENT_SLA_BREACH_WARNING_THRESHOLD_PROPERTY_GUID = "BE79DAC0-A04E-8A36-708A-F1497B1F9608"; const String INCIDENT_SLA_STATUS_WARNING_ENUM_GUID = "CFD5CB2F-F5E8-0CA8-8699-E1C2C19477FA"; const String INCIDENT_SLA_STATUS_BREACHED_ENUM_GUID = "1DECB743-AF62-B72F-74DB-92124A05F676"; //Get the Object using the GUID from above - since this is a singleton object we can get it by GUID EnterpriseManagementObject emoIncidentSLASettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(INCIDENT_SLA_SETTINGS_OBJECT_GUID), ObjectQueryOptions.Default); TimeSpan tsWarningThreshold; Int32 intWarningThreshold; if (this.WarningThreshold == TimeSpan.Zero) //Not specified { if (!Int32.TryParse(emoIncidentSLASettings[new Guid(INCIDENT_SLA_BREACH_WARNING_THRESHOLD_PROPERTY_GUID)].ToString(), out intWarningThreshold)) { intWarningThreshold = 0; } tsWarningThreshold = new TimeSpan(0, intWarningThreshold, 0); } else { tsWarningThreshold = this.WarningThreshold; } string incidentBreachedCriteria = string.Empty; string incidentWarningCriteria = string.Empty; string incidentRevertToBlankCriteria = string.Empty; // Define the query criteria string for each of the queries // This XML validates against the Microsoft.EnterpriseManagement.Core.Criteria schema. #region IncidentBreachedCriteria /* * This criteria allows for the following scenario: * incident is created with Target Resolution Time (TRT) * time passes until TRT < Now() * incident is marked as SLA Status = Breached * * ignore incidents which are already marked Breached * ignore incidents which are already resolved (i.e. Resolved Date is not null) * */ incidentBreachedCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""System.WorkItem.Incident.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""IncidentManagement"" /> <Expression> <And> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/TargetResolutionTime$</Property> </ValueExpressionLeft> <Operator>Less</Operator> <ValueExpressionRight> <Value>" + DateTime.Parse(DateTime.UtcNow.ToString()).ToString() + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> <Expression> <Or> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/SLAStatus$</Property> </ValueExpressionLeft> <Operator>NotEqual</Operator> <ValueExpressionRight> <Value>" + "{{" + INCIDENT_SLA_STATUS_BREACHED_ENUM_GUID + "}}" + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> <Expression> <UnaryExpression> <ValueExpression> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/SLAStatus$</Property> </ValueExpression> <Operator>IsNull</Operator> </UnaryExpression> </Expression> </Or> </Expression> <Expression> <UnaryExpression> <ValueExpression> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/ResolvedDate$</Property> </ValueExpression> <Operator>IsNull</Operator> </UnaryExpression> </Expression> </And> </Expression> </Criteria> ", mpSystem.KeyToken, mpSystem.Version.ToString()); #endregion #region IncidentWarningCriteria /* * This criteria allows for the following scenario: * incident is created with Target Resolution Time (TRT) * time passes until TRT > Now()-Warning Period AND the incident has not already been marked as Breached. * incident is marked as SLA Status = Warning * * ignore incidents which are already marked Breached * ignore incidents which are already marked Warning * ignore incidents which are already resolved (i.e. Resolved Date is not null) * */ incidentWarningCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""System.WorkItem.Incident.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""IncidentManagement"" /> <Expression> <And> <Expression> <UnaryExpression> <ValueExpression> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/ResolvedDate$</Property> </ValueExpression> <Operator>IsNull</Operator> </UnaryExpression> </Expression> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/TargetResolutionTime$</Property> </ValueExpressionLeft> <Operator>Less</Operator> <ValueExpressionRight> <Value>" + DateTime.Parse(DateTime.UtcNow.Add(tsWarningThreshold).ToString()).ToString() + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> <Expression> <UnaryExpression> <ValueExpression> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/SLAStatus$</Property> </ValueExpression> <Operator>IsNull</Operator> </UnaryExpression> </Expression> </And> </Expression> </Criteria> ", mpSystem.KeyToken, mpSystem.Version.ToString()); #endregion #region IncidentRevertToBlankCriteria /* * This criteria allows for the following case * incident is created with Target Resolution Time (TRT) * time passes until TRT > Now()-Warning Period * incident is marked as SLA Status = Warning * incident urgency or priority is changed such that the Target Resolution Time **INCREASES** to a new Target Resolution Time (TRTNew). * if TRTNew < Now() - Warning Period, the incident SLA status should be reverted to blank. * * ignore incidents which are already resolved (i.e. Resolved Date is not null) */ incidentRevertToBlankCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""System.WorkItem.Incident.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""IncidentManagement"" /> <Expression> <And> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/TargetResolutionTime$</Property> </ValueExpressionLeft> <Operator>Greater</Operator> <ValueExpressionRight> <Value>" + DateTime.Parse(DateTime.UtcNow.Add(tsWarningThreshold).ToString()).ToString() + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/SLAStatus$</Property> </ValueExpressionLeft> <Operator>Equal</Operator> <ValueExpressionRight> <Value>" + "{{" + INCIDENT_SLA_STATUS_WARNING_ENUM_GUID + "}}" + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> <Expression> <UnaryExpression> <ValueExpression> <Property>$Target/Property[Type='IncidentManagement!System.WorkItem.Incident']/ResolvedDate$</Property> </ValueExpression> <Operator>IsNull</Operator> </UnaryExpression> </Expression> </And> </Expression> </Criteria> ", mpSystem.KeyToken, mpSystem.Version.ToString()); #endregion //Breached must be processed first, then warning, then revert List <EnterpriseManagementObject> listBreachedIncidents = SetSLAStatus(incidentBreachedCriteria, incidentTypeProjection, emg, INCIDENT_SLA_STATUS_BREACHED_ENUM_GUID); List <EnterpriseManagementObject> listWarningIncidents = SetSLAStatus(incidentWarningCriteria, incidentTypeProjection, emg, INCIDENT_SLA_STATUS_WARNING_ENUM_GUID); List <EnterpriseManagementObject> listRevertToBlankIncidents = SetSLAStatus(incidentRevertToBlankCriteria, incidentTypeProjection, emg, ""); this.BreachedIncidents = listBreachedIncidents.ToArray(); this.WarningIncidents = listWarningIncidents.ToArray(); this.RevertToBlankIncidents = listRevertToBlankIncidents.ToArray(); return(ActivityExecutionStatus.Closed); }
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); }
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') { ; } }
void processChangeRequests() { //get a list of projects with a change request associated to them. ManagementPackTypeProjection mptpChangeRequestHasProject = emg.EntityTypes.GetTypeProjection("Cireson.ProjectAutomation.ChangeRequestHasProjectAndDependentActivities.ProjectionType", mpManagementPacks.First(mp => mp.Name == "Cireson.ProjectAutomation.Library")); //set up the type projection criteria ObjectProjectionCriteria opcCriteria = new ObjectProjectionCriteria(xmlChangeRequestHasProjectCriteria, mptpChangeRequestHasProject, mpManagementPacks.First(mp => mp.Name == "System.WorkItem.ChangeRequest.Library"), emg); //get the type projection var changeRequestProjection = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opcCriteria, ObjectQueryOptions.Default).Where( p => p.Any(e => e.Value.Object.IsInstanceOf(mpcClasses.First(mpc => mpc.Name == "Cireson.ProjectAutomation.Project")))); //log the number of change requests processed. if (changeRequestProjection.Count() > 0) { EventLog.WriteEntry(strEventLogTitle, string.Format("{0} Change Requests have a Project and are in an 'In-Progress' status. Processing Change Requests...", changeRequestProjection.Count())); } else { EventLog.WriteEntry(strEventLogTitle, string.Format("{0} Change Requests have a Project and are in an 'In-Progress' status. Exiting workflow.", changeRequestProjection.Count())); } foreach (EnterpriseManagementObjectProjection emo in changeRequestProjection) { try { //get the work item and the project EnterpriseManagementObject emoChangeRequest = emo.Object; EnterpriseManagementObject emoProject = emo.FirstOrDefault(e => e.Value.Object.IsInstanceOf(mpcClasses.First(mpc => mpc.Name == "Cireson.ProjectAutomation.Project"))).Value.Object as EnterpriseManagementObject; var dependentActivities = emo.Where(e => e.Value.Object.IsInstanceOf(mpcClasses.First(mpc => mpc.Name == "System.WorkItem.Activity.DependentActivity"))); //if there are dependent activities and we have a project, continue on... if (dependentActivities.Count() > 0 && emoProject != null) { foreach (var dependentActivity in dependentActivities) { try { EnterpriseManagementObject dependsOnWorkItemActivity = emg.EntityObjects.GetRelatedObjects <EnterpriseManagementObject>(dependentActivity.Value.Object.Id, mprRelationships.First(r => r.Name == "System.DependentActivityDependsOnWorkItem"), TraversalDepth.OneLevel, ObjectQueryOptions.Default).FirstOrDefault(); if (dependsOnWorkItemActivity != null) { //get the parent work item (release record). EnterpriseManagementObject emoReleaseRecord = emg.EntityObjects.GetParentObjects <EnterpriseManagementObject>(dependsOnWorkItemActivity.Id, ObjectQueryOptions.Default).FirstOrDefault( e => e.IsInstanceOf(mpcClasses.First(mpc => mpc.Name == "System.WorkItem.ReleaseRecord"))); // only process release records that are 'In-Progress', "On-Hold', or in 'Editing' status. if (emoReleaseRecord != null && ( emoReleaseRecord[null, "Status"].Value == releaseStatusEnums.First(e => e.Name == "ReleaseStatusEnum.InProgress") || emoReleaseRecord[null, "Status"].Value == releaseStatusEnums.First(e => e.Name == "ReleaseStatusEnum.Editing") || emoReleaseRecord[null, "Status"].Value == releaseStatusEnums.First(e => e.Name == "ReleaseStatusEnum.OnHold"))) { //log the found release record relationship EventLog.WriteEntry(strEventLogTitle, string.Format( "Change Request '{0}' is related to Release Record '{1}' through a Dependent Activity. " + "The Release Record is in '{2}' status. " + "Project '{3}' is the task source. Begining sync of tasks from Project Server to the Release Record...", emoChangeRequest.DisplayName, emoReleaseRecord.DisplayName, releaseStatusEnums.First(e => e == emoReleaseRecord[null, "Status"].Value).DisplayName, emoProject.DisplayName)); buildReleaseRecord(emoReleaseRecord, emoProject); } } } catch (EnterpriseManagementException ex) { exceptionsList.Add(new DependentActivityProcessingException(string.Format("An error occured while processing '{0}' related to '{1}'.", dependentActivity.Value.Object.DisplayName, emo.Object.DisplayName), ex)); } } } } catch (EnterpriseManagementException ex) { exceptionsList.Add(new ChangeRecordProcessingException(string.Format("An error occured while processing '{0}'", emo.Object.DisplayName), ex)); } } }