public IHttpActionResult GetComputerPartialMonitoringObject() { ManagementPackClassCriteria classCriteria = new ManagementPackClassCriteria("Name = 'Microsoft.Windows.Computer'"); IList <ManagementPackClass> monitoringClasses = mg.EntityTypes.GetClasses(classCriteria); List <PartialMonitoringObject> windowsComputerObjects = new List <PartialMonitoringObject>(); IObjectReader <PartialMonitoringObject> reader = mg.EntityObjects.GetObjectReader <PartialMonitoringObject>(monitoringClasses[0], ObjectQueryOptions.Default); windowsComputerObjects.AddRange(reader); List <SCOMComputerModel> SCOMComputers = new List <SCOMComputerModel>(); foreach (PartialMonitoringObject windowsComputerObject in windowsComputerObjects) { SCOMComputerModel SCOMComputer = new SCOMComputerModel(); SCOMComputer.id = windowsComputerObject.Id; SCOMComputer.displayName = windowsComputerObject.DisplayName; SCOMComputer.healthState = windowsComputerObject.HealthState.ToString(); SCOMComputer.inMaintenance = windowsComputerObject.InMaintenanceMode; SCOMComputer.isAvailable = windowsComputerObject.IsAvailable; SCOMComputers.Add(SCOMComputer); } return(Json(SCOMComputers)); }
public IHttpActionResult EnableComputerMaintenance(SCOMComputerMaintenanceModel Data) { ManagementPackClassCriteria classCriteria = new ManagementPackClassCriteria("Name = 'Microsoft.Windows.Computer'"); IList <ManagementPackClass> monClasses = mg.EntityTypes.GetClasses(classCriteria); MonitoringObjectCriteria criteria = new MonitoringObjectCriteria(string.Format("Name = '{0}'", Data.DisplayName.ToString()), monClasses[0]); List <MonitoringObject> monObjects = new List <MonitoringObject>(); List <SCOMComputerMaintenanceModel> MaintenanceComputers = new List <SCOMComputerMaintenanceModel>(); //travers trough all classes to get monitoring objects foreach (ManagementPackClass monClass in monClasses) { monObjects.AddRange(mg.EntityObjects.GetObjectReader <MonitoringObject>(criteria, ObjectQueryOptions.Default)); } foreach (MonitoringObject monObject in monObjects) { if (!monObject.InMaintenanceMode) { { //set maintenance properties DateTime startTime = DateTime.UtcNow; DateTime schedEndTime = DateTime.UtcNow.AddMinutes(Data.Minutes); MaintenanceModeReason reason = MaintenanceModeReason.PlannedOther; string comment = Data.comment; monObject.ScheduleMaintenanceMode(startTime, schedEndTime, reason, comment); //Add properties to list SCOMComputerMaintenanceModel maintenanceComputer = new SCOMComputerMaintenanceModel(); maintenanceComputer.DisplayName = monObject.DisplayName; maintenanceComputer.EndTime = schedEndTime; maintenanceComputer.Minutes = Data.Minutes; maintenanceComputer.comment = comment; //add computers to list MaintenanceComputers.Add(maintenanceComputer); } } //If computer already in maintenance. Throw conflict message else { MaintenanceWindow MaintenanceWindow = monObject.GetMaintenanceWindow(); SCOMComputerMaintenanceModel maintenanceComputer = new SCOMComputerMaintenanceModel(); HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Conflict); message.Content = new StringContent("Computer already in maintenance " + MaintenanceWindow.ScheduledEndTime); throw new HttpResponseException(message); } } //Return list of computers as Json return(Json(MaintenanceComputers)); }
/// <summary> /// The get management pack class. /// </summary> /// <param name="entityClassName"> /// The class name. /// </param> /// <returns> /// The <see cref="ManagementPackClass"/>. /// </returns> /// <exception cref="ApplicationException">Failed to find management pack class </exception> public static ManagementPackClass GetManagementPackClass(string entityClassName) { ManagementPackClassCriteria criteria = new ManagementPackClassCriteria("Name='" + entityClassName + "'"); IList <ManagementPackClass> mpClasses = OM12Connection.HuaweiESightMG.EntityTypes.GetClasses(criteria); if (mpClasses.Count == 0) { throw new ApplicationException("Failed to find management pack class " + entityClassName); } return(mpClasses[0]); }
public IHttpActionResult GetLinuxComputersByName(string ComputerName) { ManagementPackClassCriteria classCriteria = new ManagementPackClassCriteria("Name = 'Microsoft.Linux.Computer'"); IList <ManagementPackClass> monitoringClasses = mg.EntityTypes.GetClasses(classCriteria); if (string.IsNullOrEmpty(ComputerName)) { throw new HttpResponseException(Request .CreateResponse(HttpStatusCode.BadRequest)); } else { MonitoringObjectCriteria criteria = new MonitoringObjectCriteria(string.Format("Name = '{0}'", ComputerName), monitoringClasses[0]); List <PartialMonitoringObject> linuxComputerObjects = new List <PartialMonitoringObject>(); IObjectReader <PartialMonitoringObject> reader = mg.EntityObjects.GetObjectReader <PartialMonitoringObject>(criteria, ObjectQueryOptions.Default); linuxComputerObjects.AddRange(reader); //Check if computers are in list if (linuxComputerObjects.Count > 0) { List <SCOMComputerModel> SCOMLinuxComputers = new List <SCOMComputerModel>(); foreach (PartialMonitoringObject linuxComputerObject in linuxComputerObjects) { SCOMComputerModel SCOMComputer = new SCOMComputerModel(); SCOMComputer.id = linuxComputerObject.Id; SCOMComputer.displayName = linuxComputerObject.DisplayName; SCOMComputer.healthState = linuxComputerObject.HealthState.ToString(); SCOMComputer.inMaintenance = linuxComputerObject.InMaintenanceMode; SCOMComputer.isAvailable = linuxComputerObject.IsAvailable; SCOMLinuxComputers.Add(SCOMComputer); } //Successful return return(Json(SCOMLinuxComputers)); } //If computer cannot be found else { HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.NotFound); message.Content = new StringContent("Cannot find Computer. Please see input"); throw new HttpResponseException(message); } } }
public static ManagementPackClass GetManagementPackClassByName(string strClassName, string strManagementPackName, EnterpriseManagementGroup emg) { ManagementPackClass mpcToReturn = null; ManagementPackClassCriteria mpcc = new ManagementPackClassCriteria(String.Format("Name = '{0}'", strClassName)); foreach (ManagementPackClass mpc in emg.EntityTypes.GetClasses(mpcc)) { if (mpc.GetManagementPack().Name == strManagementPackName) { mpcToReturn = mpc; } } return(mpcToReturn); }
public static ManagementPackClass GetClassByName(string strName, EnterpriseManagementGroup emg) { ManagementPackClassCriteria mpcc = new ManagementPackClassCriteria(String.Format("Name = '{0}'", strName)); IList <ManagementPackClass> listClasses = emg.EntityTypes.GetClasses(mpcc); if (listClasses.Count > 0) { return(listClasses[0]); } else { return(null); } }
public IHttpActionResult GetClassPartialMonitoringObject(Guid classId) { if (classId == Guid.Empty) { throw new HttpResponseException(Request .CreateResponse(HttpStatusCode.BadRequest)); } //Use the input class id to create a criteria for our query ManagementPackClassCriteria classCriteria = new ManagementPackClassCriteria(string.Format("Id = '{0}'", classId.ToString())); IList <ManagementPackClass> monitoringClasses = mg.EntityTypes.GetClasses(classCriteria); List <PartialMonitoringObject> inputClassObjects = new List <PartialMonitoringObject>(); IObjectReader <PartialMonitoringObject> reader = mg.EntityObjects.GetObjectReader <PartialMonitoringObject>(monitoringClasses[0], ObjectQueryOptions.Default); inputClassObjects.AddRange(reader); List <SCOMClassObjectModel> classObjects = new List <SCOMClassObjectModel>(); //If objects are found add them to list and return if (inputClassObjects.Count > 0) { foreach (PartialMonitoringObject classObject in inputClassObjects) { SCOMClassObjectModel inputClassObject = new SCOMClassObjectModel(); inputClassObject.id = classObject.Id; inputClassObject.displayName = classObject.DisplayName; inputClassObject.healthState = classObject.HealthState.ToString(); inputClassObject.path = classObject.Path; classObjects.Add(inputClassObject); } return(Json(classObjects)); } //if class does not have any monitoring objects return 'no content' else { HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.NoContent); message.Content = new StringContent("Class found but no object exist"); throw new HttpResponseException(message); } }
public static ManagementPackClass GetManagementPackClassByName(string strClassName, EnterpriseManagementGroup emg) { ManagementPackClassCriteria mpcc = new ManagementPackClassCriteria(String.Format("Name = '{0}'", strClassName)); IList <ManagementPackClass> mpcResults = emg.EntityTypes.GetClasses(mpcc); if (mpcResults.Count == 0) { throw new InvalidOperationException("Found zero classes with the name '" + strClassName + "'."); } if (mpcResults.Count > 1) { throw new InvalidOperationException("Found multiple classes with the name '" + strClassName + "'."); } return(mpcResults[0]); }
public static EnterpriseManagementObject GetLoggedInUserAsObject(EnterpriseManagementGroup emg) { EnterpriseManagementObject emoUserToReturn = null; string strUserName = System.Environment.UserName; string strDomain = System.Environment.UserDomainName; string strUserByUserNameAndDomainCriteria = string.Format("{0} = '{1}' AND {2} = '{3}'", Constants.strPropertyUserName, strUserName, Constants.strPropertyDomain, strDomain); ManagementPackClassCriteria mpccUser = new ManagementPackClassCriteria(String.Format("{0} = '{1}'", Constants.strMPAttributeName, Constants.strClassUser)); ManagementPackClass mpcUser = GetManagementPackClassByName(Constants.strClassUser, Constants.strManagementPackSystemLibrary, emg); EnterpriseManagementObjectCriteria emocUserByUserNameAndDomain = new EnterpriseManagementObjectCriteria(strUserByUserNameAndDomainCriteria, mpcUser); IObjectReader <EnterpriseManagementObject> emoUsers = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emocUserByUserNameAndDomain, ObjectQueryOptions.Default); foreach (EnterpriseManagementObject emoUser in emoUsers) { //There will be only one if any emoUserToReturn = emoUser; } return(emoUserToReturn); }
static void Main(string[] args) { ManagementGroup mg = new ManagementGroup("localhost"); Console.WriteLine("Creating a maintenance window..."); string query = "DisplayName = 'SQL 2005 DB Engine'"; ManagementPackClassCriteria criteria = new ManagementPackClassCriteria(query); IList <ManagementPackClass> monClasses = mg.EntityTypes.GetClasses(criteria); List <MonitoringObject> monObjects = new List <MonitoringObject>(); foreach (ManagementPackClass monClass in monClasses) { monObjects.AddRange(mg.EntityObjects.GetObjectReader <MonitoringObject>(monClass, ObjectQueryOptions.Default)); } foreach (MonitoringObject monObject in monObjects) { if (!monObject.InMaintenanceMode) { DateTime startTime = DateTime.UtcNow; DateTime schedEndTime = DateTime.UtcNow.AddHours(1); MaintenanceModeReason reason = MaintenanceModeReason.SecurityIssue; String comment = "Applying Monthly Security Patches."; monObject.ScheduleMaintenanceMode(startTime, schedEndTime, reason, comment); Console.WriteLine(monObject.DisplayName + " set in maintenance mode for an hour."); } else { MaintenanceWindow window = monObject.GetMaintenanceWindow(); DateTime schedEndTime = window.ScheduledEndTime; Console.WriteLine(monObject.DisplayName + " already in maintenance mode until " + schedEndTime.ToShortTimeString() + "."); } } }
//This is sending the Command in the button the user selected to SCOM, looking for the task protected void ButtonClick(object sender, GridViewCommandEventArgs e) { string query = ""; if (e.CommandName == "startService" || e.CommandName == "stopService" || e.CommandName == "killService" || e.CommandName == "restartService" || e.CommandName == "Cred") { query = "DisplayName = '" + System.Configuration.ConfigurationManager.AppSettings[e.CommandName] + "'"; int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = ServiceView.Rows[index]; string ServiceName = row.Cells[0].Text; ManagementGroup mg = new ManagementGroup(msserver); ManagementPackTaskCriteria taskCriteria = new ManagementPackTaskCriteria(query); IList <ManagementPackTask> tasks = mg.TaskConfiguration.GetTasks(taskCriteria); ManagementPackTask task = null; if (tasks.Count == 1) { task = tasks[0]; } else { Server.Transfer("~/ErrorPage.aspx?Error=6"); } // Get the agent class. query = "Name = 'Microsoft.Windows.Computer'"; ManagementPackClassCriteria criteria = new ManagementPackClassCriteria(query); IList <ManagementPackClass> classes = mg.EntityTypes.GetClasses(criteria); if (classes.Count != 1) { Server.Transfer("~/ErrorPage.aspx?Error=5"); } // Create a MonitoringObject list containing a specific agent (the // target of the task). if (Request.QueryString["id"] == null) { Server.Transfer("~/ErrorPage.aspx?Error=1"); } string fullAgentName = Request.QueryString["id"]; List <MonitoringObject> targets = new List <MonitoringObject>(); query = "Id = '" + fullAgentName + "'"; MonitoringObjectCriteria targetCriteria = new MonitoringObjectCriteria(query, classes[0]); targets.AddRange(mg.EntityObjects.GetObjectReader <MonitoringObject>(targetCriteria, ObjectQueryOptions.Default)); if (targets.Count != 1) { Server.Transfer("~/ErrorPage.aspx?Error=3"); } // Use the default task configuration. Microsoft.EnterpriseManagement.Runtime.TaskConfiguration config = new Microsoft.EnterpriseManagement.Runtime.TaskConfiguration(); if (userchanged) { SecureString theSecureString = new NetworkCredential("", userpassword).SecurePassword; Microsoft.EnterpriseManagement.Runtime.TaskCredentials cred = new Microsoft.EnterpriseManagement.Runtime.WindowsTaskCredentials(userdomain, username, theSecureString); config.Credentials = cred; } IList <Microsoft.EnterpriseManagement.Configuration.ManagementPackOverrideableParameter> overrideparams = task.GetOverrideableParameters(); config.Overrides.Add(new Pair <ManagementPackOverrideableParameter, string>(overrideparams[1], ServiceName)); // Run the task. IList <Microsoft.EnterpriseManagement.Runtime.TaskResult> results = mg.TaskRuntime.ExecuteTask(targets, task, config); if (results.Count == 0) { Server.Transfer("~/ErrorPage.aspx?Error=4"); } } Response.Redirect(Request.RawUrl); }
protected void Page_Load(object sender, EventArgs e) { if (userchanged) { logedinuser.Text = ". Tasks will run with the user:"******"\\" + username; } //Connect to SCOM ManagementGroup mg = new ManagementGroup(msserver); if (!(mg.IsConnected)) { Server.Transfer("~/ErrorPage.aspx?Error=6"); } string query = "DisplayName = '" + System.Configuration.ConfigurationManager.AppSettings["GetServices"] + "'"; ManagementPackTaskCriteria taskCriteria = new ManagementPackTaskCriteria(query); IList <ManagementPackTask> tasks = mg.TaskConfiguration.GetTasks(taskCriteria); ManagementPackTask task = null; if (tasks.Count == 1) { task = tasks[0]; } else { Server.Transfer("~/ErrorPage.aspx?Error=2"); } // Get the agent class. query = "Name = 'Microsoft.Windows.Computer'"; ManagementPackClassCriteria criteria = new ManagementPackClassCriteria(query); IList <ManagementPackClass> classes = mg.EntityTypes.GetClasses(criteria); if (classes.Count != 1) { Server.Transfer("~/ErrorPage.aspx?Error=5"); } // Create a MonitoringObject list containing a specific agent (the // target of the task). string fullAgentName; if (Request.QueryString["id"] == null && Request.QueryString["DisplayName"] == null) { Server.Transfer("~/ErrorPage.aspx?Error=1"); } else if (Request.QueryString["id"] != null) { fullAgentName = Request.QueryString["id"]; query = "Id = '" + fullAgentName + "'"; objectid = fullAgentName; } else if (Request.QueryString["DisplayName"] != null) { fullAgentName = Request.QueryString["DisplayName"]; query = "DisplayName = '" + fullAgentName + "'"; objectid = fullAgentName; } else { //to be developed } List <MonitoringObject> targets = new List <MonitoringObject>(); MonitoringObjectCriteria targetCriteria = new MonitoringObjectCriteria(query, classes[0]); targets.AddRange(mg.EntityObjects.GetObjectReader <MonitoringObject>(targetCriteria, ObjectQueryOptions.Default)); if (targets.Count != 1) { Server.Transfer("~/ErrorPage.aspx?Error=3"); } //Get user filter options Microsoft.EnterpriseManagement.Runtime.TaskConfiguration config = new Microsoft.EnterpriseManagement.Runtime.TaskConfiguration(); try { IList <Microsoft.EnterpriseManagement.Configuration.ManagementPackOverrideableParameter> overrideparams = task.GetOverrideableParameters(); //user Service State Filter string State = Request.QueryString["state"]; State = $"($_.startmode -match \"{State}\")"; //user Service Status filter string Status = Request.QueryString["status"]; Status = $"($_.state -match \"{Status}\")"; //user Service Name like filter string ServiceName = Request.QueryString["name"]; //user Service sorting string Sort = Request.QueryString["sort"]; string overridevalue = ""; if (ServiceName != null) { overridevalue = $"gwmi -Query \"select * from win32_service where name like '%{ServiceName}%'\" | select displayname,name,startmode,state"; } else { overridevalue = "gwmi -Query \"select * from win32_service\" | select displayname,name,startmode,state"; } if ((Request.QueryString["state"] != null) && (Request.QueryString["status"]) != null) { overridevalue += "| ?{" + State + " -and " + Status + "}"; } else if ((Request.QueryString["state"] != null)) { overridevalue += "| ?{" + State + "}"; } else if ((Request.QueryString["status"] != null)) { overridevalue += "| ?{" + Status + "}"; } else { //do nothing } if ((Request.QueryString["sort"] != null)) { string sort = Request.QueryString["sort"]; sort = sort.Replace("|", ","); overridevalue = overridevalue + "| sort " + sort; } else { overridevalue = overridevalue + "| sort-object -property @{Expression = {$_.State}; Ascending = $false},startmode ,name"; } config.Overrides.Add(new Pair <ManagementPackOverrideableParameter, string>(overrideparams[1], overridevalue)); } catch { Server.Transfer("~/ErrorPage.aspx?Error=7"); } // Run the task. try { IList <Microsoft.EnterpriseManagement.Runtime.TaskResult> results = mg.TaskRuntime.ExecuteTask(targets, task, config); if (results.Count == 0) { Server.Transfer("~/ErrorPage.aspx?Error=4"); } // Display the task results. int resultNo = 0; foreach (Microsoft.EnterpriseManagement.Runtime.TaskResult res in results) { resultNo++; if (res.Status == Microsoft.EnterpriseManagement.Runtime.TaskStatus.Failed) { } else { //convert task result XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(res.Output); string xPathQry = @"/DataItem/Description"; System.Xml.XmlNode TaskDescription = xmlDoc.SelectSingleNode(xPathQry); string Servicelist = TaskDescription.OuterXml.ToString(); Servicelist = Servicelist.Replace("<Description>", "").Replace("</Description>", ""); // put result in table //DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Name", typeof(string)), new DataColumn("DisplayName", typeof(string)), new DataColumn("StartType", typeof(string)), new DataColumn("Status", typeof(string)) }); //Read the contents of CSV file. string csvData = Servicelist; string test = csvData.Split('\r')[0].ToString(); if (test == "<Description />") { Server.Transfer("~/ErrorPage.aspx?Error=7"); } string[] stringSeparators = new string[] { "\r\n" }; foreach (string row in csvData.Split(stringSeparators, StringSplitOptions.None)) { int i = 0; try { if (!string.IsNullOrEmpty(row)) { dt.Rows.Add(); dt.Rows[dt.Rows.Count - 1][0] = row.Split(',')[0]; dt.Rows[dt.Rows.Count - 1][1] = row.Split(',')[1]; dt.Rows[dt.Rows.Count - 1][2] = row.Split(',')[2]; dt.Rows[dt.Rows.Count - 1][3] = row.Split(',')[3].Replace(";", ""); i++; } string privrew = row.ToString(); } catch { } } ServiceView.DataSource = dt; ServiceView.DataBind(); } } } catch { Server.Transfer("~/ErrorPage.aspx?Error=0"); } }
public IHttpActionResult GetLinuxComputersByNameDetailed(string ComputerName) { ManagementPackClassCriteria classCriteria = new ManagementPackClassCriteria("Name = 'Microsoft.Linux.Computer'"); IList <ManagementPackClass> monitoringClasses = mg.EntityTypes.GetClasses(classCriteria); if (string.IsNullOrEmpty(ComputerName)) { throw new HttpResponseException(Request .CreateResponse(HttpStatusCode.BadRequest)); } else { MonitoringObjectCriteria criteria = new MonitoringObjectCriteria(string.Format("Name = '{0}'", ComputerName), monitoringClasses[0]); List <PartialMonitoringObject> linuxComputerObjects = new List <PartialMonitoringObject>(); IObjectReader <PartialMonitoringObject> reader = mg.EntityObjects.GetObjectReader <PartialMonitoringObject>(criteria, ObjectQueryOptions.Default); linuxComputerObjects.AddRange(reader); //Check if computers are in list if (linuxComputerObjects.Count > 0) { List <SCOMComputerModelDetailed> SCOMLinuxComputers = new List <SCOMComputerModelDetailed>(); foreach (PartialMonitoringObject linuxComputerObject in linuxComputerObjects) { ReadOnlyCollection <PartialMonitoringObject> RelatedObjects = linuxComputerObject.GetRelatedPartialMonitoringObjects(); SCOMComputerModelDetailed SCOMComputer = new SCOMComputerModelDetailed(); SCOMComputer.id = linuxComputerObject.Id; SCOMComputer.displayName = linuxComputerObject.DisplayName; SCOMComputer.healthState = linuxComputerObject.HealthState.ToString(); SCOMComputer.inMaintenance = linuxComputerObject.InMaintenanceMode; SCOMComputer.isAvailable = linuxComputerObject.IsAvailable; SCOMComputer.relatedObjectsCount = RelatedObjects.Count(); //Populate a list of child objects List <SCOMComputerModelChild> SCOMLinuxComputerChildObjects = new List <SCOMComputerModelChild>(); foreach (PartialMonitoringObject RelatedObject in RelatedObjects) { SCOMComputerModelChild ChildObject = new SCOMComputerModelChild(); ChildObject.id = RelatedObject.Id; ChildObject.displayName = RelatedObject.DisplayName; ChildObject.fullName = RelatedObject.FullName; ChildObject.inMaintenance = RelatedObject.InMaintenanceMode; ChildObject.path = RelatedObject.Path; ChildObject.healthState = RelatedObject.HealthState.ToString(); SCOMLinuxComputerChildObjects.Add(ChildObject); } //Add the list of all child objects to property of the computer object SCOMComputer.relatedObjects = SCOMLinuxComputerChildObjects; //Add the computer to the list to return SCOMLinuxComputers.Add(SCOMComputer); } //Successful return return(Json(SCOMLinuxComputers)); } //If computer cannot be found else { HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.NotFound); message.Content = new StringContent("Cannot find Computer. Please see input"); throw new HttpResponseException(message); } } }
//----------------------------------------------------------------------------------- public static void Start(string[] args) { ManagementGroup mg = new ManagementGroup("localhost"); IConnectorFrameworkManagement icfm = mg.ConnectorFramework; Guid connectorGuid = new Guid("{6A1F8C0E-B8F1-4147-8C9B-5A2F98F10003}"); MonitoringConnector connector; System.Timers.Timer FeedBackTimer = new System.Timers.Timer(); FeedBackTimer.Elapsed += new ElapsedEventHandler(GetAlertForClosing); FeedBackTimer.Interval = 1000 * 60; FeedBackTimer.Start(); try { if (args.Length == 1) { if (args[0] == "InstallConnector") { ConnectorInfo info = new ConnectorInfo(); info.Description = "Sample connector"; info.DisplayName = "Sample connector"; info.Name = "Sample connector"; connector = icfm.Setup(info, connectorGuid); connector.Initialize(); Console.WriteLine("Connector {0} has been succefuly installed", info.DisplayName); } else if (args[0] == "UninstallConnector") { connector = icfm.GetConnector(connectorGuid); IList<MonitoringConnectorSubscription> subscriptions; subscriptions = icfm.GetConnectorSubscriptions(); foreach (MonitoringConnectorSubscription subscription in subscriptions) { if (subscription.MonitoringConnectorId == connectorGuid) { icfm.DeleteConnectorSubscription(subscription); } } connector.Uninitialize(); icfm.Cleanup(connector); } return; } connector = icfm.GetConnector(connectorGuid); //Обрабатываем предупреждения в бесконечном цикле так как наше приложение является службой Windows while (true) { //Обьявляем перменную типа коллекция для хранения предупреждений ReadOnlyCollection<ConnectorMonitoringAlert> alerts; alerts = connector.GetMonitoringAlerts(); //Запускаем цикл для обработки каждого предупреждения foreach (ConnectorMonitoringAlert alert in alerts) { //Делаем проверку должно ли предупреждение создавать инцидент, если да то переменной flag присваиваем значение Yes. if (alert.ResolutionState == 0) { string flag = "No"; if ((alert.Priority == ManagementPackWorkflowPriority.High) && (alert.Severity == ManagementPackAlertSeverity.Warning)) { flag = "Yes"; } if ((alert.Priority == ManagementPackWorkflowPriority.Normal) && (alert.Severity == ManagementPackAlertSeverity.Error)) { flag = "Yes"; } if ((alert.Priority == ManagementPackWorkflowPriority.High) && (alert.Severity == ManagementPackAlertSeverity.Error)) { flag = "Yes"; } Console.WriteLine("Begin Processing Alert!"); // The criteria specifies that you want to collect // computers running Windows Server 2003. String criteria = "Id = " + "'" +alert.ClassId + "'"; Console.WriteLine(criteria); ManagementPackClassCriteria classCriteria = new ManagementPackClassCriteria(criteria); Console.WriteLine("Querying for data..."); // There should only be one item in the monitoringClasses collection. IList<ManagementPackClass> monitoringClasses = mg.EntityTypes.GetClasses(classCriteria); // Get all instances of computers running Windows Server 2003 in the management group. List<MonitoringObject> targets = new List<MonitoringObject>(); IObjectReader<MonitoringObject> reader = mg.EntityObjects.GetObjectReader<MonitoringObject>(monitoringClasses[0], ObjectQueryOptions.Default); targets.AddRange(reader); string logicalgroup = ""; foreach (MonitoringObject target in targets) { logicalgroup = DisplayRelationshipInformation(target, mg, alert.MonitoringObjectId); Console.WriteLine("SCOM Group: {0}", logicalgroup); if (logicalgroup.Contains("PS.")) { break; } } Log operLog = new Log("log.txt", "C:\\SCOM_OT\\Log"); operLog.Write("Begin Processing Alert: " + alert.Name.ToString() + " with serial number " + i.ToString() + " and ID " + alert.Id.ToString()); Console.WriteLine("SCOM Group Substring: {0}", logicalgroup.Substring(3)); //Send the alert to the other management system with the appropriate API //from the other management system. //Add a comment to the alert. string AlertFilePath; AlertFilePath = "C:\\SCOM_OT\\Alerts\\" + alert.Id.ToString() + ".txt"; System.IO.StreamWriter file = new System.IO.StreamWriter(AlertFilePath, true); file.WriteLine("#{0} Alert received on {1}", i.ToString(), DateTime.Now); file.WriteLine(">> Name: {0}", alert.Name.ToString()); file.WriteLine(">> Id: {0}", alert.Id.ToString()); file.WriteLine(">> SCOM Group: {0}", logicalgroup.Substring(3)); file.WriteLine(">> Category: {0}", alert.Category.ToString()); file.WriteLine(">> ConnectorId: {0}", alert.ConnectorId.ToString()); file.WriteLine(">> ConnectorStatus: {0}", alert.ConnectorStatus.ToString()); file.WriteLine(">> RepeatCount: {0}", alert.RepeatCount.ToString()); file.WriteLine(">> ResolutionState: {0}", alert.ResolutionState.ToString()); file.WriteLine(">> LastModified: {0}", alert.LastModified.ToString()); file.WriteLine(">> LastModifiedByNonConnector: {0}", alert.LastModifiedByNonConnector.ToString()); file.WriteLine(">> Priority: {0}", alert.Priority.ToString()); file.WriteLine(">> Severity: {0}", alert.Severity.ToString()); file.WriteLine(">> Description: {0}", alert.Description); file.WriteLine(">> Monitoring Object ID: {0}", alert.MonitoringObjectId); file.WriteLine(">> Must Generate Incident: {0}", flag); file.WriteLine(">> Processed in OT: No"); file.WriteLine(""); file.Close(); Console.WriteLine("#{0} Alert received on {1}", i.ToString(), DateTime.Now); Console.WriteLine(">> Id: {0}", alert.Id.ToString()); Console.WriteLine(">> Category: {0}", alert.Category.ToString()); Console.WriteLine(">> ConnectorId: {0}", alert.ConnectorId.ToString()); Console.WriteLine(">> ConnectorStatus: {0}", alert.ConnectorStatus.ToString()); Console.WriteLine(">> RepeatCount: {0}", alert.RepeatCount.ToString()); Console.WriteLine(">> ResolutionState: {0}", alert.ResolutionState.ToString()); Console.WriteLine(">> LastModified: {0}", alert.LastModified.ToString()); Console.WriteLine(">> LastModifiedByNonConnector: {0}", alert.LastModifiedByNonConnector.ToString()); Console.WriteLine(">> Priority: {0}", alert.Priority.ToString()); Console.WriteLine(">> Severity: {0}", alert.Severity.ToString()); Console.WriteLine(">> Description: {0}", alert.Description); Console.WriteLine(""); i = i + 1; //Console.WriteLine("\nAlert Resolution State Before: " + alert.ResolutionState.ToString()); alert.ResolutionState = 11; //Console.WriteLine("\nAlert Resolution State After: " + alert.ResolutionState.ToString()); alert.Update("Alert has been forwarded to OT"); operLog.Write("End Processing Alert: " + alert.Name.ToString() + " with serial number " + i.ToString() + " and ID " + alert.Id.ToString()); } } //Wait for a minute before checking for new alerts again. Thread.Sleep(5 * 1000); } } catch (EnterpriseManagementException error) { Console.WriteLine(error.Message); } }