/// <summary> /// This constructor is for unhosted objects managed by specific instance of defined Action Point class OR for hosted objects, which are hosted on defined Action Point class. /// </summary> /// <param name="managementGroup"></param> /// <param name="seedClass"></param> /// <param name="actionPointClassName"></param> /// <param name="insertConnector"></param> public SCOMClassInstanceEditor(ManagementGroup managementGroup, ManagementPackClass seedClass, ManagementPackClass actionPointClass, MonitoringConnector insertConnector, ManagementPackRelationship hostingRelationship = null) { myActionPointClass = actionPointClass; if (seedClass.Hosted) { relMAPShouldManageEntity = null; relMAPManagesEntity = null; relHosting = hostingRelationship ?? managementGroup.EntityTypes.GetRelationshipClass(SystemId.HostingRelationshipId); } else { relHosting = null; if (actionPointClass.IsSubtypeOf(managementGroup.EntityTypes.GetClass(SystemCenterId.ManagementActionPointClassId)) || actionPointClass.Id == SystemCenterId.ManagementActionPointClassId) { relMAPShouldManageEntity = managementGroup.EntityTypes.GetRelationshipClass(SystemCenterId.ManagementActionPointShouldManageEntityRelationshipId); } else if (actionPointClass.IsSubtypeOf(managementGroup.EntityTypes.GetClass(SystemCenterId.HealthServiceClassId)) || actionPointClass.Id == SystemCenterId.HealthServiceClassId) { relHSShouldManageEntiry = managementGroup.EntityTypes.GetRelationshipClass(SystemCenterId.HealthServiceShouldManageEntityRelationshipId); } else { throw new NotSupportedException("For unhosted scenario, action point class should be either Microsoft.SystemCenter.ManagementActionPoint or Microsoft.SystemCenter.HealthService, or inherited from these classes."); } relMAPManagesEntity = managementGroup.EntityTypes.GetRelationshipClass(SystemCenterId.ManagementActionPointManagesEntityRelationshipId); } myActionPoints = new List <MonitoringObject>(); myActionPoints.AddRange(managementGroup.EntityObjects.GetObjectReader <MonitoringObject>(myActionPointClass, ObjectQueryOptions.Default)); DefaultConstructor(managementGroup, seedClass, insertConnector); }
public CablesTree(EnterpriseManagementGroup _emg, ManagementPackRelationship _relChildNetworkAdapterRefParentNetworkAdapter) { emg = _emg; relChildNetworkAdapterRefParentNetworkAdapter = _relChildNetworkAdapterRefParentNetworkAdapter; classModule = null; Location_Id = Guid.Empty; }
private void AddToCatalogWindow_Loaded(object sender, RoutedEventArgs e) { try { emg = GetSession(); if (emg == null) { emg = new EnterpriseManagementGroup("SM"); } //mpAssetCore = emg.ManagementPacks.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version()); mpSoftLibrary = emg.ManagementPacks.GetManagementPack("SMCenter.SoftwareAssetManagement.Library", "75b45bd6835084b1", new Version()); //mpSystemSoftwareLibrary = emg.ManagementPacks.GetManagementPack("System.Software.Library", "31bf3856ad364e35", new Version()); //classSoftwareItem = emg.EntityTypes.GetClass("System.SoftwareItem", mpSystemSoftwareLibrary); classSoftwareTitle = emg.EntityTypes.GetClass("SMCenter.SoftwareTitle", mpSoftLibrary); classSoftwareVersion = emg.EntityTypes.GetClass("SMCenter.SoftwareVersion", mpSoftLibrary); //classPublisher = emg.EntityTypes.GetClass("SMCenter.Company", mpAssetCore); //SMCenter.PublisherHasSoftwareTitle //SMCenter.SoftwareTitleHasSoftwareVersion //SMCenter.SoftwareVersionReferencesDiscoveredSoftwareItem relSoftwareTitleHasSoftwareVersion = emg.EntityTypes.GetRelationshipClass("SMCenter.SoftwareTitleHasSoftwareVersion", mpSoftLibrary); //relExcludedSoftwareItemGroup = emg.EntityTypes.GetRelationshipClass("SMCenter.ExcludedSoftwareItemGroupContainsEntities", mpSoftLibrary); //TemplateSoftwareTitle.PathString = "SotwareTitle"; //TemplateSoftwareTitle.mpClass = classSoftwareTitle; } catch (Exception ex) { System.Windows.MessageBox.Show("Initialize procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error); this.Close(); } }
/// <summary> /// This constructor is for unhosted objects managed by specific instance of defined Action Point class OR for hosted objects, /// which are hosted on defined Action Point class. /// </summary> /// <param name="managementGroup"></param> /// <param name="seedClass"></param> /// <param name="actionPointClassName"></param> /// <param name="monitoringConnector"></param> public ScomClassInstanceEditor(ManagementGroup managementGroup, ManagementPackClass seedClass, ManagementPackClass actionPointClass, MonitoringConnector monitoringConnector = null, ManagementPackRelationship hostingRelationship = null) : this(managementGroup, seedClass, monitoringConnector) { _actionPointClass = actionPointClass ?? throw new ArgumentNullException(nameof(actionPointClass)); if (seedClass.Hosted) { _relMapShouldManageEntity = null; _relMapManagesEntity = null; _relHosting = hostingRelationship ?? managementGroup.EntityTypes.GetRelationshipClass(SystemRelationship.Hosting); } else { if (actionPointClass.IsSubtypeOf(managementGroup.EntityTypes.GetClass(_managementActionPointClassId)) || actionPointClass.Id == _managementActionPointClassId) { _relMapShouldManageEntity = managementGroup.EntityTypes.GetRelationshipClass(_managementActionPointShouldManageEntityRelationshipId); } else if (actionPointClass.IsSubtypeOf(managementGroup.EntityTypes.GetClass(SystemMonitoringClass.HealthService)) || actionPointClass.Id == SystemMonitoringClass.HealthService.Id) { _relHsShouldManageEntity = managementGroup.EntityTypes.GetRelationshipClass(SystemMonitoringRelationship.HealthServiceShouldManageEntity); } else { throw new NotSupportedException("For unhosted scenario, action point class should be either Microsoft.SystemCenter.ManagementActionPoint or Microsoft.SystemCenter.HealthService, or inherited from these classes."); } _relMapManagesEntity = managementGroup.EntityTypes.GetRelationshipClass(_managementActionPointManagesEntityRelationshipId); } _actionPoints.AddRange(managementGroup.EntityObjects.GetObjectReader <MonitoringObject>(_actionPointClass, ObjectQueryOptions.Default)); }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { //try //{ GetSession(); mpCore = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version()); mpNA = emg.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version()); classLocation = emg.EntityTypes.GetClass("SMCenter.Location", mpCore); //classNetworkMap = emg.EntityTypes.GetClass("SMCenter.NetworkMap", mpNA); relLoctoLoc = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mpCore); //Fill Templates this.TemplateLocationItem.emg = emg; this.TemplateLocationItem.PathString = "LinkedLocation"; this.TemplateLocationItem.mpClass = classLocation; this.TemplateLocationItem.mpRelationshipClass = relLoctoLoc; this.TemplateLocationItem.criteria = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", classLocation); //////Handlers this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted)); this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit)); //} //catch (Exception ex) //{ // System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message); //} }
public TreeViewForm(EnterpriseManagementGroup _emg, ManagementPackClass _mpClass, ManagementPackRelationship _RelationshipClass, EnterpriseManagementObjectCriteria _criteria) { InitializeComponent(); emg = _emg; mpClass = _mpClass; RelationshipClass = _RelationshipClass; criteria = _criteria; }
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); } }
/// <summary> /// This constructor is for unhosted objects managed by All Management Server resource pool. /// </summary> /// <param name="managementGroup"></param> /// <param name="seedClass"></param> /// <param name="insertConnector"></param> public ScomClassInstanceEditor(ManagementGroup managementGroup, ManagementPackClass seedClass, MonitoringConnector monitoringConnector = null) { _managementGroup = managementGroup ?? throw new ArgumentNullException(nameof(managementGroup)); _seedClass = seedClass ?? throw new ArgumentNullException(nameof(seedClass)); _monitoringConnector = monitoringConnector; _relToClearHs = _managementGroup.EntityTypes.GetRelationshipClass(SystemMonitoringRelationship.HealthServiceShouldManageEntity); _relToClearMap = _managementGroup.EntityTypes.GetRelationshipClass(_managementActionPointShouldManageEntityRelationshipId); }
public CablesTree(EnterpriseManagementGroup _emg, ManagementPackRelationship _relChildNetworkAdapterRefParentNetworkAdapter, ManagementPackClass _classModule, ManagementPackRelationship _relConfigItemRefLocation, LogFile _LogFile) { emg = _emg; relChildNetworkAdapterRefParentNetworkAdapter = _relChildNetworkAdapterRefParentNetworkAdapter; classModule = _classModule; relConfigItemRefLocation = _relConfigItemRefLocation; Location_Id = new Guid(); LogFile = _LogFile; }
/// <summary> /// Get DiskPartitions /// </summary> private void GetDiskPartitions() { // Get var diskPartitions = SNMP.WalkSNMP(SNMP.sysHostDiskPartition, Address, Port, Community); if (diskPartitions.Count > 0) { // Create Device Management Pack Class ManagementPackClass mpc_Device = SCOM_Functions.GetManagementPackClass("AP.F5.Device"); // Create Root Entity Class & Display Name Prop ManagementPackClass mpc_Entity = SCOM_Functions.GetManagementPackClass("System.Entity"); ManagementPackProperty mpp_EntityDisplayName = mpc_Entity.PropertyCollection["DisplayName"]; // Parent Device Key Property (IP Address) ManagementPackProperty mpp_DeviceKey = mpc_Device.PropertyCollection["DeviceName"]; // Create DiskPartitions Group Object ManagementPackClass mpc_DiskPartitionGroup = SCOM_Functions.GetManagementPackClass("AP.F5.Device.DiskPartitionsGroup"); SCOM_Object_DiskPartitionGroup = new CreatableEnterpriseManagementObject(m_managementGroup, mpc_DiskPartitionGroup); SCOM_Object_DiskPartitionGroup[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Device ManagementPackProperty mpp_DiskPartitionGroupName = mpc_DiskPartitionGroup.PropertyCollection["Name"]; SCOM_Object_DiskPartitionGroup[mpp_DiskPartitionGroupName].Value = "Disks"; // Create Management Pack Class Objects for DiskPartition and Needed Properties ManagementPackClass mpc_DiskPartition = SCOM_Functions.GetManagementPackClass(className: "AP.F5.Device.DiskPartition"); ManagementPackProperty mpp_DiskPartitionIndex = mpc_DiskPartition.PropertyCollection["Index"]; ManagementPackProperty mpp_DiskPartitionMountpoint = mpc_DiskPartition.PropertyCollection["Mountpoint"]; // Set DiskPartition-Group Relationship ManagementPackRelationship mpr_DiskPartitionsGroup = SCOM_Functions.GetManagementPackRelationship("AP.F5.Device.DiskPartitionsGroup.HostsDiskPartitions"); for (int i = 0; i < diskPartitions.Count; i++) { DiskPartition newDiskPartition = new DiskPartition(); string index = "." + diskPartitions[i].Id.ToString(); index = index.Replace(SNMP.sysHostDiskPartition, ""); // Create SCOM Fan Object newDiskPartition.SCOM_Object_DiskPartition = new CreatableEnterpriseManagementObject(SCOM_Functions.m_managementGroup, mpc_DiskPartition); // Set Key of Device newDiskPartition.SCOM_Object_DiskPartition[mpp_DeviceKey].Value = SystemNodeName; // Set Key of DiskPartitions Group newDiskPartition.SCOM_Object_DiskPartition[mpp_DiskPartitionGroupName].Value = "Disks"; //Set Logical Entity Display Name newDiskPartition.SCOM_Object_DiskPartition[mpp_EntityDisplayName].Value = diskPartitions[i].Data.ToString(); // Set Fan Properties newDiskPartition.SCOM_Object_DiskPartition[mpp_DiskPartitionIndex].Value = index; newDiskPartition.SCOM_Object_DiskPartition[mpp_DiskPartitionMountpoint].Value = diskPartitions[i].Data.ToString(); DiskPartitions.Add(newDiskPartition); } } }
/// <summary> /// Get Processors /// </summary> private void GetProcessors() { // Get var processors = SNMP.WalkSNMP(SNMP.sysMultiHostCpuIndex, Address, Port, Community); if (processors.Count > 0) { // Create Device Management Pack Class ManagementPackClass mpc_Device = SCOM_Functions.GetManagementPackClass("AP.F5.Device"); // Create Root Entity Class & Display Name Prop ManagementPackClass mpc_Entity = SCOM_Functions.GetManagementPackClass("System.Entity"); ManagementPackProperty mpp_EntityDisplayName = mpc_Entity.PropertyCollection["DisplayName"]; // Parent Device Key Property (IP Address) ManagementPackProperty mpp_DeviceKey = mpc_Device.PropertyCollection["DeviceName"]; // Create Processors Group Object ManagementPackClass mpc_DeviceProcessorsGroup = SCOM_Functions.GetManagementPackClass("AP.F5.Device.ProcessorsGroup"); SCOM_Object_ProcessorGroup = new CreatableEnterpriseManagementObject(m_managementGroup, mpc_DeviceProcessorsGroup); SCOM_Object_ProcessorGroup[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Device ManagementPackProperty mpp_DeviceProcessorsGroupName = mpc_DeviceProcessorsGroup.PropertyCollection["Name"]; SCOM_Object_ProcessorGroup[mpp_DeviceProcessorsGroupName].Value = "Processors"; // Create Management Pack Class Objects for Processor and Needed Properties ManagementPackClass mpc_Processor = SCOM_Functions.GetManagementPackClass(className: "AP.F5.Device.Processor"); ManagementPackProperty mpp_ProcessorIndex = mpc_Processor.PropertyCollection["Index"]; ManagementPackProperty mpp_ProcessorName = mpc_Processor.PropertyCollection["Name"]; // Set Processor-Group Relationship ManagementPackRelationship mpr_ProcessorsGroup = SCOM_Functions.GetManagementPackRelationship("AP.F5.Device.ProcessorsGroup.HostsProcessors"); for (int i = 0; i < processors.Count; i++) { Processor newProcessor = new Processor(); string index = "." + processors[i].Id.ToString(); index = index.Replace(SNMP.sysMultiHostCpuIndex, ""); // Create SCOM Fan Object newProcessor.SCOM_Object_Processor = new CreatableEnterpriseManagementObject(SCOM_Functions.m_managementGroup, mpc_Processor); // Set Key of Device newProcessor.SCOM_Object_Processor[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Fans Group newProcessor.SCOM_Object_Processor[mpp_DeviceProcessorsGroupName].Value = "Processors"; //Set Logical Entity Display Name newProcessor.SCOM_Object_Processor[mpp_EntityDisplayName].Value = "CPU-" + i.ToString(); // Set Fan Properties newProcessor.SCOM_Object_Processor[mpp_ProcessorIndex].Value = index; newProcessor.SCOM_Object_Processor[mpp_ProcessorName].Value = "CPU-" + i.ToString(); Processors.Add(newProcessor); } } }
private void DefaultConstructor(ManagementGroup managementGroup, ManagementPackClass seedClass, MonitoringConnector insertConnector) { mySeedClass = seedClass; myConnector = insertConnector; myMG = managementGroup; relToClearHS = managementGroup.EntityTypes.GetRelationshipClass(SystemCenterId.HealthServiceShouldManageEntityRelationshipId); relToClearMAP = managementGroup.EntityTypes.GetRelationshipClass(SystemCenterId.ManagementActionPointShouldManageEntityRelationshipId); // load initial data Refresh(); }
/// <summary> /// Get Fans /// </summary> private void GetFans() { // Get Count of Fans int fanCount = Convert.ToInt32(SNMP.GetSNMP(SNMP.sysChassisFanNumber, Address, Port, Community)[0].Data.ToString()); // If There Are Fans Then Create FanGroup and Relationship if (fanCount > 0) { // Create Device Group Management Pack Class ManagementPackClass mpc_Device = SCOM_Functions.GetManagementPackClass("AP.F5.Device"); // Create Root Entity Class & Display Name Prop ManagementPackClass mpc_Entity = SCOM_Functions.GetManagementPackClass("System.Entity"); ManagementPackProperty mpp_EntityDisplayName = mpc_Entity.PropertyCollection["DisplayName"]; // Parent Device Key Property (IP Address) ManagementPackProperty mpp_DeviceKey = mpc_Device.PropertyCollection["DeviceName"]; // Create FanGroup Object ManagementPackClass mpc_DeviceFanGroup = SCOM_Functions.GetManagementPackClass("AP.F5.Device.FansGroup"); SCOM_Object_FanGroup = new CreatableEnterpriseManagementObject(m_managementGroup, mpc_DeviceFanGroup); SCOM_Object_FanGroup[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Device ManagementPackProperty mpp_DeviceFansGroupName = mpc_DeviceFanGroup.PropertyCollection["Name"]; SCOM_Object_FanGroup[mpp_DeviceFansGroupName].Value = "Fans"; // Create Management Pack Class Objects for Fan and Needed Properties ManagementPackClass mpc_Fan = SCOM_Functions.GetManagementPackClass(className: "AP.F5.Device.Fan"); ManagementPackProperty mpp_FanIndex = mpc_Fan.PropertyCollection["Index"]; ManagementPackProperty mpp_FanName = mpc_Fan.PropertyCollection["Name"]; // Set Fan-Group Relationship ManagementPackRelationship mpr_FanGroup = SCOM_Functions.GetManagementPackRelationship("AP.F5.Device.FansGroup.HostsFans"); // Create Fans for (int i = 1; i <= fanCount; i++) { Fan newfan = new Fan(); // Create SCOM Fan Object newfan.SCOM_Object_Fan = new CreatableEnterpriseManagementObject(SCOM_Functions.m_managementGroup, mpc_Fan); // Set Key of Device newfan.SCOM_Object_Fan[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Fans Group newfan.SCOM_Object_Fan[mpp_DeviceFansGroupName].Value = "Fans"; //Set Logical Entity Display Name newfan.SCOM_Object_Fan[mpp_EntityDisplayName].Value = "Fan-" + i.ToString(); // Set Fan Properties newfan.SCOM_Object_Fan[mpp_FanIndex].Value = Convert.ToInt32(SNMP.GetSNMP(SNMP.sysChassisFanIndex + i.ToString(), Address, Port, Community)[0].Data.ToString());; newfan.SCOM_Object_Fan[mpp_FanName].Value = "Fan-" + i.ToString(); Fans.Add(newfan); } } }
/// <summary> /// Get Power Supplies /// </summary> private void GetPowerSupplies() { // Get Count of PowerSupplies int powerSupplyCount = Convert.ToInt16(SNMP.GetSNMP(SNMP.sysChassisPowerSupplyNumber, Address, Port, Community)[0].Data.ToString()); // If There are Fans Then Continue if (powerSupplyCount > 0) { // Create Device Group Management Pack Class ManagementPackClass mpc_Device = SCOM_Functions.GetManagementPackClass("AP.F5.Device"); // Create Root Entity Class & Display Name Prop ManagementPackClass mpc_Entity = SCOM_Functions.GetManagementPackClass("System.Entity"); ManagementPackProperty mpp_EntityDisplayName = mpc_Entity.PropertyCollection["DisplayName"]; // Parent Device Key Property (IP Address) ManagementPackProperty mpp_DeviceKey = mpc_Device.PropertyCollection["DeviceName"]; // Create PowerSuppliesGroup Object ManagementPackClass mpc_DevicePowerSupplyGroup = SCOM_Functions.GetManagementPackClass("AP.F5.Device.PowerSuppliesGroup"); SCOM_Object_PowerSupplyGroup = new CreatableEnterpriseManagementObject(m_managementGroup, mpc_DevicePowerSupplyGroup); SCOM_Object_PowerSupplyGroup[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Device ManagementPackProperty mpp_DevicePowerSuppliesGroupName = mpc_DevicePowerSupplyGroup.PropertyCollection["Name"]; SCOM_Object_PowerSupplyGroup[mpp_DevicePowerSuppliesGroupName].Value = "PSUs"; // Create Management Pack Class Objects for PowerSupply and Needed Properties ManagementPackClass mpc_PowerSupply = SCOM_Functions.GetManagementPackClass(className: "AP.F5.Device.PowerSupply"); ManagementPackProperty mpp_PowerSupplyIndex = mpc_PowerSupply.PropertyCollection["Index"]; ManagementPackProperty mpp_PowerSupplyName = mpc_PowerSupply.PropertyCollection["Name"]; // Set PowerSupply-Group Relationship ManagementPackRelationship mpr_PowerSuppliesGroup = SCOM_Functions.GetManagementPackRelationship("AP.F5.Device.PowerSuppliesGroup.HostsPowerSupplies"); for (int i = 1; i <= powerSupplyCount; i++) { PowerSupply newpsu = new PowerSupply(); // Create SCOM Object newpsu.SCOM_Object_PowerSupply = new CreatableEnterpriseManagementObject(SCOM_Functions.m_managementGroup, mpc_PowerSupply); // Set Key of Device newpsu.SCOM_Object_PowerSupply[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Fans Group newpsu.SCOM_Object_PowerSupply[mpp_DevicePowerSuppliesGroupName].Value = "PSUs"; //Set Logical Entity Display Name newpsu.SCOM_Object_PowerSupply[mpp_EntityDisplayName].Value = "PSU-" + i.ToString(); // Set Fan Properties newpsu.SCOM_Object_PowerSupply[mpp_PowerSupplyIndex].Value = Convert.ToInt32(SNMP.GetSNMP(SNMP.sysChassisPowerSupplyIndex + i.ToString(), Address, Port, Community)[0].Data.ToString()); newpsu.SCOM_Object_PowerSupply[mpp_PowerSupplyName].Value = "PSU-" + i.ToString(); PowerSupplies.Add(newpsu); } } }
/// <summary> /// Get Temp Sensor /// </summary> private void GetTempSensors() { // Get Count of Temperature Sensors int TempSensorCount = Convert.ToInt16(SNMP.GetSNMP(SNMP.sysChassisTempNumber, Address, Port, Community)[0].Data.ToString()); // If we have Temperature Sensors if (TempSensorCount > 0) { // Create Device Group Management Pack Class ManagementPackClass mpc_Device = SCOM_Functions.GetManagementPackClass("AP.F5.Device"); // Create Root Entity Class & Display Name Prop ManagementPackClass mpc_Entity = SCOM_Functions.GetManagementPackClass("System.Entity"); ManagementPackProperty mpp_EntityDisplayName = mpc_Entity.PropertyCollection["DisplayName"]; // Parent Device Key Property (IP Address) ManagementPackProperty mpp_DeviceKey = mpc_Device.PropertyCollection["DeviceName"]; // Create FanGroup Object ManagementPackClass mpc_DeviceTempSensorsGroup = SCOM_Functions.GetManagementPackClass("AP.F5.Device.TempSensorsGroup"); SCOM_Object_TempSensorsGroup = new CreatableEnterpriseManagementObject(m_managementGroup, mpc_DeviceTempSensorsGroup); SCOM_Object_TempSensorsGroup[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Device ManagementPackProperty mpp_DeviceTempSensorsGroupName = mpc_DeviceTempSensorsGroup.PropertyCollection["Name"]; SCOM_Object_TempSensorsGroup[mpp_DeviceTempSensorsGroupName].Value = "Temp. Sensors"; // Create Management Pack Class Objects for TempSensor and Needed Properties ManagementPackClass mpc_TempSensor = SCOM_Functions.GetManagementPackClass(className: "AP.F5.Device.TempSensor"); ManagementPackProperty mpp_TempSensorIndex = mpc_TempSensor.PropertyCollection["Index"]; ManagementPackProperty mpp_TempSensorName = mpc_TempSensor.PropertyCollection["Name"]; // Set Fan-Group Relationship ManagementPackRelationship mpr_TempSensorsGroup = SCOM_Functions.GetManagementPackRelationship("AP.F5.Device.TempSensorsGroup.HostsTempSensors"); // Create Temp Sensors for (int i = 1; i <= TempSensorCount; i++) { TempSensor newTempSensor = new TempSensor(); // Create SCOM TempSensor Object newTempSensor.SCOM_Object_TempSensor = new CreatableEnterpriseManagementObject(SCOM_Functions.m_managementGroup, mpc_TempSensor); // Set Key of Device newTempSensor.SCOM_Object_TempSensor[mpp_DeviceKey].Value = SystemNodeName; // Set Key of Fans Group newTempSensor.SCOM_Object_TempSensor[mpp_DeviceTempSensorsGroupName].Value = "Temp. Sensors"; //Set Logical Entity Display Name newTempSensor.SCOM_Object_TempSensor[mpp_EntityDisplayName].Value = "TempSensor-" + i.ToString(); // Set Fan Properties newTempSensor.SCOM_Object_TempSensor[mpp_TempSensorIndex].Value = Convert.ToInt32(SNMP.GetSNMP(SNMP.sysChassisTempIndex + i.ToString(), Address, Port, Community)[0].Data.ToString()); newTempSensor.SCOM_Object_TempSensor[mpp_TempSensorName].Value = "TempSensor-" + i.ToString(); TempSensors.Add(newTempSensor); } } }
public static TreeViewItem Create(Guid NetworkAdapter_Guid, EnterpriseManagementGroup _emg, ManagementPackRelationship _relNetworkAdapterHasChildNetworkAdapter) { emg = _emg; relNetworkAdapterHasChildNetworkAdapter = _relNetworkAdapterHasChildNetworkAdapter; //mpNetworkAssetLibrary = emg.ManagementPacks.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version()); //relNetworkAdapterHasChildNetworkAdapter = emg.EntityTypes.GetRelationshipClass("SMCenter.NetworkAdapterHasChildNetworkAdapter", mpNetworkAssetLibrary); TreeViewItem TVI = new TreeViewItem(); if (NetworkAdapter_Guid != Guid.Empty) { TVI = CreateChildTree(NetworkAdapter_Guid); } return(TVI); }
public static ManagementPackRelationship GetManagementPackRelationshipByName(string strRelationshipName, string strManagementPackName, EnterpriseManagementGroup emg) { ManagementPackRelationship mprToReturn = null; ManagementPackRelationshipCriteria mprc = new ManagementPackRelationshipCriteria(String.Format("Name = '{0}'", strRelationshipName)); foreach (ManagementPackRelationship mpr in emg.EntityTypes.GetRelationshipClasses(mprc)) { if (mpr.GetManagementPack().Name == strManagementPackName) { mprToReturn = mpr; } } return(mprToReturn); }
//private EnterpriseManagementObject NetworkMap { get; set; } //private EnterpriseManagementObject LinkedLocation { get; set; } public SearchNetworkMap(EnterpriseManagementGroup _emg, ManagementPackRelationship _relConfigItemRefLocation, ManagementPackRelationship _relNetworkMapRefLocation, ManagementPackRelationship _relLoctoLoc, ManagementPackRelationship _relConfigItemRefRack) { try { emg = _emg; relNetworkMapRefLocation = _relNetworkMapRefLocation; relLoctoLoc = _relLoctoLoc; relConfigItemRefLocation = _relConfigItemRefLocation; relConfigItemRefRack = _relConfigItemRefRack; } catch (Exception ex) { System.Windows.MessageBox.Show("SearchNetworkMap class constructor error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error); } }
//Add action log relationship to passed emo private bool AddActionLogEntry( EnterpriseManagementGroup emg, EnterpriseManagementObject emoIncident, string strTitle, string strDescription ) { try { //Get the System.WorkItem.Library mp ManagementPack mpWorkItemLibrary = emg.ManagementPacks.GetManagementPack(new Guid("405D5590-B45F-1C97-024F-24338290453E")); //Get the actionlog class ManagementPackClass typeActionLog = emg.EntityTypes.GetClass("System.WorkItem.TroubleTicket.ActionLog", mpWorkItemLibrary); //Create a new action log entry CreatableEnterpriseManagementObject objectActionLog = new CreatableEnterpriseManagementObject(emg, typeActionLog); //Setup the action log entry objectActionLog[typeActionLog, "Id"].Value = Guid.NewGuid().ToString(); objectActionLog[typeActionLog, "Description"].Value = strDescription + "\n"; objectActionLog[typeActionLog, "Title"].Value = strTitle; objectActionLog[typeActionLog, "EnteredBy"].Value = UserPrincipal.Current.DisplayName; objectActionLog[typeActionLog, "EnteredDate"].Value = DateTime.Now.ToUniversalTime(); //Get the enumeration and relationship for the actionlog entry ManagementPackEnumeration enumActionLog = mpWorkItemLibrary.GetEnumerations().GetItem("System.WorkItem.ActionLogEnum.TaskExecuted"); objectActionLog[typeActionLog, "ActionType"].Value = enumActionLog; ManagementPackRelationship relActionLog = emg.EntityTypes.GetRelationshipClass("System.WorkItem.TroubleTicketHasActionLog", mpWorkItemLibrary); //Get the projection for the incident from the emo EnterpriseManagementObjectProjection emopIncident = new EnterpriseManagementObjectProjection(emoIncident); //Add relationship and save emopIncident.Add(objectActionLog, relActionLog.Target); emopIncident.Commit(); return(true); } catch { return(false); } }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { string userName = (System.Security.Principal.WindowsIdentity.GetCurrent().Name).Replace("\\", "_"); //string strlog = @"c:\Temp\SMCLog_" + userName + ".txt"; //Debug.WriteLine(strlog); //TextWriterTraceListener TL = new TextWriterTraceListener(strlog); //Trace.Listeners.Add(TL); //Trace.AutoFlush = true; GetSession(); ManagementPack mp = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version()); locationClass = emg.EntityTypes.GetClass("SMCenter.Location", mp); relationClass = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mp); //FillTreeView.Now(emg, locationClass, relationClass, LocationTreeView); Fill(); }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { try { GetSession(); mpCore = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version()); mpNA = emg.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version()); mpNetworkManagementLibrary = emg.GetManagementPack("System.NetworkManagement.Library", "31bf3856ad364e35", new Version()); classLocation = emg.EntityTypes.GetClass("SMCenter.Location", mpCore); classRack = emg.EntityTypes.GetClass("SMCenter.Rack", mpNA); classPatchPanel = emg.EntityTypes.GetClass("SMCenter.PatchPanel", mpNA); //classPPPort = emg.EntityTypes.GetClass("SMCenter.PatchPanelPort", mpNA); classNAPort = emg.EntityTypes.GetClass("System.NetworkManagement.NetworkAdapter", mpNetworkManagementLibrary); //classNetworkMap = emg.EntityTypes.GetClass("SMCenter.NetworkMap", mpNA); relLoctoLoc = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mpCore); relConfigItemRefRack = emg.EntityTypes.GetRelationshipClass("SMCenter.ConfigItemRefRack", mpNA); relNodetoPort = emg.EntityTypes.GetRelationshipClass("System.NetworkManagement.NodeComposedOfNetworkAdapter", mpNetworkManagementLibrary); //Fill Templates //this.TemplateLocationItem.emg = emg; //this.TemplateLocationItem.PathString = "LinkedLocation"; //this.TemplateLocationItem.mpClass = classLocation; //this.TemplateLocationItem.mpRelationshipClass = relLoctoLoc; //this.TemplateLocationItem.criteria = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", classLocation); this.TemplateRackItem.PathString = "Rack"; this.TemplateRackItem.mpClass = classRack; //////Handlers this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted)); this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit)); } catch (Exception ex) { System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message); } }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { try { GetSession(); ManagementPack mp = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version()); ManagementPack mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version()); organizationClass = emg.EntityTypes.GetClass("SMCenter.Organization", mp); UserClass = emg.EntityTypes.GetClass("System.Domain.User", mpSystem); relationClass = emg.EntityTypes.GetRelationshipClass("SMCenter.OrganizationContainsChildOrganization", mp); userrelationClass = emg.EntityTypes.GetRelationshipClass("SMCenter.UserHasOrganization", mp); FillTreeView.Now(emg, organizationClass, relationClass, OrganizationTreeView); this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted)); } catch (Exception ex) { System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message); } }
static void Main(string[] Args) { EnterpriseManagementGroup Emg = new EnterpriseManagementGroup("MIMSCSM"); Guid g = new Guid(“2D7968F72AE76CE2627354D110A35A8A”); ManagementPack mpSystem = Emg.ManagementPacks.GetManagementPack(SystemManagementPack.System); ManagementPackRelationship relContainment = mpSystem.GetRelationship(“System.Containment”); TraversalDepth tdRecursive = TraversalDepth.Recursive; IList <EnterpriseManagementObject> listContainedObjects = Emg.EntityObjects.GetRelatedObjects <EnterpriseManagementObject>(guidObjectID, relContainment, tdRecursive, ObjectQueryOptions.Default); foreach (EnterpriseManagementObject emo in listContainedObjects) { Console.WriteLine(emo.DisplayName); } }
public static TreeViewItem Create(Guid NetworkAdapter_Guid, EnterpriseManagementGroup _emg) { try { emg = _emg; mpNetworkAssetLibrary = emg.ManagementPacks.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version()); relNetworkAdapterHasChildNetworkAdapter = emg.EntityTypes.GetRelationshipClass("SMCenter.NetworkAdapterHasChildNetworkAdapter", mpNetworkAssetLibrary); TreeViewItem TVI = new TreeViewItem(); if (NetworkAdapter_Guid != Guid.Empty) { TVI = CreateTree(NetworkAdapter_Guid); } else { System.Windows.MessageBox.Show("Id Network Adapter is Empty"); } return(TVI); } catch (Exception ex) { System.Windows.MessageBox.Show("CabelTree Create procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { try { GetSession(); mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version()); mpCore = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version()); mpNA = emg.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version()); mpSoft = emg.GetManagementPack("SMCenter.SoftwareAssetManagement.Library", "75b45bd6835084b1", new Version()); classCompany = emg.EntityTypes.GetClass("SMCenter.Company", mpCore); classVersion = emg.EntityTypes.GetClass("SMCenter.SoftwareVersion", mpSoft); relPublisherHasSoftwareTitle = emg.EntityTypes.GetRelationshipClass("SMCenter.PublisherHasSoftwareTitle", mpSoft); //SMCenter.PublisherHasSoftwareTitle relSoftwareTitleHasSoftwareVersion = emg.EntityTypes.GetRelationshipClass("SMCenter.SoftwareTitleHasSoftwareVersion", mpSoft);; //SMCenter.SoftwareTitleHasSoftwareVersion //Fill Templates //this.TemplatePublisher.eemg = emg; this.TemplatePublisher.PathString = "Publisher"; this.TemplatePublisher.mpClass = classCompany; //this.TemplatePublisher.mpRelationshipClass = relLoctoLoc; //this.TemplateLocationItem.criteria = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", classLocation); //////Handlers this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted)); this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit)); FillListViewCI(); } catch (Exception ex) { System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message); } }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { try { string userName = (System.Security.Principal.WindowsIdentity.GetCurrent().Name).Replace("\\", "_"); //string strlog = @"c:\Temp\SMCLog_" + userName + ".txt"; //TextWriterTraceListener TL = new TextWriterTraceListener(strlog); //Trace.Listeners.Add(TL); //Trace.AutoFlush = true; GetSession(); ManagementPack mpCore = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version()); ManagementPack mpHA = emg.GetManagementPack("SMCenter.HardwareAssetManagement.Library", "75b45bd6835084b1", new Version()); ManagementPack mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version()); HAClass = emg.EntityTypes.GetClass("SMCenter.HardwareAsset", mpHA); ConfItemClass = emg.EntityTypes.GetClass("System.ConfigItem", mpSystem); LocationClass = emg.EntityTypes.GetClass("SMCenter.Location", mpCore); CatalogItemClass = emg.EntityTypes.GetClass("SMCenter.HardwareCatalogItem", mpHA); relationHAtoCIClass = emg.EntityTypes.GetRelationshipClass("SMCenter.HardwareAssetReferencesConfigItem", mpHA); relationLocationClass = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mpCore); //Fill Templates this.TemplateCatalogItem.PathString = "CatalogItem"; this.TemplateCatalogItem.mpClass = CatalogItemClass; ManagementPackClass WarrantyClass = emg.EntityTypes.GetClass("SMCenter.WarrantyContract", mpCore); this.TemplateWarranty.PathString = "Warranty"; this.TemplateWarranty.mpClass = WarrantyClass; ManagementPackClass SupportContractClass = emg.EntityTypes.GetClass("SMCenter.SupportContract", mpCore); this.TemplateSupportContract.PathString = "SupportContract"; this.TemplateSupportContract.mpClass = SupportContractClass; ManagementPackClass OrganizationClass = emg.EntityTypes.GetClass("SMCenter.Organization", mpCore); this.TemplateOrganization.PathString = "Organization"; this.TemplateOrganization.mpClass = OrganizationClass; this.TemplateLocationItem.emg = emg; this.TemplateLocationItem.PathString = "Location"; this.TemplateLocationItem.mpClass = LocationClass; this.TemplateLocationItem.mpRelationshipClass = relationLocationClass; this.TemplateLocationItem.criteria = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", LocationClass); ManagementPackClass CostCenterClass = emg.EntityTypes.GetClass("SMCenter.CostCenter", mpCore); this.TemplateCostCenter.PathString = "CostCenter"; this.TemplateCostCenter.mpClass = CostCenterClass; ManagementPackClass LeaseClass = emg.EntityTypes.GetClass("SMCenter.LeaseContract", mpCore); this.TemplateLease.PathString = "Lease"; this.TemplateLease.mpClass = LeaseClass; ManagementPackClass SupplierClass = emg.EntityTypes.GetClass("SMCenter.Company", mpCore); this.TemplateSupplier.PathString = "Supplier"; this.TemplateSupplier.mpClass = SupplierClass; //Handlers this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted)); this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit)); //this.AddHandler(FormEvents.SubmittedEvent, new EventHandler<PreviewFormCommandEventArgs>(this.OnSubmitted)); } catch (Exception ex) { Trace.WriteLine(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message); } }
private List<ConnectedObject> GetRelatedObjects(Guid objectId, ManagementPackRelationship rel) { var l = new List<ConnectedObject>(); var items = _emg.EntityObjects.GetRelatedObjects<EnterpriseManagementObject>(objectId, AffectedItemRelationship, TraversalDepth.OneLevel, ObjectQueryOptions.Default); foreach (var item in items) { var obj = new ConnectedObject(); obj.Add("_Id", item.Id); var classes = item.GetMostDerivedClasses(); var c = classes.Where(x => !x.Extension).FirstOrDefault(); if (c == null) { c = classes.FirstOrDefault(); while (c.Extension) { c = (ManagementPackClass)c.GetBaseType(); } } obj.Add("_Type", c.Name); obj.Add("_BaseType", item.GetLeastDerivedNonAbstractClass().Name); foreach (var prop in item.GetProperties()) { var name = prop.Name; if (obj.ContainsKey(name)) name = name + "_" + prop.Id; var val = item[prop].Value; if (val != null) { if (prop.Type == ManagementPackEntityPropertyTypes.@enum) val = val.ToString(); obj.Add(name, val); } } l.Add(obj); } return l; }
public static EnterpriseManagementRelationshipObject <EnterpriseManagementObject> GetSingleRelationship(EnterpriseManagementGroup emg, ManagementPackRelationship classRelationship, Guid Id, bool IdObjectIsSource) { try { EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relObject = null; if (IdObjectIsSource) { var items = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default); foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items) { relObject = rel; } } else { var items = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default); foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items) { relObject = rel; } } return(relObject); } catch (Exception ex) { System.Windows.MessageBox.Show("_Rel procedure error : " + ex.Message, "Service Manager"); return(null); } }
public ScomClassInstanceEditor(ManagementGroup managementGroup, Guid seedClassId, Guid actionPointClassId, MonitoringConnector monitoringConnector = null, ManagementPackRelationship hostingRelationship = null) : this(managementGroup, managementGroup.EntityTypes.GetClass(seedClassId), managementGroup.EntityTypes.GetClass(actionPointClassId), monitoringConnector, hostingRelationship) { }
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; } } }
//execute the Workflow to Notify the Assigned User protected override ActivityExecutionStatus Execute(ActivityExecutionContext TTUExecutionContext) { //since workflows only run on the workflow server, we can safely //connect and execute against the localhost EnterpriseManagementGroup emg = new EnterpriseManagementGroup("localhost"); //Get the classes we need to work with /* * get-scsmclass -name "System.WorkItem.TroubleTicket.AnalystCommentLog" | select name, id * get-scsmclass -name "System.WorkItem.TroubleTicket.UserCommentLog" | select name, id * get-scsmrelationshipclass -name "System.WorkItem.TroubleTicketHasAnalystComment" | select name, id * https://github.com/SMLets/SMLets/blob/55f1bac3bc7a7011a461b24f6d7787ba89fe2624/SMLets.Shared/Code/EntityTypes.cs#L120 * https://github.com/SMLets/SMLets/blob/55f1bac3bc7a7011a461b24f6d7787ba89fe2624/SMLets.Shared/Code/EntityTypes.cs#L161 */ ManagementPackClass UserCommentClass = emg.EntityTypes.GetClass(new Guid("a3d4e16f-5e8a-18ba-9198-d9815194c986")); ManagementPackClass UserClass = emg.EntityTypes.GetClass(new Guid("943d298f-d79a-7a29-a335-8833e582d252")); ManagementPackClass LocalizationClass = emg.EntityTypes.GetClass(new Guid("efa8bbd3-3fa4-2f37-d0d5-7a6bf53be7c8")); ManagementPackRelationship TroubleTicketHasUserCommentRelClass = emg.EntityTypes.GetRelationshipClass(new Guid("ce423786-16dd-da9c-fb7b-21ab5189e12b")); ManagementPackRelationship AssignedUserRelClass = emg.EntityTypes.GetRelationshipClass(new Guid("15e577a3-6bf9-6713-4eac-ba5a5b7c4722")); ManagementPackRelationship UserHasPreferenceRelClass = emg.EntityTypes.GetRelationshipClass(new Guid("649e37ab-bf89-8617-94f6-d4d041a05171")); //Get the Template GUID from the Translate MP EnterpriseManagementObject emoAdminSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("49a053e7-6080-e211-fd79-ca3607eecce7"), ObjectQueryOptions.Default); string templateID = emoAdminSetting[null, "TroubleTicketUserCommentTemplate"].Value.ToString(); bool isAzureTranslateEnabled; try { isAzureTranslateEnabled = Boolean.Parse(emoAdminSetting[null, "EnableAzureTranslate"].ToString()); } catch { isAzureTranslateEnabled = false; } //get the objects we'll need to work with starting with... //Comment object, the string/guid is an incoming parameter from the management pack //$commentObject = Get-SCSMObject -id "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" Guid CommentGuid = new Guid(this.InstanceIds[0].ToString()); EnterpriseManagementObject CommentObject = emg.EntityObjects.GetObject <EnterpriseManagementObject>(CommentGuid, ObjectQueryOptions.Default); //Comment and Work Item relationship object //Using SMLets' Get-SCSMRelationshipObject -ByTarget parameter: https://github.com/SMLets/SMLets/blob/55f1bac3bc7a7011a461b24f6d7787ba89fe2624/SMLets.Shared/Code/EntityObjects.cs#L1853 //$WorkItemActionLogRelObject = Get-SCSMRelationshipObject -ByTarget $commentObject | ?{$_.relationshipid -eq "835a64cd-7d41-10eb-e5e4-365ea2efc2ea"} IList <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > CommentWorkItemRelObjects = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(CommentObject.Id, ObjectQueryOptions.Default); EnterpriseManagementRelationshipObject <EnterpriseManagementObject> WorkItemActionLogRelObject = null; foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relObject in CommentWorkItemRelObjects) { //if the relationship object has an ID that is the TroubleTicketHasUserCommentRelClass, then update the variable above with it if (relObject.RelationshipId.ToString() == TroubleTicketHasUserCommentRelClass.Id.ToString()) { //we now have the relationship object that contains the Comment and the Work Item WorkItemActionLogRelObject = relObject; break; } } //if the WorkItemActionLogRelObject is empty, we have a Service Request //end this workflow and let the other carry out if (WorkItemActionLogRelObject == null) { return(base.Execute(TTUExecutionContext)); } //Work Item object //Get-SCSMObject -id $WorkItemActionLogRelObject.SourceObject.Id EnterpriseManagementObject WorkItem = emg.EntityObjects.GetObject <EnterpriseManagementObject>(WorkItemActionLogRelObject.SourceObject.Id, ObjectQueryOptions.Default); //Assigned User relationship object IList <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > WorkItemRelUsers = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(WorkItem.Id, TraversalDepth.Recursive, ObjectQueryOptions.Default); EnterpriseManagementObject AssignedUser = null; foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relObject in WorkItemRelUsers) { //if the relationship object has an ID that is the Assigned User and it isn't an old (isDeleted) user, then update the variable above with it if ((relObject.RelationshipId == AssignedUserRelClass.Id) && (relObject.IsDeleted == false)) { //we now have the relationship object that contains the Assigned User AssignedUser = relObject.TargetObject; break; } } //if the Assigned User exists, try and retrieve their Locale if (AssignedUser != null) { //Try to retrieve the Assigned User's Locale //Affected User's Preference relationship objects //https://github.com/SMLets/SMLets/blob/55f1bac3bc7a7011a461b24f6d7787ba89fe2624/SMLets.Shared/Code/EntityObjects.cs#L2775 //Get-SCSMRelatedObject -SMObject AffectedUser EnterpriseManagementObject AssignedUserLocale = null; //get the Assigned User's locale IList <EnterpriseManagementObject> AssignedUserPreferences = emg.EntityObjects.GetRelatedObjects <EnterpriseManagementObject>(AssignedUser.Id, TraversalDepth.OneLevel, ObjectQueryOptions.Default); foreach (EnterpriseManagementObject preference in AssignedUserPreferences) { if (preference.GetClasses()[0].Name == "System.UserPreference.Localization") { AssignedUserLocale = preference; break; } } //check if the Assigned User has a defined Locale, if they do and Azure Translate is enabled we can go ahead with a comparison. if ((AssignedUserLocale != null) && (isAzureTranslateEnabled)) { //get the Assigned User's locale string AssignedUserLocaleCode = AssignedUserLocale[(ManagementPackType)LocalizationClass, "LocaleID"].Value.ToString(); //get the Assigned User's language code //PowerShell equivalent: //[System.Globalization.Cultureinfo]::GetCultureInfo(LocaleCode).TwoLetterISOLanguageName string AssignedUserLangCode = System.Globalization.CultureInfo.GetCultureInfo(int.Parse(AssignedUserLocaleCode)).TwoLetterISOLanguageName.ToString().ToLower(); //now we need determine the language of the comment that was left //first, grab the Comment object and it's actual comment that was left //second, grab the person who entered the comment string CommentText = CommentObject[(ManagementPackType)UserCommentClass, "Comment"].Value.ToString(); string EnteredBy = CommentObject[(ManagementPackType)UserCommentClass, "EnteredBy"].Value.ToString(); int CommentFirstSentencePeriod = CommentText.IndexOf("."); //use a period to try to find the end of the first sentence to save on Azure spend //second, make the call to the Azure Translate class in this project to Detect the language code of the comment AzureCognitiveServicesTranslate languageManipulation = new AzureCognitiveServicesTranslate(); string CommentLangCode = null; string CommentLangDetectSample = null; int CommentLangDetectSamplePeriodIndex = CommentText.IndexOf("."); try { CommentLangDetectSample = CommentText.Substring(0, CommentLangDetectSamplePeriodIndex); } catch { CommentLangDetectSample = CommentText; } if (CommentLangDetectSample.Length > 1) { CommentLangCode = languageManipulation.LanguageDetect(emg, CommentLangDetectSample); } else { CommentLangCode = languageManipulation.LanguageDetect(emg, CommentText); } //if the detected Comment Language is different than that of the Assigned User then... //translate, leave the translated comment on the Action Log, notify on the new translated entry //this if statement would compare as seen below: //if ("en" != "es") if (CommentLangCode != AssignedUserLangCode) { //different languages //translate with Azure string translatedComment = languageManipulation.LanguageTranslate(emg, CommentLangCode, AssignedUserLangCode, CommentText); //create a New translated User Comment via projection/function from Rob Ford on TechNet //https://social.technet.microsoft.com/Forums/WINDOWS/en-US/1f06e71c-00f4-4cf7-9f7e-a9a78b4b907c/creating-action-log-entry-for-incident-via-sdk-in-c?forum=customization AddActionLogEntry newComment = new AddActionLogEntry(); string newCommentGuid = newComment.AddToActionLog(emg, WorkItem, translatedComment, EnteredBy, "UserCommentLog"); //notify on the new comment using the recently created comment's guid instead of the one that came in from the workflow parameter NotifyUser notification = new NotifyUser(); notification.SendNotification(this.SubscriptionId, this.DataItems, newCommentGuid, new String[] { templateID }, new String[] { AssignedUser.Id.ToString() }, TTUExecutionContext); } else { //same language //notify on the original comment NotifyUser notification = new NotifyUser(); notification.SendNotification(this.SubscriptionId, this.DataItems, this.InstanceIds[0].ToString(), new String[] { templateID }, new String[] { AssignedUser.Id.ToString() }, TTUExecutionContext); } } else { //the Affected user doesn't have a locale or Azure Translate isn't enabled, just notify them //notify the User NotifyUser notification = new NotifyUser(); notification.SendNotification(this.SubscriptionId, this.DataItems, this.InstanceIds[0].ToString(), new String[] { templateID }, new String[] { AssignedUser.Id.ToString() }, TTUExecutionContext); } } else { //the assigned user doesn't exist, so there isn't anyone to notify } return(base.Execute(TTUExecutionContext)); }