private void UpdateConnectorInstance() { //Get the server name to connect to and connect String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString(); EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName); //Get the Connectors MP and AA Connector Class ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0")); ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector"); //Get the Connector object using the object ID EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default); //Set the property values to the new values emoAAConnector[classAAConnector, "DisplayName"].Value = this.DisplayName; emoAAConnector[classAAConnector, "AutomationAccount"].Value = this.AutomationAccount; emoAAConnector[classAAConnector, "SubscriptionID"].Value = this.SubscriptionID; emoAAConnector[classAAConnector, "ResourceGroup"].Value = this.ResourceGroup; emoAAConnector[classAAConnector, "RunAsAccountName"].Value = this.RunAsAccountName; emoAAConnector[classAAConnector, "RunAsAccountPassword"].Value = this.RunAsAccountPassword; emoAAConnector[classAAConnector, "RefreshIntervalHours"].Value = this.RefreshIntervalHours; //Update Connector instance emoAAConnector.Commit(); mpConnectors.AcceptChanges(); }
private void SetQueueStatus(Boolean bEnabled) { EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtManagementServer.Text); //TODO: Switch this back to 'WorkItemGroup.%' Had to temporarily change this due to a bad naming convention in the code that has been fixed. string strQueueDiscoveryCriteria = "Name LIKE '[cspi]%Discovery%'"; ManagementPackDiscoveryCriteria mpdc = new ManagementPackDiscoveryCriteria(strQueueDiscoveryCriteria); IList <ManagementPackDiscovery> listDiscoveries = emg.Monitoring.GetDiscoveries(mpdc); pbProgress.Value = 0; pbProgress.Show(); double dDiscoveriesCount = listDiscoveries.Count; double i = 0; ManagementPack mp = null; foreach (ManagementPackDiscovery discovery in listDiscoveries) { i++; if (bEnabled == true) { discovery.Enabled = ManagementPackMonitoringLevel.@true; } else { discovery.Enabled = ManagementPackMonitoringLevel.@false; } discovery.Status = ManagementPackElementStatus.PendingUpdate; mp = discovery.GetManagementPack(); double dComplete = i / dDiscoveriesCount * 100; pbProgress.Value = (int)dComplete; } mp.AcceptChanges(); }
public bool DeleteProjectConnector(IDataItem item) { try { //get the connector class. Later we will get the type projection so we can delete related objects. //item = ConsoleContextHelper.Instance.GetInstance((Guid)item["$Id$"]); //get type projection of the connector (Cireson.ProjectAutomation.ConnectorRelatesToProjects.ProjectionType) (34e516cf-644f-11b7-be02-6c886ec0573b) item = ConsoleContextHelper.Instance.GetProjectionInstance((Guid)item["$Id$"], new Guid("34e516cf-644f-11b7-be02-6c886ec0573b")); //add in some sort of confirmation on delete... later. if (MessageBox.Show( String.Format(ServiceManagerLocalization.GetStringFromManagementPack("strConfirmDelete") + " {0}", item["DisplayName"]), ServiceManagerLocalization.GetStringFromManagementPack("strDeleteConnector"), MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No) { return(false); } var emg = ConsoleContext.GetConsoleEMG(); var emoConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>((Guid)item["$Id$"], ObjectQueryOptions.Default); var iddRemove = new IncrementalDiscoveryData(); // (Cireson.ProjectAutomation.Library) (System.ProjectConfigItemRelatesToProjectConnector) (da061582-3f6c-d7b7-d17d-0a91b8a51ace) ManagementPackRelationship mprConnectorHasProject = emg.EntityTypes.GetRelationshipClass(new Guid("da061582-3f6c-d7b7-d17d-0a91b8a51ace")); //remove the related project CIs. foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> obj in emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(emoConnector.Id, mprConnectorHasProject, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default)) { iddRemove.Remove(obj.TargetObject); } //remove workflow rule for the connector try { //Cireson Project Server Automation Library Configuration (Cireson.ProjectAutomation.Library.Configuration) (19b2a173-bea9-9e50-0709-1470424916f2) ManagementPack mpConnectorWorkflow = emg.ManagementPacks.GetManagementPack(new Guid("19b2a173-bea9-9e50-0709-1470424916f2")); //Project Server Connector (Cireson.ProjectAutomation.Library) (Microsoft.SystemCenter.Connector.ProjectServer) (d581d2d6-b6cd-b558-7ac7-db233a7c82ec) ManagementPackClass mpcConnector = emg.EntityTypes.GetClass(new Guid("d581d2d6-b6cd-b558-7ac7-db233a7c82ec")); string sConnectorRuleId = string.Format("{0}.{1}", "Cireson.ProjectServer.Automation", new Guid(emoConnector[mpcConnector, "Id"].Value.ToString()).ToString("N")); ManagementPackRule mprConnector = mpConnectorWorkflow.GetRule(sConnectorRuleId); mprConnector.Status = ManagementPackElementStatus.PendingDelete; mpConnectorWorkflow.AcceptChanges(); } catch { } iddRemove.Remove(emoConnector); iddRemove.Commit(emg); return(true); } catch (Exception ex) { ConsoleContextHelper.Instance.ShowErrorDialog(ex, string.Empty, ConsoleJobExceptionSeverity.Error); return(false); } }
//--------------------------------------------------------------------- internal ManagementPackOverride PerformMove() { ManagementPackOverride targetOverride; AddDependencyIfNeeded(); CreateTargetOverride(out targetOverride); m_mpOverride.Status = ManagementPackElementStatus.PendingDelete; // dmuscett 2012-03-02 first save the NEW one, THEN delete the old one. // this can lead to duplicates, but at least prevents the issue where the old one is // removed and the new one fails to apply, effectively deleting it... m_targetMp.AcceptChanges(); m_sourceMp.AcceptChanges(); return(targetOverride); }
private void UpdateConnectorInstance() { //Get the server name to connect to and connect String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString(); EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName); //Get the Connectors MP and CSV Connector Class ManagementPack mpConnectors = emg.GetManagementPack("Microsoft.Demo.Connectors", null, new Version("1.0.0.0")); ManagementPackClass classCSVConnector = mpConnectors.GetClass("Microsoft.Demo.Connectors.CSVConnector"); //Get the Connector object using the object ID EnterpriseManagementObject emoCSVConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default); //Set the property values to the new values emoCSVConnector[classCSVConnector, "DisplayName"].Value = this.DisplayName; emoCSVConnector[classCSVConnector, "DataFilePath"].Value = this.DataFilePath; emoCSVConnector[classCSVConnector, "DataFilePath"].Value = this.DataFilePath; emoCSVConnector[classCSVConnector, "MappingFilePath"].Value = this.MappingFilePath; emoCSVConnector[classCSVConnector, "NumberMinutes"].Value = this.NumberMinutes; //Update Connector instance emoCSVConnector.Commit(); //Get the rule using the Connector ID and then update the data source and write action module configuration ManagementPackRule ruleConnector = mpConnectors.GetRule(this.ConnectorID); ruleConnector.DataSourceCollection[0].Configuration = "<Scheduler>" + "<SimpleReccuringSchedule>" + "<Interval Unit=\"Minutes\">" + this.NumberMinutes + "</Interval>" + "</SimpleReccuringSchedule>" + "<ExcludeDates />" + "</Scheduler>"; ruleConnector.WriteActionCollection[0].Configuration = "<Subscription>" + "<WindowsWorkflowConfiguration>" + "<AssemblyName>CSVConnectorWorkflow</AssemblyName>" + "<WorkflowTypeName>WorkflowAuthoring.CSVConnectorWorkflow</WorkflowTypeName>" + "<WorkflowParameters>" + "<WorkflowParameter Name=\"DataFilePath\" Type=\"string\">" + this.DataFilePath + "</WorkflowParameter>" + "<WorkflowParameter Name=\"FormatFilePath\" Type=\"string\">" + this.MappingFilePath + "</WorkflowParameter>" + "</WorkflowParameters>" + "<RetryExceptions />" + "<RetryDelaySeconds>60</RetryDelaySeconds>" + "<MaximumRunningTimeSeconds>300</MaximumRunningTimeSeconds>" + "</WindowsWorkflowConfiguration>" + "</Subscription>"; ruleConnector.Status = ManagementPackElementStatus.PendingUpdate; mpConnectors.AcceptChanges(); }
private void SetRuleStatus(bool bEnabled) { EnterpriseManagementGroup emg = new EnterpriseManagementGroup(txtManagementServer.Text); string strRuleCriteria = "Name LIKE 'NotificationSubscription%'"; ManagementPackRuleCriteria mprc = new ManagementPackRuleCriteria(strRuleCriteria); IList <ManagementPackRule> listRules = emg.Monitoring.GetRules(mprc); double dRulesCount = listRules.Count; double i = 0; pbProgress.Value = 0; pbProgress.Style = ProgressBarStyle.Continuous; pbProgress.Show(); //TODO: Undo this MP hackery. ManagementPack mp = null; foreach (ManagementPackRule rule in listRules) { i++; if (rule.Enabled != ManagementPackMonitoringLevel.@false && bEnabled == false) { rule.Enabled = ManagementPackMonitoringLevel.@false; rule.Status = ManagementPackElementStatus.PendingUpdate; //TODO: Undo this MP hackery. mp = rule.GetManagementPack(); } else if (rule.Enabled != ManagementPackMonitoringLevel.@true && bEnabled == true) { rule.Enabled = ManagementPackMonitoringLevel.@true; rule.Status = ManagementPackElementStatus.PendingUpdate; //TODO: Undo this MP hackery. mp = rule.GetManagementPack(); } double dProgress = i / (dRulesCount) * 100; pbProgress.Value = (int)dProgress; } pbProgress.Style = ProgressBarStyle.Marquee; lblStatus.Text = "Accepting changes to MP..."; mp.AcceptChanges(); pbProgress.Style = ProgressBarStyle.Continuous; pbProgress.Value = 100; lblStatus.Text = "Done!"; lblStatus.ForeColor = Color.Red; lblStatus.Height = lblStatus.Height * 3; return; }
//TODO: Add support for this at some point /* * [Parameter(ValueFromPipeline = false, Mandatory = false)] * public ManagementPackImage Image * { * get { return _image; } * set { _image = value; } * } */ protected override void ProcessRecord() { base.ProcessRecord(); //Create a new folder and set it's parent folder and display name ManagementPackFolder folder = new ManagementPackFolder(_managementpack, SMHelpers.MakeMPElementSafeUniqueIdentifier("Folder"), ManagementPackAccessibility.Public); folder.DisplayName = _displayname; folder.ParentFolder = _parentfolder; //TODO: Parameterize this someday //Set the systemfolder icon to be the icon that is used ManagementPackElementReference <ManagementPackImage> foldericonreference = (ManagementPackElementReference <ManagementPackImage>)_mg.Resources.GetResource <ManagementPackImage>(Images.Microsoft_EnterpriseManagement_ServiceManager_UI_Console_Image_Folder, SMHelpers.GetManagementPack(ManagementPacks.Microsoft_EnterpriseManagement_ServiceManager_UI_Console, _mg)); ManagementPackImageReference image = new ManagementPackImageReference(folder, foldericonreference, _managementpack); //Submit changes _managementpack.AcceptChanges(); }
protected override void ProcessRecord() { base.ProcessRecord(); ManagementPackView view = _mg.Presentation.GetView(_view.Id); ManagementPack mp = view.GetManagementPack(); view.Status = ManagementPackElementStatus.PendingDelete; string viewInfo = view.Name; if (view.DisplayName != null) { viewInfo = view.DisplayName; } if (ShouldProcess(viewInfo)) { mp.AcceptChanges(); } }
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); }
/// <summary> /// Save the management pack to the active connection. /// </summary> private void SaveManagementPack() { UpLevelVersion(); try { configurationOverridePack.Verify(); configurationOverridePack.AcceptChanges(); Log.WriteTrace( EventType.ExternalDependency, "Successfully saved the updated management pack", configurationOverridePack.Version.ToString()); } catch (Exception ex) { Log.WriteError( EventType.ExternalDependency, "Unable to save the updated management pack", ex.Message); throw; } }
/// <summary> /// Creates the mp. /// </summary> private static void CreateESightConfigLibraryMp() { try { // var apmMpPath = @"E:\Projects\scom-plugin\SCOM\release\MPFiles\Temp"; OnLog("CreateESightConfigLibraryMp-ScomInstallPath:" + ScomInstallPath); var apmMpPath = $"{ScomInstallPath}\\Server\\ApmConnector"; OnLog(apmMpPath); var keyPath = $"{RunPath}\\..\\MPFiles\\Temp"; string outPath = $"{RunPath}\\..\\MPFiles"; string companyName = "广州摩赛网络技术有限公司"; string copyRight = "Copyright (c) 广州摩赛网络技术有限公司. All rights reserved."; string keyName = "esight.snk"; #region read eSight.View.Library var mpStore = new ManagementPackFileStore(); mpStore.AddDirectory(outPath); var reader = ManagementPackBundleFactory.CreateBundleReader(); var bundle = reader.Read($"{outPath}\\eSight.View.Library.mpb", mpStore); var eSightViewMp = bundle.ManagementPacks.FirstOrDefault(); if (eSightViewMp == null) { throw new Exception($"can not find mp : eSight.View.Library.mpb"); } #endregion var mMpStore = new ManagementPackFileStore(); mMpStore.AddDirectory(apmMpPath); mMpStore.AddDirectory(outPath); var mMp = new ManagementPack(ESightConfigLibraryName, ESightConfigLibraryName, eSightViewMp.Version, mMpStore); #region AddReferences var mLibraryMp = new ManagementPack($"{apmMpPath}\\System.Library.mp", mMpStore); var mWindowsLibraryMp = new ManagementPack($"{apmMpPath}\\Microsoft.SystemCenter.Library.mp", mMpStore); mMp.References.Add("System", new ManagementPackReference(mLibraryMp)); mMp.References.Add("SC", new ManagementPackReference(mWindowsLibraryMp)); mMp.References.Add("EVL", new ManagementPackReference(eSightViewMp)); #endregion #region AddView var view = new ManagementPackView(mMp, "ESight.Config.ESightConfigView", ManagementPackAccessibility.Public) { Target = mLibraryMp.GetClass("System.WebSite"), TypeID = mWindowsLibraryMp.GetViewType("Microsoft.SystemCenter.UrlViewType"), Description = "eSight Config View", DisplayName = "eSight Config View", Category = "Operations", Configuration = $"<Criteria><Url>https://localhost:{port}/StaticWeb/eSight.html</Url></Criteria><Presentation></Presentation><Target></Target>" }; var folderItem = new ManagementPackFolderItem("ESight.Config.ESightConfigView.FolderItem", view, eSightViewMp.GetFolder("ESight.Folder")); folderItem.Status = ManagementPackElementStatus.PendingAdd; #endregion mMp.AcceptChanges(); #region seal var mpWriterSettings = new ManagementPackAssemblyWriterSettings(companyName, Path.Combine(keyPath, keyName), false) { OutputDirectory = outPath, Copyright = copyRight }; ManagementPackAssemblyWriter mpWriter = new ManagementPackAssemblyWriter(mpWriterSettings); mpWriter.WriteManagementPack(mMp); #endregion // Remove Temp files if (Directory.Exists(keyPath)) { Directory.Delete(keyPath, true); } var tempFile = Path.Combine(RunPath, "..\\", "MPResources.resources"); if (File.Exists(tempFile)) { File.Delete(tempFile); } } catch (Exception ex) { OnLog($"create {ESightConfigLibraryName} faild", ex); throw; } }
protected override void ProcessRecord() { foreach (ManagementPackSecureReference secureReference in _secureReferences) { //First get the MP that the Secure Reference that was passed in is stored in so that we can create some SecureReferenceOverrides in it. ManagementPack mpSecureReferenceMP = secureReference.GetManagementPack(); //Before we create a new SecureReferenceOverride we need to check to see if one already exists. bool boolSecureRefOverrideAlreadyExists = false; //Loop through each Override in the MP... ManagementPackElementCollection <ManagementPackOverride> listOverrides = mpSecureReferenceMP.GetOverrides(); foreach (ManagementPackOverride mpOverride in listOverrides) { //...if it is a ManagementPackSecureReferenceOverride... if (mpOverride is ManagementPackSecureReferenceOverride) { //...then cast it to a ManagementPackSecureReferenceOverride... ManagementPackSecureReferenceOverride mpSecRefOverride = mpOverride as ManagementPackSecureReferenceOverride; //...and then compare it to the SecureReference that was passed in... if (mpSecRefOverride.SecureReference.Id == secureReference.Id) { //...if it is the same one then get a list of all the SecureData objects so we can compare with those... IList <SecureData> secureDataList = _mg.Security.GetSecureData(); foreach (SecureData secureData in secureDataList) { //...by comparing the SecureStorageID of each of the existing and the .Value of the SecureData we just created... if (String.Compare (BitConverter.ToString(secureData.SecureStorageId, 0, secureData.SecureStorageId.Length).Replace("-", ""), mpSecRefOverride.Value, StringComparison.Ordinal ) == 0 ) { //...and if you find a match... WindowsCredentialSecureData windowsCred = secureData as WindowsCredentialSecureData; if (windowsCred != null) { //...then set the bool to true so we know that there is already a SecureReferenceOverride with this same exact SecureData // so we dont need to create a new SecureReferenceOverride in this case. boolSecureRefOverrideAlreadyExists = true; } } } } } } //Do we need to create a new SecureReferenceOverride? if (!boolSecureRefOverrideAlreadyExists) { //Yes, we need to create a new SecureReferenceOverride... //First create the SecureReferenceOverride object by setting its ID ManagementPackSecureReferenceOverride secureOverride = new ManagementPackSecureReferenceOverride(mpSecureReferenceMP, String.Format("SecureReferenceOverride.{0}", Guid.NewGuid().ToString("N"))); //Then tell it that it's scope is for all objects by setting the class context to System.Entity secureOverride.Context = _mg.EntityTypes.GetClass(SystemClass.Entity); //Set the SecureReference equal to the SecureReference that was passed in. secureOverride.SecureReference = secureReference; //Give it a display name - doesnt need to be anything fancy since it doesnt show anywhere in the UI. secureOverride.DisplayName = "SecureReferenceOverride_" + Guid.NewGuid().ToString(); //Convert to a byte array secureOverride.Value = BitConverter.ToString(_credentialSecureData.SecureStorageId, 0, _credentialSecureData.SecureStorageId.Length).Replace("-", ""); //Now allow this SecureData to be downloaded to all the management servers ApprovedHealthServicesForDistribution <EnterpriseManagementObject> approved = new ApprovedHealthServicesForDistribution <EnterpriseManagementObject>(); approved.Result = ApprovedHealthServicesResults.All; //Tell SCSM that we are going to update (or submit new) this SecureReferenceOverride secureReference.Status = ManagementPackElementStatus.PendingUpdate; //Post it to the database. This will show up on the SecureReferenceOverride table in the database and in the <Overrides> section of the MP XML string secureReferenceInfo = secureReference.Name; if (secureReference.DisplayName != null) { secureReferenceInfo = secureReference.DisplayName; } if (ShouldProcess(secureReferenceInfo)) { _mg.Security.SetApprovedHealthServicesForDistribution <EnterpriseManagementObject>(_credentialSecureData, approved); mpSecureReferenceMP.AcceptChanges(); } } } }
//This Saves the values that have been set throughout the Wizard Pages back into the management pack so the //Advanced Action Log Notifier can read them via ((Get-SCSMObject -Class (Get-SCSMClass -Name "AdhocAdam.Advanced.Action.Log.Notify.AdminSettings$"))) public override void AcceptChanges(WizardMode wizardMode) { //Get the server name to connect to and then connect String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString(); EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName); //Get the Advanced Action Notifier class by GUID ManagementPackClass adhocAdamAALNClass = emg.EntityTypes.GetClass(new Guid("49a053e7-6080-e211-fd79-ca3607eecce7")); //Get the SMLets Exchange Connector Settings object using the object GUID EnterpriseManagementObject emoAdminSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default); //Workflow Status //Retrieve the unsealed workflow management pack that contains the workflows, to control whether or not the workflows are enabled/disabled //https://marcelzehner.ch/2013/07/04/a-look-at-scsm-workflows-and-notifications-and-how-to-manage-them-by-using-scripts/ ManagementPack adhocAdamAALWFClass = emg.ManagementPacks.GetManagementPack(new Guid("4db18489-38fa-895a-7149-902b675dc752")); ManagementPackRule assignedNotificationWF = adhocAdamAALWFClass.GetRule("AdhocAdam.Advanced.Action.Log.Notify.TroubleTicketAnalystCommentNotification"); ManagementPackRule affectedNotificationWF = adhocAdamAALWFClass.GetRule("AdhocAdam.Advanced.Action.Log.Notify.TroubleTicketUserCommentNotification"); ManagementPackRule workItemCommentNotificationWF = adhocAdamAALWFClass.GetRule("AdhocAdam.Advanced.Action.Log.Notify.WorkItemUserCommentNotification"); assignedNotificationWF.Status = ManagementPackElementStatus.PendingUpdate; affectedNotificationWF.Status = ManagementPackElementStatus.PendingUpdate; workItemCommentNotificationWF.Status = ManagementPackElementStatus.PendingUpdate; //Notify Assigned To if (this.IsNotifyAssignedUserEnabled == true) { assignedNotificationWF.Enabled = ManagementPackMonitoringLevel.@true; } else { assignedNotificationWF.Enabled = ManagementPackMonitoringLevel.@false; } //Notify Affected User if (this.IsNotifyAffecteddUserEnabled == true) { affectedNotificationWF.Enabled = ManagementPackMonitoringLevel.@true; } else { affectedNotificationWF.Enabled = ManagementPackMonitoringLevel.@false; } //Service Request Comments if (this.IsNotifyWorkItemCommentsEnabled == true) { workItemCommentNotificationWF.Enabled = ManagementPackMonitoringLevel.@true; } else { workItemCommentNotificationWF.Enabled = ManagementPackMonitoringLevel.@false; } //save the changes back to the unsealed mp adhocAdamAALWFClass.AcceptChanges(); //Azure Settings emoAdminSetting[adhocAdamAALNClass, "EnableAzureTranslate"].Value = this.IsAzureTranslateEnabled; emoAdminSetting[adhocAdamAALNClass, "ACSAPIKey"].Value = this.AzureCognitiveServicesTranslateAPIKey; //Templates try { emoAdminSetting[adhocAdamAALNClass, "TroubleTicketAnalystCommentTemplate"].Value = this.TroubleTicketAnalystCommentTemplate.Id; } catch { } try { emoAdminSetting[adhocAdamAALNClass, "TroubleTicketUserCommentTemplate"].Value = this.TroubleTicketUserCommentTemplate.Id; } catch { } try { emoAdminSetting[adhocAdamAALNClass, "WorkItemCommentTemplate"].Value = this.WorkItemCommentLogTemplate.Id; } catch { } //Update the MP emoAdminSetting.Commit(); this.WizardResult = WizardResult.Success; }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { if (parameters.Contains("Create")) { WizardStory wizard = new WizardStory(); //set the icon and title bar ResourceManager rm = new ResourceManager("SCSM.AzureAutomation.WPF.Connector.Resources", typeof(Resources).Assembly); Bitmap bitmap = (Bitmap)rm.GetObject("AzureAutomation2x24"); IntPtr ptr = bitmap.GetHbitmap(); BitmapSource bitmapsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); wizard.StoryImage = bitmapsource; wizard.WizardWindowTitle = "Create Azure Automation Connector"; WizardData data = new AzureAutomationWizardData(); wizard.WizardData = data; //add th pages wizard.AddLast(new WizardStep("Welcome", typeof(AzureAutomationWelcomePage), wizard.WizardData)); wizard.AddLast(new WizardStep("Configuration", typeof(AzureAutomationConfigurationPage), wizard.WizardData)); wizard.AddLast(new WizardStep("Summary", typeof(AzureAutomationSummaryPage), wizard.WizardData)); wizard.AddLast(new WizardStep("Results", typeof(AzureAutomationResultPage), wizard.WizardData)); //Create a wizard window and show it WizardWindow wizardwindow = new WizardWindow(wizard); // this is needed so that WinForms will pass messages on to the hosted WPF control System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(wizardwindow); wizardwindow.ShowDialog(); //Update the view when done with the wizard so that the new connector shows if (data.WizardResult == WizardResult.Success) { RequestViewRefresh(); } } else if (parameters.Contains("Edit")) { //Get the server name to connect to and connect to the server String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString(); EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName); //Get the object using the selected node ID String strID = String.Empty; foreach (NavigationModelNodeBase node in nodes) { strID = node["$Id$"].ToString(); } EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strID), ObjectQueryOptions.Default); //Create a new "wizard" (also used for property dialogs as in this case), set the title bar, create the data, and add the pages WizardStory wizard = new WizardStory(); wizard.WizardWindowTitle = "Edit Azure Automation Connector"; WizardData data = new AzureAutomationWizardData(emoAAConnector); wizard.WizardData = data; wizard.AddLast(new WizardStep("Configuration", typeof(AzureAutomationConfigurationPage), wizard.WizardData)); //Show the property page PropertySheetDialog wizardWindow = new PropertySheetDialog(wizard); //Update the view when done so the new values are shown bool?dialogResult = wizardWindow.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) { RequestViewRefresh(); } } else if (parameters.Contains("Delete") || parameters.Contains("Disable") || parameters.Contains("Enable")) { //Get the server name to connect to and create a connection String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString(); EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName); //Get the object using the selected node ID String strID = String.Empty; foreach (NavigationModelNodeBase node in nodes) { strID = node["$Id$"].ToString(); } EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strID), ObjectQueryOptions.Default); if (parameters.Contains("Delete")) { //Remove the object from the database IncrementalDiscoveryData idd = new IncrementalDiscoveryData(); idd.Remove(emoAAConnector); idd.Commit(emg); } //Get the rule using the connector ID ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0")); ManagementPack mpAAConnectorWorkflows = emg.GetManagementPack("SCSM.AzureAutomation.Workflows", null, new Version("1.0.0.0")); ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector"); String strConnectorID = emoAAConnector[classAAConnector, "Id"].ToString(); ManagementPackRule ruleConnector = mpAAConnectorWorkflows.GetRule(strConnectorID); //Update the Enabled property or delete as appropriate if (parameters.Contains("Delete")) { ruleConnector.Status = ManagementPackElementStatus.PendingDelete; } else if (parameters.Contains("Disable")) { emoAAConnector[classAAConnector, "Enabled"].Value = false; ruleConnector.Enabled = ManagementPackMonitoringLevel.@false; ruleConnector.Status = ManagementPackElementStatus.PendingUpdate; } else if (parameters.Contains("Enable")) { emoAAConnector[classAAConnector, "Enabled"].Value = true; ruleConnector.Enabled = ManagementPackMonitoringLevel.@true; ruleConnector.Status = ManagementPackElementStatus.PendingUpdate; } //Commit the changes to the connector object and rule emoAAConnector.Commit(); mpAAConnectorWorkflows.AcceptChanges(); //Update the view when done so the item is either removed or the updated Enabled value shows RequestViewRefresh(); } }
private void CreateConnectorInstance() { try { //Get the server name to connect to String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString(); //Conneect to the server EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName); //Get the System MP so we can get the system key token and version so we can get other MPs using that info ManagementPack mpSystem = emg.ManagementPacks.GetManagementPack(SystemManagementPack.System); string strSystemKeyToken = mpSystem.KeyToken; ManagementPack mpSubscriptions = emg.GetManagementPack("Microsoft.SystemCenter.Subscriptions", strSystemKeyToken, new Version("1.0.0.0")); //Also get the System Center and Connector MPs - we'll need things from those MPs later ManagementPack mpSystemCenter = emg.ManagementPacks.GetManagementPack(SystemManagementPack.SystemCenter); ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0")); ManagementPack mpAAConnectorWorkflows = emg.GetManagementPack("SCSM.AzureAutomation.Workflows", null, new Version("1.0.0.0")); //Get the AzureAutomationConnector class in the Connectors MP ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector"); //Create a new CreatableEnterpriseManagementObject. We'll set the properties on this and then post it to the database. EnterpriseManagementObject cemoAAConnector = new CreatableEnterpriseManagementObject(emg, classAAConnector); //Sytem.Entity properties cemoAAConnector[classAAConnector, "DisplayName"].Value = this.DisplayName; //Required //Microsoft.SystemCenter.Connector properties //This is just a tricky way to create a unique ID which conforms to the syntax rules for MP element ID attribute values. String strConnectorID = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", "AAConnector", Guid.NewGuid().ToString("N")); cemoAAConnector[classAAConnector, "Id"].Value = strConnectorID; //Required; Key //System.LinkingFramework.DataSource properties cemoAAConnector[classAAConnector, "DataProviderDisplayName"].Value = "Azure Automation Connector"; //Optional, shown in Connectors view cemoAAConnector[classAAConnector, "Enabled"].Value = true; //Optional, shown in Connectors view cemoAAConnector[classAAConnector, "Name"].Value = this.DisplayName; //SCSM.AzureAutomation.Connector properties cemoAAConnector[classAAConnector, "AutomationAccount"].Value = this.AutomationAccount; cemoAAConnector[classAAConnector, "SubscriptionID"].Value = this.SubscriptionID; cemoAAConnector[classAAConnector, "ResourceGroup"].Value = this.ResourceGroup; cemoAAConnector[classAAConnector, "RunAsAccountName"].Value = this.RunAsAccountName; cemoAAConnector[classAAConnector, "RunAsAccountPassword"].Value = this.RunAsAccountPassword; cemoAAConnector[classAAConnector, "RefreshIntervalHours"].Value = this.RefreshIntervalHours; //Create Connector instance cemoAAConnector.Commit(); //Now we need to create the CSV Connector rule... //Get the Scheduler data source module type from the System MP and the Windows Workflow Task Write Action Module Type from the Subscription MP ManagementPackDataSourceModuleType dsmtScheduler = (ManagementPackDataSourceModuleType)mpSystem.GetModuleType("System.Scheduler"); ManagementPackWriteActionModuleType wamtWindowsWorkflowTaskWriteAction = (ManagementPackWriteActionModuleType)mpSubscriptions.GetModuleType("Microsoft.EnterpriseManagement.SystemCenter.Subscription.WindowsWorkflowTaskWriteAction"); //Create a new rule for the CSV Connector in the Connectors MP. Set the name of this rule to be the same as the connector instance ID so there is a pairing between them ManagementPackRule ruleAAConnector = new ManagementPackRule(mpAAConnectorWorkflows, strConnectorID); //Set the target and other properties of the rule ruleAAConnector.Target = mpSystemCenter.GetClass("Microsoft.SystemCenter.SubscriptionWorkflowTarget"); //Create a new Data Source Module in the new CSV Connector rule ManagementPackDataSourceModule dsmSchedule = new ManagementPackDataSourceModule(ruleAAConnector, "DS1"); //Set the configuration of the data source rule. Pass in the frequency (number of minutes) dsmSchedule.Configuration = "<Scheduler>" + "<SimpleReccuringSchedule>" + "<Interval Unit=\"Hours\">" + strRefreshIntervalHours + "</Interval>" + "</SimpleReccuringSchedule>" + "<ExcludeDates />" + "</Scheduler>"; //Set the Schedule Data Source Module Type to the Simple Schedule Module Type from the System MP dsmSchedule.TypeID = dsmtScheduler; //Add the Scheduler Data Source to the Rule ruleAAConnector.DataSourceCollection.Add(dsmSchedule); //Now repeat essentially the same process for the Write Action module... //Create a new Write Action Module in the CSV Connector rule ManagementPackWriteActionModule wamAAConnector = new ManagementPackWriteActionModule(ruleAAConnector, "WA1"); //Set the Configuration XML wamAAConnector.Configuration = "<Subscription>" + "<WindowsWorkflowConfiguration>" + //Specify the Windows Workflow Foundation workflow Assembly name here "<AssemblyName>SCSM.AzureAutomation.Workflows.AT</AssemblyName>" + //Specify the type name of the workflow to call in the assembly here: "<WorkflowTypeName>WorkflowAuthoring.RefreshConnector</WorkflowTypeName>" + "<WorkflowParameters>" + //Pass in the parameters here. In this case the two parameters are the data file path and the mapping file path "<WorkflowParameter Name=\"RefreshConnectorScript_ConnectorId\" Type=\"string\">" + strConnectorID + "</WorkflowParameter>" + "</WorkflowParameters>" + "<RetryExceptions />" + "<RetryDelaySeconds>60</RetryDelaySeconds>" + "<MaximumRunningTimeSeconds>300</MaximumRunningTimeSeconds>" + "</WindowsWorkflowConfiguration>" + "</Subscription>"; //Set the module type of the module to be the Windows Workflow Task Write Action Module Type from the Subscriptions MP. wamAAConnector.TypeID = wamtWindowsWorkflowTaskWriteAction; //Add the Write Action Module to the rule ruleAAConnector.WriteActionCollection.Add(wamAAConnector); //Mark the rule as pending update ruleAAConnector.Status = ManagementPackElementStatus.PendingAdd;; //Accept the rule changes which updates the database mpAAConnectorWorkflows.AcceptChanges(); } catch (Exception e) { MessageBox.Show(e.Message + e.InnerException.Message); } }
public static void CreateNotificationRule(string strDisplayName, string strName, string strCriteria, EnterpriseManagementObject emoUser, ManagementPackClass mpc, ManagementPackObjectTemplate mpt, ref ManagementPack mp, EnterpriseManagementGroup emg) { ManagementPack mpSystemCenterLibrary = Helper.GetManagementPackByName("Microsoft.SystemCenter.Library", emg); ManagementPack mpSubscriptions = Helper.GetManagementPackByName("Microsoft.SystemCenter.Subscriptions", emg); string strSubscriptionsMPAlias = MakeMPElementSafeName(mpSubscriptions.Name); AddManagementPackReference(strSubscriptionsMPAlias, mpSubscriptions.Name, ref mp, emg); string strSystemCenterLibraryMPAlias = MakeMPElementSafeName(mpSystemCenterLibrary.Name); AddManagementPackReference(strSystemCenterLibraryMPAlias, mpSystemCenterLibrary.Name, ref mp, emg); ManagementPackClass mpcSubscriptionWorkflowTarget = GetClassByName("Microsoft.SystemCenter.SubscriptionWorkflowTarget", emg); ManagementPackDataSourceModuleType mpdsmtSubscription = (ManagementPackDataSourceModuleType)mpSubscriptions.GetModuleType("Microsoft.SystemCenter.CmdbInstanceSubscription.DataSourceModule"); ManagementPackRule mpr = new ManagementPackRule(mp, MakeMPElementSafeName(String.Format("NotificationSubscription.{0}", Guid.NewGuid()))); mpr.Enabled = ManagementPackMonitoringLevel.@true; mpr.ConfirmDelivery = true; mpr.Remotable = true; mpr.Priority = ManagementPackWorkflowPriority.Normal; mpr.Category = ManagementPackCategoryType.System; mpr.DiscardLevel = 100; mpr.Target = mp.ProcessElementReference <ManagementPackClass>(String.Format("$MPElement[Name=\"{0}!{1}\"]$", strSystemCenterLibraryMPAlias, mpcSubscriptionWorkflowTarget.Name)); ManagementPackDataSourceModule mpdsmSubscription = new ManagementPackDataSourceModule(mpr, "DS"); mpdsmSubscription.TypeID = mp.ProcessElementReference <ManagementPackDataSourceModuleType>(String.Format("$MPElement[Name=\"{0}!{1}\"]$", strSubscriptionsMPAlias, mpdsmtSubscription.Name)); StringBuilder sbDataSourceConfiguration = new StringBuilder(); sbDataSourceConfiguration.Append("<Subscription>"); sbDataSourceConfiguration.Append(String.Format("<InstanceSubscription Type=\"{0}\">", mpc.Id.ToString())); sbDataSourceConfiguration.Append(strCriteria); sbDataSourceConfiguration.Append("</InstanceSubscription>"); sbDataSourceConfiguration.Append("<PollingIntervalInSeconds>60</PollingIntervalInSeconds>"); sbDataSourceConfiguration.Append("<BatchSize>100</BatchSize>"); sbDataSourceConfiguration.Append("</Subscription>"); mpdsmSubscription.Configuration = sbDataSourceConfiguration.ToString(); ManagementPackWriteActionModuleType mpwamtSubscription = (ManagementPackWriteActionModuleType)mpSubscriptions.GetModuleType("Microsoft.EnterpriseManagement.SystemCenter.Subscription.WindowsWorkflowTaskWriteAction"); ManagementPackWriteActionModule mpwamSubscription = new ManagementPackWriteActionModule(mpr, "WA"); mpwamSubscription.TypeID = mp.ProcessElementReference <ManagementPackWriteActionModuleType>(String.Format("$MPElement[Name=\"{0}!{1}\"]$", strSubscriptionsMPAlias, mpwamtSubscription.Name)); StringBuilder sbWriteActionConfiguration = new StringBuilder(); sbWriteActionConfiguration.Append("<Subscription>"); sbWriteActionConfiguration.Append("<VisibleWorkflowStatusUi>true</VisibleWorkflowStatusUi>"); sbWriteActionConfiguration.Append("<EnableBatchProcessing>true</EnableBatchProcessing>"); sbWriteActionConfiguration.Append("<WindowsWorkflowConfiguration>"); sbWriteActionConfiguration.Append("<AssemblyName>Microsoft.EnterpriseManagement.Notifications.Workflows</AssemblyName>"); sbWriteActionConfiguration.Append("<WorkflowTypeName>Microsoft.EnterpriseManagement.Notifications.Workflows.SendNotificationsActivity</WorkflowTypeName>"); sbWriteActionConfiguration.Append("<WorkflowParameters>"); sbWriteActionConfiguration.Append("<WorkflowParameter Name=\"SubscriptionId\" Type=\"guid\">$MPElement$</WorkflowParameter>"); sbWriteActionConfiguration.Append("<WorkflowArrayParameter Name=\"DataItems\" Type=\"string\">"); sbWriteActionConfiguration.Append("<Item>$Data/.$</Item>"); sbWriteActionConfiguration.Append("</WorkflowArrayParameter>"); sbWriteActionConfiguration.Append("<WorkflowArrayParameter Name=\"InstanceIds\" Type=\"string\">"); sbWriteActionConfiguration.Append("<Item>$Data/BaseManagedEntityId$</Item>"); sbWriteActionConfiguration.Append("</WorkflowArrayParameter>"); sbWriteActionConfiguration.Append("<WorkflowArrayParameter Name=\"TemplateIds\" Type=\"string\">"); sbWriteActionConfiguration.Append(String.Format("<Item>{0}</Item>", mpt.Id.ToString())); sbWriteActionConfiguration.Append("</WorkflowArrayParameter>"); sbWriteActionConfiguration.Append("<WorkflowArrayParameter Name=\"PrimaryUserList\" Type=\"string\">"); sbWriteActionConfiguration.Append(String.Format("<Item>{0}</Item>", emoUser.Id.ToString())); sbWriteActionConfiguration.Append("</WorkflowArrayParameter>"); sbWriteActionConfiguration.Append("</WorkflowParameters>"); sbWriteActionConfiguration.Append("<RetryExceptions/>"); sbWriteActionConfiguration.Append("<RetryDelaySeconds>60</RetryDelaySeconds>"); sbWriteActionConfiguration.Append("<MaximumRunningTimeSeconds>7200</MaximumRunningTimeSeconds>"); sbWriteActionConfiguration.Append("</WindowsWorkflowConfiguration>"); sbWriteActionConfiguration.Append("</Subscription>"); mpwamSubscription.Configuration = sbWriteActionConfiguration.ToString(); mpr.DataSourceCollection.Add(mpdsmSubscription); mpr.WriteActionCollection.Add(mpwamSubscription); mpr.Status = ManagementPackElementStatus.PendingAdd; mp.AcceptChanges(); }
public static void CreateQueue(string strDisplayName, string strName, string strCriteria, ManagementPackClass mpc, ref ManagementPack mp, EnterpriseManagementGroup emg) { ManagementPack mpClass = mpc.GetManagementPack(); string strMPAlias = MakeMPElementSafeName(mpClass.Name); AddManagementPackReference(strMPAlias, mpClass.Name, ref mp, emg); ManagementPackClass classWorkItemGroup = GetClassByName("System.WorkItemGroup", emg); ManagementPackClass mpcQueue = new ManagementPackClass(mp, strName, ManagementPackAccessibility.Public); mpcQueue.Abstract = false; mpcQueue.Base = classWorkItemGroup; mpcQueue.DisplayName = strDisplayName; mpcQueue.Hosted = false; mpcQueue.Extension = false; mpcQueue.Singleton = true; mpcQueue.Status = ManagementPackElementStatus.PendingAdd; ManagementPackRelationship mprWorkItemGroupContainsWorkItem = GetRelationshipByName("System.WorkItemGroupContainsWorkItems", emg); ManagementPackRelationshipEndpoint mpreSource = new ManagementPackRelationshipEndpoint(mpcQueue, "ContainedByGroup"); ManagementPackRelationshipEndpoint mpreTarget = new ManagementPackRelationshipEndpoint(mpcQueue, "GroupContains"); mpreSource.Type = mpcQueue; mpreTarget.Type = mp.ProcessElementReference <ManagementPackClass>(String.Format("$MPElement[Name=\"{0}!{1}\"]$", strMPAlias, mpc.Name)); ManagementPackRelationship mprQueueWorkItem = new ManagementPackRelationship(mp, String.Format("{0}.Relationship", strName), ManagementPackAccessibility.Public); mprQueueWorkItem.DisplayName = String.Format("{0} Contains {1}", strDisplayName, mpc.DisplayName); mprQueueWorkItem.Abstract = false; mprQueueWorkItem.Base = mprWorkItemGroupContainsWorkItem; mprQueueWorkItem.Source = mpreSource; mprQueueWorkItem.Target = mpreTarget; mprQueueWorkItem.Status = ManagementPackElementStatus.PendingAdd; ManagementPackDiscoveryRelationship mpdrQueueWorkItem = new ManagementPackDiscoveryRelationship(); mpdrQueueWorkItem.TypeID = mprQueueWorkItem; ManagementPack mpSystemCenter = GetManagementPackByName("Microsoft.SystemCenter.Library", emg); string strSystemCenterLibraryMPAlias = MakeMPElementSafeName(mpSystemCenter.Name); AddManagementPackReference(strSystemCenterLibraryMPAlias, mpSystemCenter.Name, ref mp, emg); ManagementPackModuleType mpmtGroupPopulator = emg.Monitoring.GetModuleType("Microsoft.SystemCenter.GroupPopulator", mpSystemCenter); ManagementPackDiscovery mpdQueueWorkItem = new ManagementPackDiscovery(mp, MakeMPElementSafeName(String.Format("WorkITemGroup.{0}.Discovery.{1}", mpcQueue.Name, Guid.NewGuid().ToString()))); ManagementPackDataSourceModule mpdsmPopulator = new ManagementPackDataSourceModule(mpdQueueWorkItem, MakeMPElementSafeName(Guid.NewGuid().ToString())); ManagementPackElementReference <ManagementPackDataSourceModuleType> mperGroupPopulator = mp.ProcessElementReference <ManagementPackDataSourceModuleType>(String.Format("$MPElement[Name=\"{0}!{1}\"]$", strSystemCenterLibraryMPAlias, mpmtGroupPopulator.Name)); mpdsmPopulator.TypeID = mperGroupPopulator; StringBuilder sb = new StringBuilder(); sb.Append("<RuleId>$MPElement$</RuleId>\r\n"); sb.Append(String.Format("<GroupInstanceId>$MPElement[Name=\"{0}\"]$</GroupInstanceId>\r\n", strName)); sb.Append("<MembershipRules>\r\n"); sb.Append("<MembershipRule>\r\n"); sb.Append(String.Format("<MonitoringClass>$MPElement[Name=\"{0}!{1}\"]$</MonitoringClass>\r\n", strMPAlias, mpc.Name)); sb.Append(String.Format("<RelationshipClass>$MPElement[Name=\"{0}\"]$</RelationshipClass>\r\n", mprQueueWorkItem.Name)); sb.Append(strCriteria); sb.Append("</MembershipRule>\r\n"); sb.Append("</MembershipRules>\r\n"); mpdsmPopulator.Configuration = sb.ToString(); mpdQueueWorkItem.Enabled = ManagementPackMonitoringLevel.@true; mpdQueueWorkItem.Target = mpcQueue; mpdQueueWorkItem.ConfirmDelivery = false; mpdQueueWorkItem.Remotable = true; mpdQueueWorkItem.Priority = ManagementPackWorkflowPriority.Normal; mpdQueueWorkItem.Category = ManagementPackCategoryType.Discovery; mpdQueueWorkItem.DiscoveryRelationshipCollection.Add(mpdrQueueWorkItem); mpdQueueWorkItem.DataSource = mpdsmPopulator; mp.AcceptChanges(); }
/* public void DisableWorkflows() { var mp = AssureConfigManagementPack(); DisableWorkflow(mp, Parameters.WORKFLOW_NAME_MONITORJOBS); DisableWorkflow(mp, Parameters.WORKFLOW_NAME_STARTRUNBOOK); mp.AcceptChanges(); } public void DisableWorkflow(ManagementPack mp, string ruleName) { var overrideName = $"{ruleName}.Override"; var ruleOverride = (ManagementPackRulePropertyOverride)_emg.Overrides.GetOverrides(new ManagementPackOverrideCriteria($"Name = '{overrideName}'")).FirstOrDefault(); if (ruleOverride != null) ruleOverride.Status = ManagementPackElementStatus.PendingDelete; } public void EnableWorkflows() { var mp = AssureConfigManagementPack(); EnableWorkflow(mp, Parameters.WORKFLOW_NAME_MONITORJOBS); EnableWorkflow(mp, Parameters.WORKFLOW_NAME_STARTRUNBOOK); mp.AcceptChanges(); } public void EnableWorkflow(ManagementPack mp, string ruleName) { var rule = _emg.Monitoring.GetRules(new ManagementPackRuleCriteria($"Name = '{ruleName}'")).FirstOrDefault(); var overrideName = $"{ruleName}.Override"; var ruleOverride = (ManagementPackRulePropertyOverride)_emg.Overrides.GetOverrides(new ManagementPackOverrideCriteria($"Name = '{overrideName}'")).FirstOrDefault(); if (ruleOverride == null) ruleOverride = new ManagementPackRulePropertyOverride(mp, overrideName); ruleOverride.Rule = rule; ruleOverride.Property = ManagementPackWorkflowProperty.Enabled; ruleOverride.Value = "true"; ruleOverride.Context = EntityClass; ruleOverride.Enforced = true; ruleOverride.DisplayName = $"Enable {ruleName}"; } */ public ManagementPack AssureConfigManagementPack() { var mp = _emg.ManagementPacks.GetManagementPacks(new ManagementPackCriteria($"Name = '{Parameters.CONFIGMP_NAME}'")).FirstOrDefault(); if (mp == null) { mp = new ManagementPack(Parameters.CONFIGMP_NAME, Parameters.CONFIGMP_NAME, Parameters.CONFIGMP_VERSION, _emg); mp.DisplayName = Parameters.CONFIGMP_DISPLAYNAME; mp.AcceptChanges(); _emg.ManagementPacks.ImportManagementPack(mp); } return mp; }