public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { base.ExecuteCommand(nodes, task, parameters); string nodesStr = "Nodes:"; foreach (NavigationModelNodeBase node in nodes) { nodesStr += $"{node.DisplayName}/r/n"; } string parametersStr = "Parameters:"; foreach (var p in parameters) { parametersStr += p; } var str = $@" {nodesStr} Task: {task.DisplayName} {parametersStr} "; MessageBox.Show(str); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { try { EnterpriseManagementGroup emg = ConsoleContext.GetConsoleEMG(); // (Cireson.ProjectAutomation.Library) (Microsoft.SystemCenter.Connector.ProjectServer.Settings) (5a49b80c-4c34-d189-ca94-a591580f1995) ManagementPackClass mpcSettings = emg.EntityTypes.GetClass(new Guid("5a49b80c-4c34-d189-ca94-a591580f1995")); //get the settings class. EnterpriseManagementObject emoSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(mpcSettings.Id, ObjectQueryOptions.Default); //get the settings class instance. //somewhere here we will have a container for our class data to feed the consoleWizard obj. AdminSettingsData admData = new AdminSettingsData(emoSettings); WizardStory consoleWizard = new WizardStory(); consoleWizard.WizardData = admData; consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strGroomingSettings"), typeof(AdminSettingsGroomingForm), admData)); consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strStatusSettings"), typeof(AdminSettingsStatusForm), admData)); consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strProjectTasksSettings"), typeof(AdminSettingsProjectTasksForm), admData)); consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strProjectLicensingSettings"), typeof(AdminSettingsLicensingForm), admData)); PropertySheetDialog propertyDialog = new PropertySheetDialog(consoleWizard); propertyDialog.Width = 800; propertyDialog.Height = 700; propertyDialog.WindowStartupLocation = WindowStartupLocation.CenterOwner; propertyDialog.Title = ServiceManagerLocalization.GetStringFromManagementPack("strSettings"); propertyDialog.ShowInTaskbar = true; propertyDialog.Icon = BitmapFrame.Create(System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Microsoft.EnterpriseManagement.ServiceManager.ProjectServer.ConsoleTasks;component/Icons/Image.Cireson.16x16.ico", UriKind.RelativeOrAbsolute)).Stream); propertyDialog.ShowDialog(); } catch (Exception ex) { ConsoleContextHelper.Instance.ShowErrorDialog(ex, string.Empty, ConsoleJobExceptionSeverity.Error); } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { /* * This GUID is generated automatically when you import the Management Pack with the singleton admin setting class in it. * You can get this GUID by running a query like: * Select BaseManagedEntityID, FullName from BaseManagedEntity where FullName like '%<enter your class ID here>%' * where the GUID you want is returned in the BaseManagedEntityID column in the result set */ String strSingletonBaseManagedObjectID = "4AD8DC00-2333-93D6-5EB4-D372A42DEA7B"; //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 GUID from above - since this is a singleton object we can get it by GUID EnterpriseManagementObject emoIncidentSLASettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strSingletonBaseManagedObjectID), 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 Incident SLA Settings"; WizardData data = new IncidentSLASettingsWizardData(emoIncidentSLASettings, emg); wizard.WizardData = data; wizard.AddLast(new WizardStep("Configuration", typeof(Settings), wizard.WizardData)); //Show the property page PropertySheetDialog wizardWindow = new PropertySheetDialog(wizard); wizardWindow.ShowDialog(); }
public override async void ExecuteCommand(IList<NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection<string> parameters) { base.ExecuteCommand(nodes, task, parameters); if (ConsoleHandler.Current.Initialize()) { var item = ConsoleHandler.Current.GetFormDataContext(nodes); if ((bool)item["$IsNew$"]) System.Windows.MessageBox.Show("You cannot start runbook from template!"); else { var res = System.Windows.MessageBox.Show("Make sure the changes you've made are commited before starting runbook. Please note that execution of this job will not be tracked. Do you still want to start runbook?", "Warning!", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Warning); if (res == System.Windows.MessageBoxResult.Yes) { try { var activityId = (Guid)item["$Id$"]; var j = ConsoleHandler.Current.CreateStartRunbookJob(activityId); await ConsoleHandler.Current.AAClient.StartJob(j); System.Windows.MessageBox.Show("Runbook started successfully.", "Started", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information); } catch (Exception e) { System.Windows.MessageBox.Show($"Failed to start runbook because: {e.Message}", "Error!", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); } } } } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; IDataItem OMSConnectorUI = Microsoft.EnterpriseManagement.UI.Extensions.Shared.ConsoleContextHelper.Instance.GetProjectionInstance(new Guid("a34fe17a-0ca7-4b85-08c2-2039ac41ca44"), new Guid("df38f99c-ee70-647a-4d2e-fd6e41fe481f")); IDataItem emoProjectionObject = (IDataItem)OMSConnectorUI; Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; IDataItem HWConnectorUI = Microsoft.EnterpriseManagement.UI.Extensions.Shared.ConsoleContextHelper.Instance.GetProjectionInstance(new Guid("5fb27713-acf5-28b8-d7b9-0483a255b0af"), new Guid("42ab3437-c522-c4e1-e29d-0acf1082a8ec")); IDataItem emoProjectionObject = (IDataItem)HWConnectorUI; Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; IDataItem HWConnectorUI = Microsoft.EnterpriseManagement.UI.Extensions.Shared.ConsoleContextHelper.Instance.GetProjectionInstance(new Guid("bbb51076-e86f-ecee-f535-cdaade5bcbad"), new Guid("baec3cda-8f2d-588c-9182-cefd1847e638")); IDataItem emoProjectionObject = (IDataItem)HWConnectorUI; Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; IDataItem HWConnectorUI = Microsoft.EnterpriseManagement.UI.Extensions.Shared.ConsoleContextHelper.Instance.GetProjectionInstance(new Guid("69501c7e-0d07-a401-80f8-4fe8bd7147de"), new Guid("c54fe486-44ab-0dd2-a8c7-2eadc995b274")); IDataItem emoProjectionObject = (IDataItem)HWConnectorUI; Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; IDataItem HWConnectorUI = Microsoft.EnterpriseManagement.UI.Extensions.Shared.ConsoleContextHelper.Instance.GetProjectionInstance(new Guid("21c88509-5a22-365b-bdb3-a2122ea4508a"), new Guid("46e2eadd-42e1-991f-95d1-9afe089c8a98")); IDataItem emoProjectionObject = (IDataItem)HWConnectorUI; Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; IDataItem HWConnectorUI = Microsoft.EnterpriseManagement.UI.Extensions.Shared.ConsoleContextHelper.Instance.GetProjectionInstance(new Guid("2338f5c9-020a-9c82-28bb-e955ad8751a7"), new Guid("74a46790-b217-ea0f-28b7-ecbc658e8f29")); IDataItem emoProjectionObject = (IDataItem)HWConnectorUI; Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; IDataItem HWConnectorUI = Microsoft.EnterpriseManagement.UI.Extensions.Shared.ConsoleContextHelper.Instance.GetProjectionInstance(new Guid("6ec06321-f6c7-6d8c-fa80-cb4df7d63f48"), new Guid("70e05905-0d8a-4113-0109-d1ffd47bdc43")); IDataItem emoProjectionObject = (IDataItem)HWConnectorUI; Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup mg = session.ManagementGroup; EnterpriseManagementObject LicConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("21c88509-5a22-365b-bdb3-a2122ea4508a"), ObjectQueryOptions.Default); LicConnector[null, "SyncNow"].Value = (bool)true; LicConnector.Commit(); MessageBox.Show("License Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup mg = session.ManagementGroup; EnterpriseManagementObject SWConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("2338f5c9-020a-9c82-28bb-e955ad8751a7"), ObjectQueryOptions.Default); SWConnector[null, "SyncNow"].Value = (bool)true; SWConnector.Commit(); MessageBox.Show("Software Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup mg = session.ManagementGroup; EnterpriseManagementObject HWConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("6ec06321-f6c7-6d8c-fa80-cb4df7d63f48"), ObjectQueryOptions.Default); HWConnector[null, "SyncNow"].Value = (bool)true; HWConnector.Commit(); MessageBox.Show("Hardware Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK); }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Getting the emg Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>(); EnterpriseManagementGroup mg = new EnterpriseManagementGroup("localhost"); EnterpriseManagementObject OMSConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("a34fe17a-0ca7-4b85-08c2-2039ac41ca44"), ObjectQueryOptions.Default); OMSConnector[null, "SyncNow"].Value = (bool)true; OMSConnector.Commit(); MessageBox.Show("OMS FUll Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK); }
public override void ExecuteCommand(IList<NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection<string> parameters) { base.ExecuteCommand(nodes, task, parameters); if (ConsoleHandler.Current.Initialize()) { var jobId = ConsoleHandler.Current.GetPropertyFormNavModel<Guid>(nodes, "JobId"); if (jobId == default(Guid)) System.Windows.MessageBox.Show("Runbook was not started yet!", "Error!", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); else ConsoleHandler.Current.NavigateToPortal($"jobs/{jobId}"); } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { foreach (NavigationModelNodeBase node in nodes) { if (parameters.Contains("Incident")) { Incident incident = new Incident(); incident.IDToCopy = node["Id"].ToString(); incident.EMG = incident.EMG = Common.GetManagementGroupConnectionFromRegistry(); string strWorkItemID = incident.Copy(); } } }
private void brd_Add_MouseDown(object sender, MouseButtonEventArgs e) { try { //NavigationModelNodeBase nodeIn = null; NavigationModelNodeBase NBNew; NavigationModelNodeTask nmntNew = NavigationTasksHelper.CreateNewInstanceLink(mpClass); Microsoft.EnterpriseManagement.GenericForm.GenericCommon.MonitorCreatedForm(null, nmntNew, out NBNew); } catch (Exception exc) { Trace.WriteLine(DateTime.Now + " : " + "Error in brd_Add_MouseDown() " + exc.Message); } }
private void brd_Add_MouseDown(object sender, MouseButtonEventArgs e) { try { //MessageBox.Show("Open null form " + mpClass.Name + ". Binding sip. Id=" + guidClass + ". PathString = " + PathString); //NavigationModelNodeBase nodeIn = null; NavigationModelNodeBase NBNew; NavigationModelNodeTask nmntNew = NavigationTasksHelper.CreateNewInstanceLink(mpClass); Microsoft.EnterpriseManagement.GenericForm.GenericCommon.MonitorCreatedForm(null, nmntNew, out NBNew); } catch (Exception exc) { MessageBox.Show(DateTime.Now + " : " + "Error in brd_Add_MouseDown() " + exc.Message); } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { /* * This GUID is generated automatically when you import the Management Pack with the singleton admin setting class in it. * You can get this GUID by running a query like: * Select BaseManagedEntityID, FullName where FullName like ‘%<enter your class ID here>%’ * where the GUID you want is returned in the BaseManagedEntityID column in the result set */ /*In this above example I imported the MP, and then used: * Select BaseManagedEntityID, FullName * From BaseManagedEntity * where FullName like 'AdhocAdam%' * against the ServiceManager DB to figure out the following strSingletonBaseManagedObjectID. Per * https://blogs.technet.microsoft.com/servicemanager/2011/05/26/getting-management-pack-elements-using-the-sdk/ * the id is always unique and never changes as its based on the MP ID, Element Names, and the key token. */ String strSingletonBaseManagedObjectID = "49a053e7-6080-e211-fd79-ca3607eecce7"; //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 GUID from above – since this is a singleton object we can get it by GUID EnterpriseManagementObject emoAdminSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strSingletonBaseManagedObjectID), 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 = "AdhocAdam - Advanced Action Log Notifier"; WizardData data = new AdminSettingWizardData(emoAdminSetting); wizard.WizardData = data; wizard.AddLast(new WizardStep("General", typeof(AdminSettingsForm), wizard.WizardData)); wizard.AddLast(new WizardStep("Azure", typeof(AzureSettingsForm), wizard.WizardData)); wizard.AddLast(new WizardStep("About", typeof(AboutForm), 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(); } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { try { EnterpriseManagementGroup emg = ConsoleContext.GetConsoleEMG(); if (parameters.Contains("Create")) { //do stuff ProjectConnectorHelpers helper = new ProjectConnectorHelpers(); ProjectConnectorData data = helper.CreateProjectConnector(); if (data.WizardResult == WizardResult.Success) { this.RequestViewRefresh(); } } else if (parameters.Contains("Edit")) { //do other stuff ProjectConnectorHelpers helper = new ProjectConnectorHelpers(); WizardResult result = helper.EditProjectConnector(nodes[0]); if (result == WizardResult.Success) { this.RequestViewRefresh(); } } else if (parameters.Contains("Delete")) { //delete stuff ProjectConnectorHelpers helper = new ProjectConnectorHelpers(); if (helper.DeleteProjectConnector(nodes[0])) { this.RequestViewRefresh(); } } } catch (Exception ex) { ConsoleContextHelper.Instance.ShowErrorDialog(ex, string.Empty, ConsoleJobExceptionSeverity.Error); } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //*** IMPORTANT NOTE: The IManagementGroupSession is not a part of the publicly document/supported official SDK and is subject to change in a future release. IManagementGroupSession session = (IManagementGroupSession)FrameworkServices.GetService <IManagementGroupSession>(); EnterpriseManagementGroup emg = session.ManagementGroup; if (parameters.Contains("Edit")) { //There will only ever be one item because we are going to limit this task to single select foreach (NavigationModelNodeBase node in nodes) { //*** IMPORTANT NOTE: The ConsoleContextHelper class is not a part of the publicly document/supported official SDK and is subject to change in a future release. ConsoleContextHelper.Instance.PopoutForm(node); } } else if (parameters.Contains("Delete")) { MessageBoxResult result = MessageBox.Show("Are you sure you want to delete the selected Cost Centers?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result != MessageBoxResult.Yes) { return; } //Create an IncrementalDiscoveryData "bucket" for capturing all the deletes that will be processed at the same time IncrementalDiscoveryData idd = new IncrementalDiscoveryData(); foreach (NavigationModelNodeBase node in nodes) { EnterpriseManagementObject emoCostCenter = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(node["$Id$"].ToString()), ObjectQueryOptions.Default); idd.Remove(emoCostCenter); } idd.Commit(emg); RequestViewRefresh(); } }
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(); } }
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 override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { /* * This GUID is generated automatically when you import the Management Pack with the singleton admin setting class in it. * You can get this GUID by running a query like: * Select BaseManagedEntityID, FullName where FullName like ‘%<enter your class ID here>%’ * where the GUID you want is returned in the BaseManagedEntityID column in the result set */ /*In this above example I imported the MP, and then used: * Select BaseManagedEntityID, FullName * From BaseManagedEntity * where FullName like 'SMLets%' * against the ServiceManager DB to figure out the following strSingletonBaseManagedObjectID. Per * https://blogs.technet.microsoft.com/servicemanager/2011/05/26/getting-management-pack-elements-using-the-sdk/ * the id is always unique and never changes as its based on the MP ID, Element Names, and the key token. */ String strSingletonBaseManagedObjectID = "a0022e87-75a8-65ee-4581-d923ff06a564"; //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 GUID from above – since this is a singleton object we can get it by GUID EnterpriseManagementObject emoAdminSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strSingletonBaseManagedObjectID), ObjectQueryOptions.Default); //Get the SMLets Exchange Connector MP ManagementPack smletsMP = emg.ManagementPacks.GetManagementPack(new Guid("15d8b765-a2f8-b63e-ad14-472f9b3c12f0")); //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 = "SMLets Exchange Connector Settings v" + smletsMP.Version.ToString(); WizardData data = new AdminSettingWizardData(emoAdminSetting); wizard.WizardData = data; wizard.AddLast(new WizardStep("General", typeof(GeneralSettingsForm), wizard.WizardData)); wizard.AddLast(new WizardStep("DLL", typeof(DLLForm), wizard.WizardData)); wizard.AddLast(new WizardStep("Processing Logic", typeof(ProcessingLogicForm), wizard.WizardData)); wizard.AddLast(new WizardStep("File Attachments", typeof(FileAttachmentForm), wizard.WizardData)); wizard.AddLast(new WizardStep("Templates", typeof(TemplateForm), wizard.WizardData)); wizard.AddLast(new WizardStep("Multi-Mailbox", typeof(MultipleMailboxes), wizard.WizardData)); wizard.AddLast(new WizardStep("Custom Rules", typeof(CustomRules), wizard.WizardData)); wizard.AddLast(new WizardStep("Parsing Keywords", typeof(KeywordsForm), wizard.WizardData)); wizard.AddLast(new WizardStep("Cireson", typeof(CiresonIntegrationForm), wizard.WizardData)); wizard.AddLast(new WizardStep("Announcements", typeof(AnnouncementsForm), wizard.WizardData)); wizard.AddLast(new WizardStep("SCOM", typeof(SCOMIntegrationForm), wizard.WizardData)); wizard.AddLast(new WizardStep("A.I.", typeof(ArtificialIntelligence), wizard.WizardData)); wizard.AddLast(new WizardStep("Translation", typeof(AzureTranslate), wizard.WizardData)); wizard.AddLast(new WizardStep("Vision", typeof(AzureVision), wizard.WizardData)); wizard.AddLast(new WizardStep("Transcription", typeof(AzureSpeech), wizard.WizardData)); wizard.AddLast(new WizardStep("Workflow", typeof(WorkflowSettings), wizard.WizardData)); wizard.AddLast(new WizardStep("Logging", typeof(Logging), wizard.WizardData)); wizard.AddLast(new WizardStep("History", typeof(HistoryForm), wizard.WizardData)); wizard.AddLast(new WizardStep("About", typeof(AboutForm), wizard.WizardData)); //Show the property page PropertySheetDialog wizardWindow = new PropertySheetDialog(wizard); wizardWindow.Width = 1100; wizardWindow.Height = 750; //Update the view when done so the new values are shown bool?dialogResult = wizardWindow.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) { RequestViewRefresh(); } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> navigationNodes, NavigationModelNodeTask task, ICollection <String> parameters) { foreach (NavigationModelNode navigationNode in navigationNodes) { IDataItem dataitemIncident = null; IDataItem dataitemIncidentStatus = null; IDataItem dataitemMessageType = null; bool boolIsFormAction = false; Uri uriFormsDefinition = new Uri(NavigationModel.NavigationRoot, "Windows/Forms/"); if (navigationNode != null && uriFormsDefinition.IsBaseOf(navigationNode.Location)) { boolIsFormAction = true; FrameworkElement userControl = GetIncidentControl(navigationNode); if (userControl != null) { if (userControl.CheckAccess()) { dataitemIncident = userControl.DataContext as IDataItem; } else { using (AutoResetEvent autoreset = new AutoResetEvent(false)) { EventHandler delegateHandleUserControl = delegate(object sender, EventArgs e) { dataitemIncident = userControl.DataContext as IDataItem; autoreset.Set(); }; userControl.Dispatcher.BeginInvoke( System.Windows.Threading.DispatcherPriority.Normal, delegateHandleUserControl, null, null); autoreset.WaitOne(); } } } } else { //Console Node IDataItem dataItem = navigationNode as IDataItem; if (dataItem != null) { dataitemIncident = DataQueryHelper.GetEmoProjectionItem((Guid)dataItem[Constants.MP_PROPERTY_ID_DOLLAR], new Guid(Constants.MP_PROJECTION_TYPE_INCIDENT)); } } String strMessage = String.Empty; Boolean boolAddToActionLog = false; dataitemIncidentStatus = (IDataItem)dataitemIncident[Constants.MP_PROPERTY_INCIDENT_STATUS]; bool?result = SendEmailForm.LaunchDialog(task.DisplayName, ref dataitemMessageType, ref dataitemIncidentStatus, out strMessage, out boolAddToActionLog); if (result == null || !result.Value || String.IsNullOrEmpty(strMessage)) { // The user either did not enter any comment or he clicked the cancel button break; } dataitemIncident[Constants.MP_PROPERTY_INCIDENT_MESSAGE] = strMessage; dataitemIncident[Constants.MP_PROPERTY_INCIDENT_MESSAGE_TYPE] = dataitemMessageType; dataitemIncident[Constants.MP_PROPERTY_INCIDENT_STATUS] = dataitemIncidentStatus; if (boolAddToActionLog) { //Add the Action Log Object IDataItem dataitemSentEmailActionType = DataQueryHelper.GetEnumerations(new Guid(Constants.MP_ENUM_TYPE_SENT_EMAIL), false)[0]; IDataItem dataitemActionLogItem = DataQueryHelper.CreateNewInstanceBindableItem(new Guid(Constants.MP_CLASS_TYPE_ACTION_LOG)); dataitemActionLogItem[Constants.MP_PROPERTY_ACTION_LOG_ENTERED_DATE] = DateTime.Now; dataitemActionLogItem[Constants.MP_PROPERTY_ACTION_LOG_DESCRIPTION] = strMessage; dataitemActionLogItem[Constants.MP_PROPERTY_ACTION_LOG_ID] = Guid.NewGuid().ToString(); dataitemActionLogItem[Constants.MP_PROPERTY_ACTION_LOG_ACTION_TYPE] = dataitemSentEmailActionType; dataitemActionLogItem[Constants.MP_PROPERTY_ACTION_LOG_TITLE] = dataitemSentEmailActionType[DataItemConstants.DisplayName]; dataitemActionLogItem[Constants.MP_PROPERTY_ACTION_LOG_ENTERED_BY] = (String)DataQueryHelper.GetCurrentLoggedInUser()[DataItemConstants.DisplayName]; if (dataitemIncident.HasProperty(Constants.MP_PROPERTY_ACTION_LOG_ACTION_LOGS)) { dataitemIncident[Constants.MP_PROPERTY_ACTION_LOG_ACTION_LOGS] = dataitemActionLogItem; } } if (!boolIsFormAction) { //If this was initiated from the console we need to update the incident straight away EnterpriseManagementObjectProjectionDataType.UpdateDataItem(dataitemIncident); } } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { TimerActivitySettingsWindow timerActivitySettingsWindow = new TimerActivitySettingsWindow(); timerActivitySettingsWindow.ShowDialog(); //Make it modal, because we can. Also prevents two instances from opening. }
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("AzureAutomation2x32"); 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", null, new Version("1.0.0.0")); ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector"); String strConnectorID = emoAAConnector[classAAConnector, "Id"].ToString(); ManagementPackRule ruleConnector = mpConnectors.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(); mpConnectors.AcceptChanges(); //Update the view when done so the item is either removed or the updated Enabled value shows RequestViewRefresh(); } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { try { //Connect to MG IServiceContainer isContainer = (IServiceContainer)FrameworkServices.GetService(typeof(IServiceContainer)); IManagementGroupSession imgSession = (IManagementGroupSession)isContainer.GetService(typeof(IManagementGroupSession)); if (imgSession == null) { MessageBox.Show("Failed to connect to the current session", "Assign Incident Settings", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } EnterpriseManagementGroup emg = imgSession.ManagementGroup; //Get the analyst settings class and MP ManagementPack mpSetting = emg.ManagementPacks.GetManagementPack(new Guid("56d5c2d6-7e19-59ff-7a81-ac8a331fcb3f")); ManagementPackClass classSettings = mpSetting.GetClass("AssignSettingsClass"); //Get the emo for the settings EnterpriseManagementObject emoSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(classSettings.Id, ObjectQueryOptions.Default); //Setup form AdminForm af = new AdminForm(); if (emoSettings[classSettings, "AssignDomain1"].Value != null) { af.textD1.Text = emoSettings[classSettings, "AssignDomain1"].Value.ToString(); } if (emoSettings[classSettings, "AssignDomain2"].Value != null) { af.textD2.Text = emoSettings[classSettings, "AssignDomain2"].Value.ToString(); } if (emoSettings[classSettings, "AssignDomain3"].Value != null) { af.textD3.Text = emoSettings[classSettings, "AssignDomain3"].Value.ToString(); } if (emoSettings[classSettings, "AssignGroup1"].Value != null) { af.textG1.Text = emoSettings[classSettings, "AssignGroup1"].Value.ToString(); } if (emoSettings[classSettings, "AssignGroup2"].Value != null) { af.textG2.Text = emoSettings[classSettings, "AssignGroup2"].Value.ToString(); } if (emoSettings[classSettings, "AssignGroup2"].Value != null) { af.textG3.Text = emoSettings[classSettings, "AssignGroup3"].Value.ToString(); } if (emoSettings[classSettings, "AssignShowAccount"].Value != null) { if (emoSettings[classSettings, "AssignShowAccount"].Value.ToString() == "1") { af.checkShow.Checked = true; } } if (emoSettings[classSettings, "AssignShowTier"].Value != null) { if (emoSettings[classSettings, "AssignShowTier"].Value.ToString() == "1") { af.checkShowTier.Checked = true; } } if (emoSettings[classSettings, "AssignedUserAlias"].Value != null) { af.textAssignedUserName.Text = emoSettings[classSettings, "AssignedUserAlias"].Value.ToString(); } else { af.textAssignedUserName.Text = "AssignedUser"; } if (emoSettings[classSettings, "ActionLogAlias"].Value != null) { af.textActionLogName.Text = emoSettings[classSettings, "ActionLogAlias"].Value.ToString(); } else { af.textActionLogName.Text = "ActionLogs"; } DialogResult dr = af.ShowDialog(); if (dr != DialogResult.Cancel) { //save settings emoSettings[classSettings, "AssignDomain1"].Value = af.textD1.Text; emoSettings[classSettings, "AssignDomain2"].Value = af.textD2.Text; emoSettings[classSettings, "AssignDomain3"].Value = af.textD3.Text; emoSettings[classSettings, "AssignGroup1"].Value = af.textG1.Text; emoSettings[classSettings, "AssignGroup2"].Value = af.textG2.Text; emoSettings[classSettings, "AssignGroup3"].Value = af.textG3.Text; if (af.checkShow.Checked) { emoSettings[classSettings, "AssignShowAccount"].Value = "1"; } else { emoSettings[classSettings, "AssignShowAccount"].Value = "0"; } if (af.checkShowTier.Checked) { emoSettings[classSettings, "AssignShowTier"].Value = "1"; } else { emoSettings[classSettings, "AssignShowTier"].Value = "0"; } emoSettings[classSettings, "AssignedUserAlias"].Value = af.textAssignedUserName.Text; emoSettings[classSettings, "ActionLogAlias"].Value = af.textActionLogName.Text; emoSettings.Commit(); } } catch (System.Exception e) { MessageBox.Show(e.Message); return; } }
public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters) { //Used for idataitem (form mode, 1=new form, 2=edit form); int iMode = 0; //Set title for messageboxes string sAppTitle = "Assign Incident Directly To Analyst"; //Connect to MG IServiceContainer isContainer = (IServiceContainer)FrameworkServices.GetService(typeof(IServiceContainer)); IManagementGroupSession imgSession = (IManagementGroupSession)isContainer.GetService(typeof(IManagementGroupSession)); if (imgSession == null) { MessageBox.Show("Failed to connect to the current session", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } EnterpriseManagementGroup emg = imgSession.ManagementGroup; //Get the incident class (System.WorkItem.Incident) ManagementPackClass classIncident = emg.EntityTypes.GetClass(new Guid("A604B942-4C7B-2FB2-28DC-61DC6F465C68")); //Microsoft.Windows.Library ManagementPack mpWindows = emg.ManagementPacks.GetManagementPack(new Guid("545131F0-58DE-1914-3A82-4FCAC9100A33")); //Get the Microsoft.AD.User class ManagementPackClass mpcADUser = emg.EntityTypes.GetClass("Microsoft.AD.User", mpWindows); //Return the currently selected incident reference NavigationModelNodeBase selincident = nodes[0]; //Form mode (not new)? if (selincident.Location.AbsoluteUri.IndexOf("FormDisplay", 0) > 0) { iMode = 2; } //Get objects EnterpriseManagementObject emoSelIncident = null; IDataItem i = ConsoleContextHelper.Instance.GetFormDataContext(nodes[0]); //Get the analyst settings class and MP ManagementPack mpSetting = emg.ManagementPacks.GetManagementPack(new Guid("56d5c2d6-7e19-59ff-7a81-ac8a331fcb3f")); ManagementPackClass classSettings = mpSetting.GetClass("AssignSettingsClass"); //Get the emo for the settings EnterpriseManagementObject emoSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(classSettings.Id, ObjectQueryOptions.Default); //TP names string sAssignedTo = "AssignedUser"; string sActionLog = "ActionLogs"; if (emoSettings[classSettings, "AssignedUserAlias"].Value != null) { sAssignedTo = emoSettings[classSettings, "AssignedUserAlias"].Value.ToString(); } if (emoSettings[classSettings, "ActionLogAlias"].Value != null) { sActionLog = emoSettings[classSettings, "ActionLogAlias"].Value.ToString(); } //Check if new if (!(bool)i["$IsNew$"]) { //Now get the guid of the selected workitem. Depending on the view type, the return will be different, so take it after the last "." //There are lots of ways of doing this, this is not the best way but it was the first I learnt and it works string strGuid = selincident.GetId().Substring(selincident.GetId().LastIndexOf('.') + 1); //Get the emo of the workitem via it's guid emoSelIncident = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strGuid), ObjectQueryOptions.Default); } //Creating new incident else { iMode = 1; } //Was task was run from an workitem opened for editing, as opposed to a list or view? if (selincident.Location.AbsoluteUri.IndexOf("FormDisplay", 0) != -1) { iMode = 2; } //Get the status guid Guid gStatus = Guid.NewGuid(); try { //"New" status will throw an exception to must catch here if (i["Status"] != null) { gStatus = (Guid)(i["Status"] as IDataItem)["Id"]; } } catch { } //Get the incident class (System.WorkItem.Incident) ManagementPackClass mpcIncident = emg.EntityTypes.GetClass(new Guid("a604b942-4c7b-2fb2-28dc-61dc6f465c68")); //Check if the incident is closed if (gStatus == new Guid("bd0ae7c4-3315-2eb3-7933-82dfc482dbaf")) { MessageBox.Show("This incident cannot be reassigned as it has been closed.", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //Note - we are alllowing resolved incidents to be re-assigned, to prevent this, uncomment the following block: /*else if (gStatus == new Guid("2b8830b6-59f0-f574-9c2a-f4b4682f1681")) * { * MessageBox.Show("This incident cannot be reassigned as it has been resolved.", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); * return; * } */ //Current assignee and Id string sId = ""; string sUser = ""; string sTierGuid = ""; if (iMode == 0) { //View mode sUser = this.GetProperty(ref emg, emoSelIncident, ref mpcADUser, "DisplayName"); sId = emoSelIncident[mpcIncident, "Id"].Value.ToString(); if (emoSelIncident[mpcIncident, "TierQueue"].Value != null) { sTierGuid = ((ManagementPackEnumeration)emoSelIncident[mpcIncident, "TierQueue"].Value).Id.ToString(); } } else { //New or edit form mode try { //Get display name of current assignee if (i[sAssignedTo] == null) { sUser = "******"; } else { sUser = (string)(i[sAssignedTo] as IDataItem)["DisplayName"]; } } catch { //Set no assignee sUser = "******"; } sId = (string)i["Id"]; try { //Check current tier queue enum value if (i["TierQueue"] != null) { sTierGuid = ((Guid)(i["TierQueue"] as IDataItem)["Id"]).ToString(); } } catch { } } //Create a new instance of the form and set it up AssignForm af = new AssignForm(); af.sTierGuid = sTierGuid; af.Text = "Assign incident " + sId + " directly to Analyst - currently assigned to " + sUser; af.textDefault.Text = sUser; af.emg = emg; //Show the analyst/tier selection form DialogResult dr = af.ShowDialog(); if (dr != DialogResult.Cancel) { //Get the samaccountname from the right hand part of the combobox.text after the ! string sADUserName = af.comboAnalysts.Text.Substring(af.comboAnalysts.Text.LastIndexOf("(") + 1); //Remove last ) sADUserName = sADUserName.Substring(0, sADUserName.Length - 1); //Format to get the display name only from the left part - this is used for the actionlog entry string sADUserDisplayName = af.comboAnalysts.Text.Substring(0, af.comboAnalysts.Text.LastIndexOf("(")).Trim(); try { //Set the query for the user - note - usernames are assumed unique across configured domains //If this is not the case, you need to customise these criteria to include a domain string sADUserCriteria = String.Format(@" <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/""> <Reference Id=""Microsoft.Windows.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""MSWinLib"" /> <Expression> <SimpleExpression> <ValueExpressionLeft> <Property>$Target/Property[Type='MSWinLib!Microsoft.AD.User']/UserName$</Property> </ValueExpressionLeft> <Operator>Equal</Operator> <ValueExpressionRight> <Value>" + sADUserName + @"</Value> </ValueExpressionRight> </SimpleExpression> </Expression> </Criteria> ", mpWindows.KeyToken, mpWindows.Version.ToString()); //Object query options ObjectQueryOptions objQueryOpts = new ObjectQueryOptions(); objQueryOpts.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered; objQueryOpts.DefaultPropertyRetrievalBehavior = ObjectPropertyRetrievalBehavior.All; //We are searching via samAccountName so there will be only 1 item objQueryOpts.MaxResultCount = 1; //Get the AD User CI object EnterpriseManagementObjectCriteria emocADUser = new EnterpriseManagementObjectCriteria(sADUserCriteria, mpcADUser, emg); IObjectReader <EnterpriseManagementObject> orADUser = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emocADUser, objQueryOpts); EnterpriseManagementObject emoAssignToUser = orADUser.ElementAt(0); if (iMode == 0) { //View mode - create a new assigned to user relationship ManagementPackRelationship relAssignedToUser = emg.EntityTypes.GetRelationshipClass(new Guid("15e577a3-6bf9-6713-4eac-ba5a5b7c4722")); CreatableEnterpriseManagementRelationshipObject cemroAssignedToUser = new CreatableEnterpriseManagementRelationshipObject(emg, relAssignedToUser); //Set the source and target... cemroAssignedToUser.SetSource(emoSelIncident); cemroAssignedToUser.SetTarget(emoAssignToUser); //Save cemroAssignedToUser.Commit(); //Add a new comment this.AddActionLogEntry(emg, emoSelIncident, "Incident was assigned to " + sADUserDisplayName, af.textComment.Text); //Check tier if (af.bShowTier) { if (af.comboTier.Text == "") { emoSelIncident[classIncident, "TierQueue"].Value = null; } else { ManagementPackEnumeration mpeTier = emg.EntityTypes.GetEnumeration(new Guid(af.comboTierGuids.Items[af.comboTier.SelectedIndex].ToString())); emoSelIncident[classIncident, "TierQueue"].Value = mpeTier; } emoSelIncident.Commit(); } //Refresh the current incident view this.RequestViewRefresh(); } else { //Note - IDataItem property names depend on the type projection being used and may differ from these //Form mode, create a proxy to the emo user object to set on the form EnterpriseManagementObjectDataType dataType = new EnterpriseManagementObjectDataType(mpcADUser); IDataItem iUser = dataType.CreateProxyInstance(emoAssignToUser); i[sAssignedTo] = iUser; //Check tier if (af.bShowTier) { if (af.comboTier.Text == "") { //Remove tier i["TierQueue"] = null; } else { //Set tier, get enum first ManagementPackEnumeration mpeTier = emg.EntityTypes.GetEnumeration(new Guid(af.comboTierGuids.Items[af.comboTier.SelectedIndex].ToString())); i["TierQueue"] = mpeTier; } } //Uncommenting this will cause the IDataItem to be saved and thus update the actual object in the database, normally you don't want to do this //as you want the user to click OK or cancel on the form instead //EnterpriseManagementObjectProjectionDataType.UpdateDataItem(i); //IDataItem Action log // //Get the System.WorkItem.Library mp ManagementPack mpWorkItemLibrary = emg.ManagementPacks.GetManagementPack(new Guid("405D5590-B45F-1C97-024F-24338290453E")); //Get the actionlog class ManagementPackClass mpcActionLog = emg.EntityTypes.GetClass("System.WorkItem.TroubleTicket.ActionLog", mpWorkItemLibrary); //Create a new action log entry as an idataitem CreatableEnterpriseManagementObject cemoActionLog = new CreatableEnterpriseManagementObject(emg, mpcActionLog); EnterpriseManagementObjectDataType dataTypeLog = new EnterpriseManagementObjectDataType(mpcActionLog); IDataItem iLog = dataTypeLog.CreateProxyInstance(cemoActionLog); //Setup the new action log entry iLog["Id"] = Guid.NewGuid().ToString(); iLog["Description"] = af.textComment.Text; iLog["Title"] = "Reassignment Comment"; iLog["EnteredBy"] = UserPrincipal.Current.DisplayName; iLog["EnteredDate"] = DateTime.Now.ToUniversalTime(); //Set action type (this also adds the icon and is required) ManagementPackEnumeration enumActionLog = mpWorkItemLibrary.GetEnumerations().GetItem("System.WorkItem.ActionLogEnum.TaskExecuted"); iLog["ActionType"] = enumActionLog; //This adds the new idataitem log entry to the entries displayed on the form, it does not over-write the existing entries i[sActionLog] = iLog; } } catch (System.Exception e) { //Oops MessageBox.Show(e.Message + "\n\n" + e.StackTrace, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } }