/// <summary> /// 根据eSight删除Server以及父级的Computer /// </summary> /// <param name="mpClass"> /// The class. /// </param> /// <param name="eSightIp"> /// The eSightIp. /// </param> public void RemoverServers(ManagementPackClass mpClass, string eSightIp) { try { MGroup.Instance.CheckConnection(); var criteria = new MonitoringObjectCriteria($"eSight = '{eSightIp}'", mpClass); var reader = MGroup.Instance.EntityObjects.GetObjectReader <PartialMonitoringObject>( criteria, ObjectQueryOptions.Default); var dns = reader.ToList().Select(x => x.Path).ToList(); var discovery = new IncrementalDiscoveryData(); dns.ForEach( dn => { var existingObject = this.GetComputerByDn(dn); if (existingObject != null) { discovery.Remove(existingObject); } }); discovery.Commit(this.MontioringConnector); } catch (Exception ex) { HWLogger.SERVICE.Error("RemoverServers", ex); } }
/// <summary> /// 删除Server以及父级的Computer /// </summary> /// <param name="mpClass">The class.</param> public void RemoverServers(ManagementPackClass mpClass) { try { MGroup.Instance.CheckConnection(); var blades = MGroup.Instance.EntityObjects.GetObjectReader <PartialMonitoringObject>( mpClass, ObjectQueryOptions.Default); var deviceIds = blades.ToList().Select(x => x.Path).ToList(); var discovery = new IncrementalDiscoveryData(); deviceIds.ForEach( deviceId => { var existingObject = this.GetComputerByDeviceId(deviceId); if (existingObject != null) { discovery.Remove(existingObject); } }); discovery.Commit(this.MontioringConnector); } catch (Exception ex) { HWLogger.SERVICE.Error("RemoverServers", ex); throw; } }
private void NewTestDialog_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.None && DialogResult == DialogResult.OK) { try { IncrementalDiscoveryData incrementalDiscovery = new IncrementalDiscoveryData(); incrementalDiscovery.Add(CreatableObjectAdapter.BaseObject); EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector(); if (ExistingObject == null) { incrementalDiscovery.Commit(connector); // new } else { incrementalDiscovery.Overwrite(connector); // update } } catch (Exception ex) { MessageBox.Show($"Failed to create new test object.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); e.Cancel = true; return; } } }
/// <summary> /// Deletes the specified appliance. /// </summary> /// <param name="appliance">The appliance.</param> /// <returns>Task<Result>.</returns> public async Task <Result> Delete(FdAppliance appliance) { return(await Task.Run(async() => { try { var obj = await this.FindByHost(appliance.HostIP); var exsitObj = obj.Data; if (exsitObj == null) { return Result.Failed(104, $"{appliance.HostIP} does not exists, delete failed."); } var client = new FdClient(appliance); var res = await client.DeleteGivenSubscriptions(appliance.SubscribeId); LogHelper.Info($"Delete Fd:DeleteGivenSubscriptions:{res.Code} {res.Message}"); var incrementalDiscoveryData = new IncrementalDiscoveryData(); incrementalDiscoveryData.Remove(exsitObj); incrementalDiscoveryData.Commit(MGroup.Instance); return Result.Done(); } catch (Exception e) { return Result.Failed(100, $"Internal error caused by {e.Message}", e); } })); }
/// <summary> /// Deletes the kun lun on synchronize. /// </summary> /// <param name="fdIp">The e sight ip.</param> /// <param name="newIds">The new device ids.</param> public void CompareDataOnSync(string fdIp, List <string> newIds) { try { MGroup.Instance.CheckConnection(); HWLogger.GetFdSdkLogger(fdIp).Info($"Check And Removed Enclosure On Polling.[curQueryResult:{string.Join(",", newIds)}]"); var criteria = new MonitoringObjectCriteria($"Name like '%{fdIp}%'", EnclosureClass); var exsitObjects = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(criteria, ObjectQueryOptions.Default).ToList(); var deleteObjects = exsitObjects.Where(x => newIds.All(newDeviceId => newDeviceId != x[EnclosureKey].Value.ToString())).ToList(); var newObjects = newIds.Where(x => exsitObjects.All(y => x != y[EnclosureKey].Value.ToString())).ToList(); HWLogger.GetFdSdkLogger(fdIp).Info($"Compare Enclosures Result:[new:{newObjects.Count}] [Delete:{deleteObjects.Count}]"); var discovery = new IncrementalDiscoveryData(); deleteObjects.ForEach(deleteDevice => { discovery.Remove(deleteDevice); }); discovery.Commit(this.MontioringConnector); HWLogger.GetFdSdkLogger(fdIp).Debug($"Remove Enclosure On Polling:[Count:{deleteObjects.Count}].[{string.Join(",", deleteObjects.Select(x => x[EnclosureKey].Value.ToString()))}]"); } catch (Exception e) { HWLogger.GetFdSdkLogger(fdIp).Error(e, $"Compare Enclosures Data On Sync."); } }
/// <summary> /// Deletes the servers on synchronize. /// </summary> /// <param name="eSightIp">The e sight ip.</param> /// <param name="newDeviceIds">The new device ids.</param> /// <param name="mpClass">The mp class.</param> public void RemoveServersOnSync(string eSightIp, List <string> newDeviceIds, ManagementPackClass mpClass) { try { HWLogger.GetESightSdkLogger(eSightIp).Info($"Check Removed Servers On Polling.[mpClass:{mpClass}][curQueryResult:{string.Join(",", newDeviceIds)}]"); MGroup.Instance.CheckConnection(); var criteria = new MonitoringObjectCriteria($"eSight = '{eSightIp}'", mpClass); var exsitDevices = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(criteria, ObjectQueryOptions.Default).ToList(); var deleteDevices = exsitDevices.Where(x => newDeviceIds.All(newDeviceId => newDeviceId != x[this.HuaweiServerKey].Value.ToString())) .ToList(); var discovery = new IncrementalDiscoveryData(); deleteDevices.ForEach(deleteDevice => { discovery.Remove(deleteDevice); }); discovery.Commit(this.MontioringConnector); if (deleteDevices.Any()) { HWLogger.GetESightSdkLogger(eSightIp).Info($"RemoveServers OnSync:delete servers[{mpClass.Name}]:{string.Join(",", deleteDevices.Select(x => x[this.HuaweiServerKey].Value.ToString()).Distinct())} "); } } catch (Exception e) { HWLogger.GetESightSdkLogger(eSightIp).Error($"RemoveServers OnSync.", e); } }
private void brd_Loc_DeleteLink_MouseDown(object sender, MouseButtonEventArgs e) { try { if (System.Windows.MessageBoxResult.OK == MessageBox.Show("Delete RelationShip?", "Warning!", MessageBoxButton.OKCancel, MessageBoxImage.Warning)) { TreeViewItem TR = (TreeViewItem)LocationTreeView.SelectedItem; // Get an object by GUID Guid G = new Guid(TR.Tag.ToString()); //EnterpriseManagementObject treeviewEMO = emg.EntityObjects.GetObject<EnterpriseManagementObject>(G, ObjectQueryOptions.Default); IncrementalDiscoveryData instance = new IncrementalDiscoveryData(); foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> obj in emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(G, relationClass, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default)) { Trace.WriteLine(DateTime.Now + " : " + "Remove Relationship " + obj.TargetObject.DisplayName); instance.Remove(obj); instance.Commit(emg); } } } catch (Exception exc) { Trace.WriteLine(DateTime.Now + " : " + "Error in Remove Relationship void " + exc.Message); } //FillTreeView.Now(emg, locationClass, relationClass, LocationTreeView); Fill(); }
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); } }
public async Task <Result> Add(ESightAppliance appliance) { return(await Task.Run(() => { try { if (OM12Connection.Exsits(ESightAppliance.EntityClassName, $"Host='{appliance.Host}'")) { return Result.Failed(101, $"ESight {appliance.Host} already exsits."); } IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData(); // add appliance record ManagementPackClass MPClass = GetMPClass(); CreatableEnterpriseManagementObject EMOAppliance = new CreatableEnterpriseManagementObject(OM12Connection.HuaweiESightMG, MPClass); IDictionary <string, ManagementPackProperty> props = OM12Connection.GetManagementPackProperties(EMOAppliance); EMOAppliance[props["Host"]].Value = appliance.Host; EMOAppliance[props["Port"]].Value = appliance.Port; EMOAppliance[props["AliasName"]].Value = appliance.AliasName; EMOAppliance[props["SystemId"]].Value = appliance.SystemId; EMOAppliance[props["LoginAccount"]].Value = appliance.LoginAccount; EMOAppliance[props["LoginPassword"]].Value = RijndaelManagedCrypto.Instance .EncryptForCS(appliance.LoginPassword); EMOAppliance[props["LastModifiedOn"]].Value = DateTime.UtcNow; EMOAppliance[props["CreatedOn"]].Value = DateTime.UtcNow; EMOAppliance[props["OpenID"]].Value = Guid.NewGuid().ToString("D"); EMOAppliance[props["SubscribeID"]].Value = Guid.NewGuid().ToString("D"); EMOAppliance[props["SubKeepAliveStatus"]].Value = 0; EMOAppliance[props["SubscriptionAlarmStatus"]].Value = 0; EMOAppliance[props["SubscriptionNeDeviceStatus"]].Value = 0; EMOAppliance[props["SubKeepAliveError"]].Value = string.Empty; EMOAppliance[props["SubscripeAlarmError"]].Value = string.Empty; EMOAppliance[props["SubscripeNeDeviceError"]].Value = string.Empty; //EMOAppliance[props["LatestConnectInfo"]].Value = string.Empty; //EMOAppliance[props["LatestStatus"]].Value = Constants.ESightConnectionStatus.NONE; ManagementPackClass baseEntity = OM12Connection.GetManagementPackClass("System.Entity"); EMOAppliance[baseEntity, "DisplayName"].Value = appliance.Host; incrementalDiscoveryData.Add(EMOAppliance); incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG); return Result.Done(); } catch (Exception e) { return Result.Failed(100, $"Internal error caused by {e.Message}", e); } })); }
/// <summary> /// The remove child high density server. /// </summary> /// <param name="dn"> /// The dn. /// </param> public void RemoveChildHighDensityServer(string dn) { var existingObject = this.GetChildHighdensityServer(dn); if (existingObject != null) { var discovery = new IncrementalDiscoveryData(); discovery.Remove(existingObject); discovery.Commit(this.MontioringConnector); } }
/// <summary> /// 根据dn移除Computer /// </summary> /// <param name="dn"> /// The dn. /// </param> public void RemoveComputerByDn(string dn) { MGroup.Instance.CheckConnection(); var existingObject = this.GetComputerByDn(dn); if (existingObject != null) { var discovery = new IncrementalDiscoveryData(); discovery.Remove(existingObject); discovery.Commit(this.MontioringConnector); } }
public async Task <Result> Update(ESightAppliance appliance) { return(await Task.Run(async() => { try { var obj = await this.FindByHost(appliance.Host); var exsitObj = obj.Data; if (exsitObj == null) { return Result.Failed(104, $"ESight {appliance.Host} can not find."); } IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData(); // update appliance record ManagementPackClass MPClass = GetMPClass(); EnterpriseManagementObject managementObject = obj.Data; var props = OM12Connection.GetManagementPackProperties(managementObject); managementObject[props["Port"]].Value = appliance.Port; managementObject[props["AliasName"]].Value = appliance.AliasName; string currentSystemId = managementObject[props["SystemId"]].Value as string; bool IsSystemIdChanged = currentSystemId != appliance.SystemId; if (IsSystemIdChanged) { managementObject[props["SystemId"]].Value = appliance.SystemId; managementObject[props["SubscribeID"]].Value = Guid.NewGuid().ToString("D"); managementObject[props["SubKeepAliveStatus"]].Value = 0; managementObject[props["SubscriptionAlarmStatus"]].Value = 0; managementObject[props["SubscriptionNeDeviceStatus"]].Value = 0; managementObject[props["SubKeepAliveError"]].Value = string.Empty; managementObject[props["SubscripeAlarmError"]].Value = string.Empty; managementObject[props["SubscripeNeDeviceError"]].Value = string.Empty; } if (appliance.UpdateCredential) { managementObject[props["LoginAccount"]].Value = appliance.LoginAccount; managementObject[props["LoginPassword"]].Value = RijndaelManagedCrypto.Instance .EncryptForCS(appliance.LoginPassword); } managementObject[props["LastModifiedOn"]].Value = DateTime.UtcNow; incrementalDiscoveryData.Add(managementObject); incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG); return Result.Done(); } catch (Exception e) { return Result.Failed(100, $"Internal error caused by {e.Message}", e); } })); }
private void PerformSCOMDiscovery(SCOMDiscoveryType direction, IList <T> objects) { IncrementalDiscoveryData discoveryDataIncremental = PrepareSCOMDiscoveryData(direction, objects); switch (direction) { case SCOMDiscoveryType.Insert: discoveryDataIncremental.Commit(myConnector); break; case SCOMDiscoveryType.Update: discoveryDataIncremental.Overwrite(myConnector); break; case SCOMDiscoveryType.Delete: discoveryDataIncremental.Commit(myConnector); break; } // after successful operation set all items to committed state foreach (var newObject in objects) { newObject.CommitStatus = InstanceCommitStatus.Committed; } }
private void OnDeleteTest(object sender, CommandEventArgs e) { if (DetailView is TestBrowser tb && tb.Grid.SelectedRows != null && tb.Grid.SelectedRows.Count > 0) { try { TestObjectAdapter firstDataItem = (TestObjectAdapter)tb.Grid.SelectedRows[0].DataBoundItem; bool doDelete = false; if (tb.Grid.SelectedRows.Count == 1) { doDelete = MessageBox.Show($"You're about to delete the {firstDataItem.DisplayName} destination.\r\nAre you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } else { doDelete = MessageBox.Show($"You're about to delete multiple destinations.\r\nAre you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } if (doDelete) { EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector(); IncrementalDiscoveryData incrementalDiscovery = new IncrementalDiscoveryData(); ManagementPackClass fqdnClass = ManagementGroup.EntityTypes.GetClass(IDs.FullyQualifiedDomainNameClassId); foreach (DataGridViewRow gridRow in tb.Grid.SelectedRows) { TestObjectAdapter dataItem = (TestObjectAdapter)gridRow.DataBoundItem; MonitoringObject currentObject = ManagementGroup.EntityObjects.GetObject <MonitoringObject>(dataItem.Source.Id, ObjectQueryOptions.Default); CreatableEnterpriseManagementObject oldInstance = new CreatableEnterpriseManagementObject(ManagementGroup, currentObject.GetMostDerivedClasses().First()); // host keys oldInstance[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value = currentObject[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value; oldInstance[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value = currentObject[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value; // key oldInstance[IDs.TestBaseClassProperties.TestIdPropertyId].Value = currentObject[IDs.TestBaseClassProperties.TestIdPropertyId].Value; incrementalDiscovery.Remove(oldInstance); } incrementalDiscovery.Commit(connector); } // emulate Refresh command for detail view SendRefreshCommandToDetailView(); } catch (Exception ex) { MessageBox.Show($"In {System.Reflection.MethodBase.GetCurrentMethod().Name} {ex.GetType().Name} said {ex.Message} at {ex.StackTrace}"); } } }
/// <summary> /// The insert detials. /// </summary> /// <param name="model"> /// The model. /// </param> private void InsertDetials(RackServer model) { try { HWLogger.GetESightSdkLogger(model.ESight).Debug($"Insert Rack:{model.DN}"); var discoveryData = new IncrementalDiscoveryData(); var rackServer = this.CreateRackServer(model); discoveryData.Add(rackServer); discoveryData.Commit(this.MontioringConnector); } catch (Exception e) { HWLogger.GetESightSdkLogger(model.ESight).Error($"Insert (Rack Error:{model.DN}", e); } }
private void OnDeleteDestination(object sender, CommandEventArgs e) { if (Grid.SelectedRows != null && Grid.SelectedRows.Count > 0) { try { InstanceState firstDataItem = (InstanceState)(Grid.SelectedRows[0].Cells[0].Tag as GridDataItem).DataItem; bool doDelete = false; if (Grid.SelectedRows.Count == 1) { doDelete = MessageBox.Show($"You're about to delete the {firstDataItem.DisplayName} destination.\r\nAre you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } else { doDelete = MessageBox.Show($"You're about to delete multiple destinations.\r\nAre you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } if (doDelete) { EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector(); IncrementalDiscoveryData incrementalDiscovery = new IncrementalDiscoveryData(); ManagementPackClass fqdnClass = ManagementGroup.EntityTypes.GetClass(IDs.FullyQualifiedDomainNameClassId); foreach (DataGridViewRow gridRow in Grid.SelectedRows) { InstanceState dataItem = (InstanceState)(gridRow.Cells[0].Tag as GridDataItem).DataItem; MonitoringObject currentObject = dataItem.GetMonitoringObject(ManagementGroup, ObjectQueryOptions.Default, retrieveAllProperties: true); CreatableEnterpriseManagementObject oldInstance = new CreatableEnterpriseManagementObject(ManagementGroup, fqdnClass); oldInstance[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value = currentObject[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value; oldInstance[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value = currentObject[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value; incrementalDiscovery.Remove(oldInstance); } incrementalDiscovery.Commit(connector); } // emulate Refresh command OnRefreshCommand(sender, e); } catch (Exception ex) { MessageBox.Show($"In {System.Reflection.MethodBase.GetCurrentMethod().Name} {ex.GetType().Name} said {ex.Message} at {ex.StackTrace}"); } } }
/// <summary> /// Removes all enclosure. /// </summary> public void RemoveAllEnclosure() { try { HWLogger.Service.Info($"RemoveAllEnclosure."); MGroup.Instance.CheckConnection(); var devices = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(EnclosureClass, ObjectQueryOptions.Default).ToList(); if (devices.Any()) { var discovery = new IncrementalDiscoveryData(); devices.ForEach(device => discovery.Remove(device)); discovery.Commit(this.MontioringConnector); } } catch (Exception ex) { HWLogger.Service.Error(ex, "RemoveAllEnclosure"); } }
private void brd_CI_Delete_MouseDown(object sender, MouseButtonEventArgs e) { try { EnterpriseManagementObject CISelected = (EnterpriseManagementObject)ListViewCI.SelectedItem; if (System.Windows.MessageBoxResult.OK == MessageBox.Show("Delete RelationShip?", "Warning!", MessageBoxButton.OKCancel, MessageBoxImage.Warning)) { if ((bool)CurrentDataItem["$IsNew$"]) { CIListViewСollection.Remove(CISelected); } else { if (CItoAddСollection.Contains(CISelected)) { //NotExisting Relationship - Remove only from Collections CIListViewСollection.Remove(CISelected); CItoAddСollection.Remove(CISelected); } else { //Remove existing Relationship Guid G = (Guid)CISelected.Id; IncrementalDiscoveryData instance = new IncrementalDiscoveryData(); foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> obj in emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(G, relationHAtoCIClass, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default)) { Trace.WriteLine(DateTime.Now + " : " + "Remove Relationship " + obj.TargetObject.DisplayName); instance.Remove(obj); instance.Commit(emg); this.CItoAddСollection.Remove(CISelected); } } } FillListViewCI(); } } catch (Exception exc) { Trace.WriteLine(DateTime.Now + " : " + "Error in Remove Relationship void " + exc.Message); } }
/// <summary> /// Adds the specified appliance. /// </summary> /// <param name="appliance">The appliance.</param> /// <returns>Result.</returns> public async Task <Result> Add(FdAppliance appliance) { return(await Task.Run(() => { try { if (MGroup.Instance.Exsits(this.FdApplianceClass, $"HostIP='{appliance.HostIP}'")) { return Result.Failed(101, $"FusionDirector {appliance.HostIP} already exsits."); } var incrementalDiscoveryData = new IncrementalDiscoveryData(); // add appliance record var emoAppliance = new CreatableEnterpriseManagementObject(MGroup.Instance, this.FdApplianceClass); var props = this.FdApplianceClass.PropertyCollection; emoAppliance[props["UniqueId"]].Value = FusionDirectUniqueIdPrefix + Guid.NewGuid().ToString("D"); emoAppliance[props["HostIP"]].Value = appliance.HostIP; emoAppliance[props["AliasName"]].Value = appliance.AliasName; emoAppliance[props["LoginAccount"]].Value = appliance.LoginAccount; emoAppliance[props["LoginPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.LoginPd); emoAppliance[props["Port"]].Value = appliance.Port; emoAppliance[props["EventUserName"]].Value = appliance.EventUserName; emoAppliance[props["EventPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.EventPd); emoAppliance[props["SubscribeId"]].Value = appliance.SubscribeId; emoAppliance[props["SubscribeStatus"]].Value = appliance.SubscribeStatus; emoAppliance[props["LatestSubscribeInfo"]].Value = appliance.LatestSubscribeInfo; emoAppliance[props["LastModifyTime"]].Value = appliance.LastModifyTime; emoAppliance[props["CreateTime"]].Value = appliance.CreateTime; emoAppliance[this.DisplayNameField].Value = appliance.HostIP; incrementalDiscoveryData.Add(emoAppliance); incrementalDiscoveryData.Commit(MGroup.Instance); return Result.Done(); } catch (Exception e) { return Result.Failed(100, $"Internal error caused by {e.Message}", e); } })); }
/// <summary> /// 删除Server /// </summary> /// <param name="mpClass">The class.</param> public void RemoverServers(ManagementPackClass mpClass) { try { HWLogger.Service.Info($"RemoverServers by MpClass.[{mpClass}]"); MGroup.Instance.CheckConnection(); var devices = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(mpClass, ObjectQueryOptions.Default).ToList(); if (devices.Any()) { var discovery = new IncrementalDiscoveryData(); devices.ForEach(device => discovery.Remove(device)); discovery.Commit(this.MontioringConnector); } } catch (Exception ex) { HWLogger.Service.Error("RemoverServers", ex); throw; } }
/// <summary> /// Removes the server from m group. /// </summary> /// <param name="fdIp">The fd ip.</param> public void RemoveEnclosureByFd(string fdIp) { try { HWLogger.GetFdSdkLogger(fdIp).Info($"RemoveEnclosureByFd.[{fdIp}]"); MGroup.Instance.CheckConnection(); var criteria = new MonitoringObjectCriteria($"Name like '%{fdIp}%'", EnclosureClass); var devices = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(criteria, ObjectQueryOptions.Default).ToList(); if (devices.Any()) { var discovery = new IncrementalDiscoveryData(); devices.ForEach(device => discovery.Remove(device)); discovery.Commit(this.MontioringConnector); } } catch (Exception ex) { HWLogger.GetFdSdkLogger(fdIp).Error(ex, "RemoveEnclosureByFd"); } }
/// <summary> /// 根据eSight删除Server以及父级的Computer /// </summary> /// <param name="mpClass">The class.</param> /// <param name="eSightIp">The eSightIp.</param> public void RemoverServersByESight(ManagementPackClass mpClass, string eSightIp) { try { HWLogger.GetESightSdkLogger(eSightIp).Info($"RemoverServersByESight.[{eSightIp}]"); MGroup.Instance.CheckConnection(); var criteria = new MonitoringObjectCriteria($"eSight = '{eSightIp}'", mpClass); var devices = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(criteria, ObjectQueryOptions.Default).ToList(); if (devices.Any()) { var discovery = new IncrementalDiscoveryData(); devices.ForEach(device => discovery.Remove(device)); discovery.Commit(this.MontioringConnector); } } catch (Exception ex) { HWLogger.GetESightSdkLogger(eSightIp).Error("RemoverServersByESight", ex); } }
/// <summary> /// Removes the server by device identifier. /// </summary> /// <param name="eSightIp">The e sight ip.</param> /// <param name="deviceId">The device identifier.</param> public void RemoveServerByDeviceId(string eSightIp, string deviceId) { try { HWLogger.GetESightSdkLogger(eSightIp).Info($"RemoveServerByDeviceId.[{deviceId}]"); MGroup.Instance.CheckConnection(); var criteria = new MonitoringObjectCriteria($"DN = '{deviceId}'", HuaweiServerClass); var reader = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(criteria, ObjectQueryOptions.Default); if (reader.Any()) { var existingObject = reader.First(); var discovery = new IncrementalDiscoveryData(); discovery.Remove(existingObject); discovery.Commit(this.MontioringConnector); } } catch (Exception e) { HWLogger.GetESightSdkLogger(eSightIp).Error($"RemoveServerByDeviceId.", e); } }
/// <summary> /// Inserts the specified model. /// </summary> /// <param name="model">The model.</param> public void Insert(Enclosure model) { try { HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Insert Enclosure:{model.UnionId}"); var discoveryData = new IncrementalDiscoveryData(); #region Enclosure var enclosure = this.CreateEnclosure(model); discoveryData.Add(enclosure); #endregion discoveryData.Commit(this.MontioringConnector); HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"InsertEnclosure finish.[{model.UnionId}]"); } catch (Exception e) { HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Error(e, $"Insert Enclosure Error:{model.UnionId}"); } }
/// <summary> /// Inserts the specified model. /// </summary> /// <param name="model">The model.</param> private void Insert(Server model) { try { HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Insert Server:{model.UnionId}"); var discoveryData = new IncrementalDiscoveryData(); #region Server var server = this.CreateServer(model); discoveryData.Add(server); #endregion discoveryData.Commit(this.MontioringConnector); HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Insert Server Finish:{model.UnionId}"); } catch (Exception e) { HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Error(e, $"Insert Server Error:{model.UnionId}"); } }
private void lbOk_MouseDown(object sender, MouseButtonEventArgs e) { try { //IDataItem DI = this.TemplateSoftwareTitle.sipInstance; //Guid CurrentNodeId = (Guid)DI["$Id$"]; //EnterpriseManagementObject SoftwareTitle_EMO = emg.EntityObjects.GetObject<EnterpriseManagementObject>(CurrentNodeId, ObjectQueryOptions.Default); //MessageBox.Show(SoftwareTitle_EMO.Name); //MessageBox.Show(TemplateSoftwareTitle.mpClass.Name); if (this.txtDisplayName.Text != "" && this.txtDisplayName.Text != null) { //ManagementPackClass classTask = ManagementGroup.EntityTypes.GetClass(“Task”, testMP) CreatableEnterpriseManagementObject Version = new CreatableEnterpriseManagementObject(emg, classSoftwareVersion); //Version [classTask, “Id”].Value = Guid.NewGuid().ToString(); Version[classSoftwareVersion, "DisplayName"].Value = this.txtDisplayName.Text; CreatableEnterpriseManagementRelationshipObject relationshipObject = new CreatableEnterpriseManagementRelationshipObject(emg, relSoftwareTitleHasSoftwareVersion); relationshipObject.SetSource(EMO_SoftwareTitle); relationshipObject.SetTarget(Version); IncrementalDiscoveryData dd = new IncrementalDiscoveryData(); dd.Add(Version); //target object dd.Add(relationshipObject); //relationship object dd.Commit(emg); this.Close(); } else { MessageBox.Show("Type SoftwareVersion DisplayName!", "Warning!!!", MessageBoxButton.OK, MessageBoxImage.Warning); } } catch (Exception ex) { System.Windows.MessageBox.Show("Ok_MouseDown void error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error); this.Close(); } }
public async Task <Result> Delete(ESightAppliance appliance) { return(await Task.Run(async() => { IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData(); try { var obj = await this.FindByHost(appliance.Host); var exsitObj = obj.Data; if (exsitObj == null) { return Result.Failed(104, $"{appliance.Host} does not exists, delete failed."); } incrementalDiscoveryData.Remove(obj.Data); incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG); return Result.Done(); } catch (Exception e) { return Result.Failed(100, $"Internal error caused by {e.Message}", e); } })); }
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(); } }
protected override void ProcessRecord() { try { ManagementPackClass clsIncident = SMHelpers.GetManagementPackClass(ClassTypes.System_WorkItem_Incident, SMHelpers.GetManagementPack(ManagementPacks.System_WorkItem_Incident_Library, _mg), _mg); EnterpriseManagementObjectProjection incidentProjection = new EnterpriseManagementObjectProjection(_mg, clsIncident); WriteVerbose("Setting basic properties"); incidentProjection.Object[clsIncident, "Id"].Value = incidentPrefix; incidentProjection.Object[clsIncident, "Title"].Value = this.Title; if (CreatedDate != null) { incidentProjection.Object[clsIncident, "CreatedDate"].Value = this.CreatedDate; } SMHelpers.UpdateIncident(_mg, clsIncident, incidentProjection, this.Impact, this.Urgency, this.Status, this.Classification, this.Source, this.SupportGroup, null, null, this.Description, null); if (AffectedCIs != null) { WriteVerbose("Adding affected CIs"); foreach (var item in AffectedCIs) { WriteVerbose(string.Format("Adding {0} as affected configuration item.", item.Object.DisplayName)); SMHelpers.AddAffectedCI(incidentProjection, item.Object, _mg); } } if (AffectedUser != null) { WriteVerbose(string.Format("Adding {0} as affected configuration item.", AffectedUser)); SMHelpers.AddAffectedUser(incidentProjection, this.AffectedUser, _mg); } // a bulk operation // do in batches of toCommit (set above) if (Bulk) { toCommit++; idd.Add(incidentProjection); if (toCommit >= batchSize) { idd.Commit(_mg); idd = new IncrementalDiscoveryData(); toCommit = 0; } } else { incidentProjection.Commit(); } if (PassThru) { //Pass the new object to the pipeline WriteObject(incidentProjection); } } catch (Exception ex) { WriteError(new ErrorRecord(ex, "NewIncident", ErrorCategory.InvalidOperation, Title)); } }
/// <summary> /// The insert detials. /// </summary> /// <param name="model"> /// The model. /// </param> public void InsertDetials(KunLunServer model) { var discoveryData = new IncrementalDiscoveryData(); var baseComputer = this.GetComputerByDn(model.DN); if (baseComputer == null) { var newBaseComputer = this.CreateComputer(model.DN); discoveryData.Add(newBaseComputer); } else { discoveryData.Add(baseComputer); } #region KunLunServer var kunLunServer = this.CreateKunLunServer(model); kunLunServer[this.ComputerKey].Value = model.DN; discoveryData.Add(kunLunServer); #endregion #region Fan var fanGroup = this.CreateLogicalGroup(this.FanGroupClass, model.DN); discoveryData.Add(fanGroup); model.FanList.ForEach( x => { var fan = this.CreateFan(x); fan[this.PartGroupKey].Value = fanGroup[this.PartGroupKey].Value; fan[this.HuaweiServerKey].Value = model.DN; fan[this.ComputerKey].Value = model.DN; discoveryData.Add(fan); }); #endregion #region PSU var powerSupplyGroup = this.CreateLogicalGroup(this.PowerSupplyGroupClass, model.DN); discoveryData.Add(powerSupplyGroup); model.PowerSupplyList.ForEach( x => { var powerSupply = this.CreatePowerSupply(x); powerSupply[this.PartGroupKey].Value = powerSupplyGroup[this.PartGroupKey].Value; powerSupply[this.HuaweiServerKey].Value = model.DN; powerSupply[this.ComputerKey].Value = model.DN; discoveryData.Add(powerSupply); }); #endregion #region Raid var raidGroup = this.CreateLogicalGroup(this.RaidGroupClass, model.DN); discoveryData.Add(raidGroup); model.RaidList.ForEach( y => { var raid = this.CreateRaidControl(y); raid[this.PartGroupKey].Value = raidGroup[this.PartGroupKey].Value; raid[this.HuaweiServerKey].Value = model.DN; raid[this.ComputerKey].Value = model.DN; discoveryData.Add(raid); }); #endregion #region Disk var diskGroup = this.CreateLogicalGroup(this.PhysicalDiskGroupClass, model.DN); discoveryData.Add(diskGroup); model.DiskList.ForEach( x => { var disk = this.CreateDisk(x); disk[this.PartGroupKey].Value = diskGroup[this.PartGroupKey].Value; disk[this.HuaweiServerKey].Value = model.DN; disk[this.ComputerKey].Value = model.DN; discoveryData.Add(disk); }); #endregion if (!this.ExsitsKunLunServer(model.DN)) { discoveryData.Commit(this.MontioringConnector); } else { discoveryData.Overwrite(this.MontioringConnector); } }
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(); } }