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>
 /// Updates the specified model.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <param name="isPolling">if set to <c>true</c> [is polling].</param>
 /// <exception cref="System.Exception"></exception>
 public void Update(Enclosure model, bool isPolling)
 {
     try
     {
         HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Start UpdateEnclosure.[{model.UnionId}] [isPolling:{isPolling}]");
         var exsitEnclosure = this.GetObject($"UnionId = '{model.UnionId}'", this.EnclosureClass);
         if (exsitEnclosure == null)
         {
             throw new Exception($"Can not find the server:{model.UnionId}");
         }
         var isChange = CompareEnclosure(model, exsitEnclosure);
         if (isChange)
         {
             var discoveryData = new IncrementalDiscoveryData();
             this.UpdateEnclosure(model, exsitEnclosure);
             discoveryData.Add(exsitEnclosure);
             discoveryData.Overwrite(this.MontioringConnector);
             HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Info($"Update enclosure finish.[{model.UnionId}]");
         }
     }
     catch (Exception e)
     {
         HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Error(e, $"Update enclosure error.[{model.UnionId}] [isPolling:{isPolling}]");
     }
 }
Example #3
0
        /// <summary>
        /// Updates the specified appliance.
        /// </summary>
        /// <param name="appliance">The appliance.</param>
        /// <param name="isUpdateCredential">是否修改了密码</param>
        /// <returns>Result.</returns>
        public async Task <Result> Update(FdAppliance appliance, bool isUpdateCredential)
        {
            return(await Task.Run(async() =>
            {
                try
                {
                    var obj = await this.FindByHost(appliance.HostIP);
                    var exsitObj = obj.Data;
                    if (exsitObj == null)
                    {
                        return Result.Failed(104, $"Fd {appliance.HostIP} can not find.");
                    }
                    var incrementalDiscoveryData = new IncrementalDiscoveryData();

                    var props = this.FdApplianceClass.PropertyCollection;
                    exsitObj[props["AliasName"]].Value = appliance.AliasName;
                    exsitObj[props["Port"]].Value = appliance.Port;
                    exsitObj[props["LastModifyTime"]].Value = appliance.LastModifyTime;

                    if (isUpdateCredential)
                    {
                        try
                        {
                            var eventAccount = exsitObj[props["EventUserName"]].Value as string;
                            var eventPd = exsitObj[props["EventPd"]].Value as string;
                            if (eventAccount != appliance.EventUserName || eventPd != appliance.EventPd)
                            {
                                using (var client = new FdClient(appliance))
                                {
                                    var res = await client.DeleteGivenSubscriptions(appliance.SubscribeId);
                                    LogHelper.Info($"Update Fd:DeleteGivenSubscriptions:{res.Code} {res.Message}");
                                    // 取消订阅后重置订阅状态
                                    exsitObj[props["SubscribeId"]].Value = string.Empty;
                                    exsitObj[props["SubscribeStatus"]].Value = string.Empty;
                                    exsitObj[props["LatestSubscribeInfo"]].Value = string.Empty;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error("DeleteSubscriptions Faild", ex);
                        }
                        exsitObj[props["LoginAccount"]].Value = appliance.LoginAccount;
                        exsitObj[props["LoginPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.LoginPd);
                        exsitObj[props["EventUserName"]].Value = appliance.EventUserName;
                        exsitObj[props["EventPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.EventPd);
                    }

                    incrementalDiscoveryData.Add(exsitObj);
                    incrementalDiscoveryData.Overwrite(MGroup.Instance);

                    return Result.Done();
                }
                catch (Exception e)
                {
                    return Result.Failed(100, $"Internal error caused by {e.Message}", e);
                }
            }));
        }
Example #4
0
        /// <summary>
        /// The update rack.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="isPolling">是否是轮询</param>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="Exception"></exception>
        public void UpdateRack(RackServer model, bool isPolling)
        {
            try
            {
                HWLogger.GetESightSdkLogger(model.ESight).Debug($"Start UpdateRack. [{model.DN}] [isPolling:{isPolling}]");
                var oldBlade = this.GetRackServer(model.DeviceId);
                if (oldBlade == null)
                {
                    throw new Exception($"Can not find the server:{model.DN}");
                }
                var propertys     = this.RackClass.PropertyCollection; // 获取到class的属性
                var discoveryData = new IncrementalDiscoveryData();
                oldBlade[this.DisplayNameField].Value = model.ServerName;
                if (model.Status != "-3")
                {
                    oldBlade[propertys["Status"]].Value = model.StatusTxt;
                }
                oldBlade[propertys["iBMCIPv4Address"]].Value  = model.iBMCIPv4Address;
                oldBlade[propertys["Type"]].Value             = model.Type;
                oldBlade[propertys["UUID"]].Value             = model.UUID;
                oldBlade[propertys["AveragePower"]].Value     = model.AveragePower;
                oldBlade[propertys["PeakPower"]].Value        = model.PeakPower;
                oldBlade[propertys["PowerConsumption"]].Value = model.PowerConsumption;
                oldBlade[propertys["DNSServerIP"]].Value      = model.DNSServerIP;
                oldBlade[propertys["DNSName"]].Value          = model.DNSName;


                oldBlade[propertys["ProductSn"]].Value      = model.ProductSN;
                oldBlade[propertys["HostName"]].Value       = model.HostName;
                oldBlade[propertys["CPUNums"]].Value        = model.CPUNums;
                oldBlade[propertys["CPUCores"]].Value       = model.CPUCores;
                oldBlade[propertys["CPUModel"]].Value       = model.CPUModel;
                oldBlade[propertys["MemoryCapacity"]].Value = model.MemoryCapacity;
                oldBlade[propertys["AssertTag"]].Value      = model.AssertTag;
                if (isPolling)
                {
                    oldBlade[propertys["BMCVersion"]].Value = model.BMCVersion;
                }
                oldBlade[propertys["eSight"]].Value = model.ESight;
                discoveryData.Add(oldBlade);
                discoveryData.Overwrite(this.MontioringConnector);
            }
            catch (Exception e)
            {
                HWLogger.GetESightSdkLogger(model.ESight).Error($"Update UpdateRack Error.[{model.DN}] [isPolling:{isPolling}]", 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;
            }
        }
Example #6
0
        private void NewDestinationDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.None && DialogResult == DialogResult.OK)
            {
                string fqdnValue        = tbFQDN.Text;
                int    targetIndexValue = 0;
                if (cbAllowDuplicates.Checked || ExistingObject != null) // for existing object always use existing index value, which was loaded into nudTargetIndex in the constructor
                {
                    targetIndexValue = Convert.ToInt32(nudTargetIndex.Value);
                }
                object selectedMAP = null;
                if (rbPool.Checked)
                {
                    selectedMAP = cbResourcePools.SelectedItem;
                }
                if (rbAgent.Checked)
                {
                    selectedMAP = lbAgentList.SelectedItem;
                }
                if (selectedMAP is MonitoringObject mo)
                {
                    tbMAPDetails.Text = $"{mo.DisplayName ?? "N/A"} of {mo.GetType().Name}";
                }
                else
                {
                    tbMAPDetails.Text = $"{selectedMAP?.ToString() ?? "NULL"} of {selectedMAP?.GetType().Name ?? "N/A"}";
                }

                // basic preliminary checks
                if (string.IsNullOrWhiteSpace(fqdnValue))
                {
                    MessageBox.Show("FQDN value cannot be empty.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
                bool ipResolved;
                try
                {
                    IPAddress[] ipList = Dns.GetHostAddresses(fqdnValue);
                    if (ipList == null || ipList.Length == 0)
                    {
                        ipResolved = false;
                    }
                    else
                    {
                        ipResolved = true;
                    }
                }
                catch
                {
                    ipResolved = false;
                }
                if (!ipResolved)
                {
                    if (MessageBox.Show("FQDN is specified, but cannot be resolved into an IP address in the current location, i.e. at the machine where SCOM Console application is running. However, the selected action point might be able to resolve it.\r\nContinue or cancel?", "Warning!", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                if (selectedMAP == null)
                {
                    MessageBox.Show("Select an agent or a resource pool, which is to handle tests for the destination.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }

                // Scenarios: 1) new object 2) edit object 3) move object to a new MAP/HS 4) 2 + 3
                #region New Object
                if (ExistingObjectId == Guid.Empty)
                {
                    // try to find an existing object, to avoid update instead of insert/add

                    if (IsFQDNClassInstanceExists(fqdnValue, targetIndexValue))
                    {
                        if (cbAllowDuplicates.Checked)
                        {
                            if (MessageBox.Show("Duplicates are allowed, but a duplicate with the same target index already exists.\r\nFind another index automatically?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                int newIndex = 0;
                                while (IsFQDNClassInstanceExists(fqdnValue, newIndex))
                                {
                                    newIndex++;
                                }
                                targetIndexValue     = newIndex;
                                nudTargetIndex.Value = newIndex;
                            }
                            else
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("This destination already exists.\r\nSelect 'Allow duplicates' to create a duplicate destination, or reuse the existing destination to add tests.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            e.Cancel = true;
                            return;
                        }
                    }

                    // finally, trying to create a new destination
                    try
                    {
                        IncrementalDiscoveryData                        incrementalDiscovery             = new IncrementalDiscoveryData();
                        CreatableEnterpriseManagementObject             newInstance                      = new CreatableEnterpriseManagementObject(ManagementGroup, fqdnClass);
                        CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;

                        newInstance[SystemId.EntityClassProperties.DisplayNamePropertyId].Value = string.IsNullOrEmpty(tbDisplayName.Text) ? fqdnValue : tbDisplayName.Text;
                        newInstance[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value = fqdnValue;
                        newInstance[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value = targetIndexValue;
                        newInstance[IDs.FullyQualifiedDomainNameClassProperties.DescriptionPropertyId].Value = string.IsNullOrEmpty(tbDescription.Text) ? "" : tbDescription.Text;

                        if (rbAgent.Checked)
                        {
                            newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relHealthServiceShouldManageEntiry);
                        }
                        if (rbPool.Checked)
                        {
                            newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relResourcePoolShouldManageEntity);
                        }
                        newSomethingShouldManageInstance?.SetTarget(newInstance);
                        newSomethingShouldManageInstance?.SetSource(selectedMAP as MonitoringObject);

                        incrementalDiscovery.Add(newInstance);
                        if (newSomethingShouldManageInstance != null)
                        {
                            incrementalDiscovery.Add(newSomethingShouldManageInstance);
                        }

                        EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector();
                        incrementalDiscovery.Commit(connector);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Failed to create new destination.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        e.Cancel = true;
                        return;
                    }

                    // END SCENARIO #1
                    return;
                }
                #endregion
                #region Update Object details
                if (ExistingObject != null)
                {
                    bool objectChanged = false;
                    objectChanged = objectChanged || (ExistingObject[SystemId.EntityClassProperties.DisplayNamePropertyId].Value?.ToString() != tbDisplayName.Text);
                    // immutable: objectChanged = objectChanged || (ExistingObject[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value?.ToString() != fqdnValue);
                    objectChanged = objectChanged || (ExistingObject[IDs.FullyQualifiedDomainNameClassProperties.DescriptionPropertyId].Value?.ToString() != tbDescription.Text);
                    // TargetIndex cannot be changed for existing objects
                    if (objectChanged)
                    {
                        try
                        {
                            IncrementalDiscoveryData            incrementalDiscovery = new IncrementalDiscoveryData();
                            CreatableEnterpriseManagementObject modifiedInstance     = new CreatableEnterpriseManagementObject(ManagementGroup, fqdnClass);

                            modifiedInstance[SystemId.EntityClassProperties.DisplayNamePropertyId].Value = string.IsNullOrEmpty(tbDisplayName.Text) ? "" : tbDisplayName.Text;
                            modifiedInstance[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value = fqdnValue;
                            modifiedInstance[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value = targetIndexValue;
                            modifiedInstance[IDs.FullyQualifiedDomainNameClassProperties.DescriptionPropertyId].Value = string.IsNullOrEmpty(tbDescription.Text) ? "" : tbDescription.Text;

                            incrementalDiscovery.Add(modifiedInstance);
                            EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector();
                            incrementalDiscovery.Overwrite(connector);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Failed to update the destination details.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            e.Cancel = true;
                            return;
                        }
                    }
                }
                #endregion
                #region Move object servicing point
                if (ExistingObject != null)
                {
                    IEnumerable <MonitoringObject> currentActionPoints = FindActionPoints(ExistingObject);
                    if (currentActionPoints.Any() && HasMAPChanged(currentActionPoints.First()))
                    {
                        try
                        {
                            MonitoringObject newMAP = selectedMAP as MonitoringObject;
                            // remove all existing SHOULD-relations
                            EnterpriseManagementConnector connector        = ManagementGroup.ConnectorFramework.GetMonitoringConnector();
                            IncrementalDiscoveryData      RemovalDiscovery = new IncrementalDiscoveryData();
                            bool commitOverwrite = false;
                            IEnumerable <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > allMAPRelations = ManagementGroup.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(ExistingObject.Id, relResourcePoolShouldManageEntity, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);
                            IEnumerable <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > allHSRelations  = ManagementGroup.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(ExistingObject.Id, relHealthServiceShouldManageEntiry, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);
                            foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in allMAPRelations)
                            {
                                if (rel.SourceObject.Id != newMAP.Id)
                                {
                                    // remove this relationship
                                    RemovalDiscovery.Remove(rel);
                                    commitOverwrite = true;
                                }
                            }
                            foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in allHSRelations)
                            {
                                if (rel.SourceObject.Id != newMAP.Id)
                                {
                                    // remove this relationship
                                    RemovalDiscovery.Remove(rel);
                                    commitOverwrite = true;
                                }
                            }
                            if (commitOverwrite)
                            {
                                RemovalDiscovery.Overwrite(connector);
                            }

                            // add the new relationship
                            IncrementalDiscoveryData incrementalDiscovery = new IncrementalDiscoveryData();
                            CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;
                            if (rbAgent.Checked)
                            {
                                newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relHealthServiceShouldManageEntiry);
                            }
                            if (rbPool.Checked)
                            {
                                newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relResourcePoolShouldManageEntity);
                            }
                            newSomethingShouldManageInstance?.SetTarget(ExistingObject);
                            newSomethingShouldManageInstance?.SetSource(newMAP);

                            if (newSomethingShouldManageInstance != null)
                            {
                                incrementalDiscovery.Add(newSomethingShouldManageInstance);
                            }

                            incrementalDiscovery.Commit(connector);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Failed to update destination's management action point.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            e.Cancel = true;
                            return;
                        }
                    }
                }
                #endregion
            }
        }
        private void PerformRelationshipCleanup(ManagementPackClass mySeedClass, CreatableEnterpriseManagementObject newSeedInstance, MonitoringObject monitoringObject)
        {
            // it's so complex, because the new instance may not exist
            EnterpriseManagementObject realSeedInstance;
            string criteriaString = "";

            foreach (ManagementPackProperty property in newSeedInstance.GetProperties())
            {
                if (property.Key)
                {
                    if (criteriaString == "")
                    {
                        criteriaString = property.Name + "='" + newSeedInstance[property] + "'";
                    }
                    else
                    {
                        criteriaString += " AND " + property.Name + "='" + newSeedInstance[property] + "'";
                    }
                }
            }
            EnterpriseManagementObjectCriteria         searchQuery          = new EnterpriseManagementObjectCriteria(criteriaString, mySeedClass);
            IObjectReader <EnterpriseManagementObject> realSeedInstanceList = myMG.EntityObjects.GetObjectReader <EnterpriseManagementObject>(searchQuery, ObjectQueryOptions.Default);

            if (realSeedInstanceList.Count == 0)
            {
                return;
            }
            else
            {
                realSeedInstance = realSeedInstanceList.First();
            }

            IncrementalDiscoveryData RemovalDiscovery = new IncrementalDiscoveryData();
            // Management Point
            bool commitOverwrite = false;
            IEnumerable <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > allMAPRelations = myMG.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(realSeedInstance.Id, relToClearMAP, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);
            IEnumerable <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > allHSRelations  = myMG.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(realSeedInstance.Id, relToClearHS, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);

            foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in allMAPRelations)
            {
                if (rel.SourceObject.Id != monitoringObject.Id)
                {
                    // remove this relationship
                    RemovalDiscovery.Remove(rel);
                    commitOverwrite = true;
                }
            }
            foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in allHSRelations)
            {
                if (rel.SourceObject.Id != monitoringObject.Id)
                {
                    // remove this relationship
                    RemovalDiscovery.Remove(rel);
                    commitOverwrite = true;
                }
            }
            if (commitOverwrite)
            {
                RemovalDiscovery.Overwrite(myConnector);
            }
        }
Example #8
0
        /// <summary>
        /// The update child blade.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <exception cref="Exception">Can not find the child blade server</exception>
        public void UpdateChildBoard(ChildHighdensity model)
        {
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateChildBoard");
            var oldObject = this.GetObject($"DN = '{model.DN}'", this.ChildHighdensityClass);

            if (oldObject == null)
            {
                throw new Exception($"Can not find the child blade server:{model.DN}");
            }
            var propertys = this.ChildHighdensityClass.PropertyCollection; // 获取到class的属性

            var discoveryData = new IncrementalDiscoveryData();

            var childHighdensityKey = this.ChildHighdensityClass.PropertyCollection["DN"];

            oldObject[propertys["Status"]].Value    = model.Status;
            oldObject[propertys["IPAddress"]].Value = model.IpAddress;
            oldObject[propertys["UUID"]].Value      = model.UUID;
            oldObject[propertys["ProductSn"]].Value = model.ProductSn;
            oldObject[propertys["Type"]].Value      = model.Type;

            oldObject[this.DisplayNameField].Value = model.Name;
            discoveryData.Add(oldObject);

            #region CPU

            var cpuGroup = oldObject.GetRelatedMonitoringObjects(this.CpuGroupClass).First();
            discoveryData.Add(cpuGroup);

            var relatedCpuObjects = cpuGroup.GetRelatedMonitoringObjects(this.CpuClass);
            var deleteCpu         = relatedCpuObjects.Where(
                x => model.CPUList.All(y => y.UUID != x[this.CpuClass.PropertyCollection["UUID"]].Value.ToString()))
                                    .ToList();
            deleteCpu.ForEach(x => { discoveryData.Remove(x); });
            model.CPUList.ForEach(
                y =>
            {
                var cpu = this.UpdateCpu(y);
                if (cpu == null)
                {
                    var newCpu = this.CreateCpu(y);
                    newCpu[this.PartChildGroupKey].Value = cpuGroup[this.PartChildGroupKey].Value;
                    newCpu[childHighdensityKey].Value    = model.DN;
                    newCpu[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newCpu[this.ComputerKey].Value       = model.DN;
                    newCpu[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newCpu);
                }
                else
                {
                    discoveryData.Add(cpu);
                }
            });

            #endregion

            #region Memory

            var memoryGroup = oldObject.GetRelatedMonitoringObjects(this.MemoryGroupClass).First();
            discoveryData.Add(memoryGroup);

            var relatedMemoryObjects = memoryGroup.GetRelatedMonitoringObjects(this.MemoryClass);
            var deleteMemory         = relatedMemoryObjects.Where(
                x => model.MemoryList.All(
                    y => y.UUID != x[this.MemoryClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deleteMemory.ForEach(x => { discoveryData.Remove(x); });
            model.MemoryList.ForEach(
                y =>
            {
                var memory = this.UpdateMemory(y);
                if (memory == null)
                {
                    var newMemory = this.CreateMemory(y);
                    newMemory[this.PartChildGroupKey].Value = memoryGroup[this.PartChildGroupKey].Value;
                    newMemory[childHighdensityKey].Value    = model.DN;
                    newMemory[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newMemory[this.ComputerKey].Value       = model.DN;
                    newMemory[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newMemory);
                }
                else
                {
                    discoveryData.Add(memory);
                }
            });

            #endregion

            #region Disk

            var diskGroup = oldObject.GetRelatedMonitoringObjects(this.DiskGroupClass).First();
            discoveryData.Add(diskGroup);

            var relatedDiskObjects = diskGroup.GetRelatedMonitoringObjects(this.DiskClass);
            var deleteDisk         = relatedDiskObjects.Where(
                x => model.DiskList.All(
                    y => y.UUID != x[this.DiskClass.PropertyCollection["UUID"]].Value.ToString()))
                                     .ToList();
            deleteDisk.ForEach(x => { discoveryData.Remove(x); });
            model.DiskList.ForEach(
                y =>
            {
                var disk = this.UpdateDisk(y);
                if (disk == null)
                {
                    var newDisk = this.CreateDisk(y);
                    newDisk[this.PartChildGroupKey].Value = diskGroup[this.PartChildGroupKey].Value;
                    newDisk[childHighdensityKey].Value    = model.DN;
                    newDisk[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newDisk[this.ComputerKey].Value       = model.DN;
                    newDisk[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newDisk);
                }
                else
                {
                    discoveryData.Add(disk);
                }
            });

            #endregion

            #region Raid

            var raidGroup = oldObject.GetRelatedMonitoringObjects(this.RaidGroupClass).First();
            discoveryData.Add(raidGroup);

            var relatedRaidObjects = raidGroup.GetRelatedMonitoringObjects(this.RaidClass);
            var deleteRaid         = relatedRaidObjects.Where(
                x => model.RaidList.All(
                    y => y.UUID != x[this.RaidClass.PropertyCollection["UUID"]].Value.ToString()))
                                     .ToList();
            deleteRaid.ForEach(x => { discoveryData.Remove(x); });
            model.RaidList.ForEach(
                y =>
            {
                var raid = this.UpdateRaidControl(y);
                if (raid == null)
                {
                    var newRaid = this.CreateRaidControl(y);
                    newRaid[this.PartChildGroupKey].Value = raidGroup[this.PartChildGroupKey].Value;
                    newRaid[childHighdensityKey].Value    = model.DN;
                    newRaid[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newRaid[this.ComputerKey].Value       = model.DN;
                    newRaid[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newRaid);
                }
                else
                {
                    discoveryData.Add(raid);
                }
            });

            #endregion

            discoveryData.Overwrite(this.MontioringConnector);
            HWLogger.NOTIFICATION_PROCESS.Debug("End UpdateChildBoard");
        }
Example #9
0
        /// <summary>
        /// Updates the main with out related.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public void UpdateMainWithOutChildBlade(HighdensityServer model)
        {
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateHighdensity WithOut ChildBoard");
            var oldBlade = this.GetHighdensityServer(model.DN);

            if (oldBlade == null)
            {
                throw new Exception($"Can not find the server:{model.DN}");
            }
            var propertys     = this.HighdensityClass.PropertyCollection; // 获取到class的属性
            var discoveryData = new IncrementalDiscoveryData();

            oldBlade[propertys["eSight"]].Value       = model.ESight;
            oldBlade[propertys["Status"]].Value       = model.Status;
            oldBlade[propertys["UUID"]].Value         = model.UUID;
            oldBlade[propertys["Vendor"]].Value       = "HUAWEI";
            oldBlade[propertys["Manufacturer"]].Value = model.Manufacturer;
            oldBlade[propertys["IPAddress"]].Value    = model.IpAddress;
            oldBlade[propertys["ProductSn"]].Value    = model.ProductSN;

            // oldBlade[propertys["ServerName"]].Value = model.ServerName;
            // oldBlade[propertys["iBMCVersion"]].Value = model.Version;
            oldBlade[this.DisplayNameField].Value = model.ServerName;
            discoveryData.Add(oldBlade);

            var fanGroup = oldBlade.GetRelatedMonitoringObjects(this.FanGroupClass).First();

            discoveryData.Add(fanGroup);

            var relatedFanObjects = fanGroup.GetRelatedMonitoringObjects(this.FanClass);
            var deleteFan         = relatedFanObjects.Where(
                x => model.FanList.All(y => y.UUID != x[this.FanClass.PropertyCollection["UUID"]].Value.ToString()))
                                    .ToList();

            deleteFan.ForEach(x => { discoveryData.Remove(x); });
            model.FanList.ForEach(
                x =>
            {
                var fan = this.UpdateFan(x);
                if (fan == null)
                {
                    var newFan = this.CreateFan(x);
                    newFan[this.PartGroupKey].Value    = fanGroup[this.PartGroupKey].Value;
                    newFan[this.ComputerKey].Value     = model.DN;
                    newFan[this.HuaweiServerKey].Value = model.DN;
                    discoveryData.Add(newFan);
                }
                else
                {
                    discoveryData.Add(fan);
                }
            });

            #region PSU

            var psuGroup = oldBlade.GetRelatedMonitoringObjects(this.PowerSupplyGroupClass).First();
            discoveryData.Add(psuGroup);

            var relatedPsuObjects = psuGroup.GetRelatedMonitoringObjects(this.PowerSupplyClass);
            var deletePsu         = relatedPsuObjects.Where(
                x => model.PowerSupplyList.All(
                    y => y.UUID != x[this.PowerSupplyClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deletePsu.ForEach(x => { discoveryData.Remove(x); });

            model.PowerSupplyList.ForEach(
                x =>
            {
                var psu = this.UpdatePowerSupply(x);
                if (psu == null)
                {
                    var newpsu = this.CreatePowerSupply(x);
                    newpsu[this.PartGroupKey].Value    = psuGroup[this.PartGroupKey].Value;
                    newpsu[this.ComputerKey].Value     = model.DN;
                    newpsu[this.HuaweiServerKey].Value = model.DN;
                    discoveryData.Add(newpsu);
                }
                else
                {
                    discoveryData.Add(psu);
                }
            });

            #endregion

            // var relatedObjects = oldBlade.GetRelatedMonitoringObjects(ChildHighdensityClass);
            // relatedObjects.ToList().ForEach(x => discoveryData.Add(x));
            discoveryData.Overwrite(this.MontioringConnector);
            HWLogger.NOTIFICATION_PROCESS.Debug("End UpdateHighdensity WithOut ChildBoard");
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                //System.Threading.Thread.Sleep(10000); //makes debugging easier.
                if (ConnectorId == null)
                {
                    throw new ArgumentNullException("ConnectorId is null.");
                }

                startTime = DateTime.UtcNow; //set the start time.

                //setup event log access
                if (!EventLog.SourceExists(strEventLogTitle)) //check if WF account is non-admin
                {
                    EventLog.CreateEventSource(strEventLogTitle, "Operations Manager");
                }

                #region Setup connection to EMG and get objects.
                emg = new EnterpriseManagementGroup("localhost");

                setEnterpriseManagementObjects();

                //get the last run date time so we can get projects with a last modified date greater than the last run. Check for UTC on project...
                DateTime lastRun = emoStatus[null, "LastRunFinishTime"].Value == null ? DateTime.MinValue : (DateTime)emoStatus[null, "LastRunFinishTime"].Value;

                //check to see if retention is enabled.  If so, and this is the first run, change the lastRun date.
                var retentionEnabled = emoSettings[null, "IsRetentionEnabled"].Value == null ? false : (bool)emoSettings[null, "IsRetentionEnabled"].Value;
                if (retentionEnabled && DateTime.Equals(lastRun, DateTime.MinValue))
                {
                    lastRun = DateTime.Now.AddDays(-(Convert.ToDouble(emoSettings[null, "RetentionDays"].Value)));
                }

                //set the start time on the status object.
                emoStatus[null, "LastRunStartTime"].Value  = startTime;
                emoStatus[null, "LastRunFinishTime"].Value = null;
                emoStatus[null, "Status"].Value            = mpeSyncStatusEnums.First(mpe => mpe.Name == "Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.Running");
                emoStatus[null, "MinValue"].Value          = 0;
                emoStatus[null, "MaxValue"].Value          = 100;
                #endregion

                #region Get connector credentails
                NetworkCredential creds = NetworkCredentialsHelper.GetProjectCredentials(emoConnector[null, "RunAsAccount"].Value.ToString(), emoConnector[null, "Id"].ToString(), emg.Name);
                #endregion

                EventLog.WriteEntry(strEventLogTitle, string.Format("Starting Project CI sync from Project Server...\r\n\r\nProject Server: {0}\r\nUser Name: {1}", emoConnector[null, "ProjectServerURL"].Value.ToString(), creds.Domain + "\\" + creds.UserName));

                #region license check
                var licenseExpiration = checkLicense(); //method will throw an exception if no license exists.
                EventLog.WriteEntry(strEventLogTitle, string.Format("License Expiration: {0}", licenseExpiration));
                #endregion

                #region Connect to Project Server and read data
                ProjectConnector projectConnector = new ProjectConnector(emoConnector[null, "ProjectServerURL"].Value.ToString(), creds);
                projectConnector.Connect();

                #endregion

                #region Read data from Project Server

                if (lastRun == DateTime.MinValue)
                {
                    EventLog.WriteEntry(strEventLogTitle, "Querying Project Server for a full list of projects...");
                }
                else
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Querying Project Server for Projects created or modified since: {0} UTC...", lastRun));
                }

                projectConnector.LoadProjects(lastRun);

                #endregion

                #region Write data to the Service Manager DB.

                totalToProcess = projectConnector.Projects.Count();
                if (totalToProcess > 0)
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Processing {0} projects returned from Project Server...", totalToProcess), EventLogEntryType.Information, 0);

                    iddObjects = new IncrementalDiscoveryData();
                    List <Exception> exceptionsList = new List <Exception>();

                    foreach (PublishedProject project in projectConnector.Projects)
                    {
                        try
                        {
                            projectConnector.LoadProjectTaskData(project);
                            projectConnector.LoadProjectMetaData(project);

                            iddObjects.Add(buildProjectCI(project, mpcClasses.First(c => c.Name == "Cireson.ProjectAutomation.Project")));
                        }
                        catch (EnterpriseManagementException ex)
                        {
                            exceptionsList.Add(new ProjectImportException(string.Format("An error occured while importing the following project:\r\n\r\nProject Name: {0}\r\n{1}\r\n", project.Name, ex)));
                            hasImportFailure = true;
                        }
                        //catch SP exceptions
                        finally
                        {
                            totalProcessed++;
                            updateWorkflowStatus(false, ((totalProcessed * 100) / totalToProcess));
                        }
                    }//end of foreach.

                    #endregion

                    //commit the changes to the database
                    iddObjects.Overwrite(emg);

                    if (exceptionsList.Count > 0)
                    {
                        throw new AggregateException(string.Format("{0} projects failed to sync. ", (totalToProcess - exceptionsList.Count).ToString()), exceptionsList);
                    }
                    else
                    {
                        EventLog.WriteEntry(strEventLogTitle, string.Format("{0} projects successfully committed.  Elapsed Time: {1} seconds.", totalProcessed, getRunTime(startTime).Seconds), EventLogEntryType.Information, 0);
                    }
                }
                else
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("No updated projects exist.  Project Connector workflow is exiting.  Elapsed Time: {0} seconds.", getRunTime(startTime).Seconds));
                }
            }
            catch (AggregateException ex)
            {
                TrackData(ex.Message);

                StringBuilder exceptionStrings = new StringBuilder();
                foreach (var innerEx in ex.InnerExceptions)
                {
                    exceptionStrings.AppendLine(string.Format(strExceptionMessage, innerEx.Message, innerEx.InnerException, innerEx.StackTrace, innerEx.Source));
                }

                EventLog.WriteEntry(strEventLogTitle, string.Format(ex.Message + "Elapsed Time: {0} seconds. The following projects failed to sync: \r\n\r\n{1}", getRunTime(startTime).Seconds, exceptionStrings.ToString()), EventLogEntryType.Error, 1);
                hasImportFailure = true;
            }
            catch (EnterpriseManagementException ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                hasImportFailure = true;
                throw;
            }
            catch (Exception ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                hasImportFailure = true;
                throw;
            }
            finally
            {
                updateWorkflowStatus(true, 100);

                if (emg != null)
                {
                    emg.Dispose();
                }
            }
            return(ActivityExecutionStatus.Closed);
        }
Example #11
0
        /// <summary>
        /// The insert detials.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public void InsertDetials(HighdensityServer 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 HighdensityServer

            var highdensityServer = this.CreateHighdensityServer(model);
            highdensityServer[this.HuaweiServerKey].Value = model.DN;

            discoveryData.Add(highdensityServer);

            #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.ComputerKey].Value     = model.DN;
                fan[this.HuaweiServerKey].Value = model.DN;
                discoveryData.Add(fan);
            });

            #endregion

            #region PSU

            var psuGroup = this.CreateLogicalGroup(this.PowerSupplyGroupClass, model.DN);
            discoveryData.Add(psuGroup);
            model.PowerSupplyList.ForEach(
                x =>
            {
                var powerSupply = this.CreatePowerSupply(x);
                powerSupply[this.PartGroupKey].Value    = psuGroup[this.PartGroupKey].Value;
                powerSupply[this.ComputerKey].Value     = model.DN;
                powerSupply[this.HuaweiServerKey].Value = model.DN;
                discoveryData.Add(powerSupply);
            });

            #endregion

            #region Child Highdensity

            var childHighdensityGroup    = this.CreateLogicalGroup(this.ChildHighdensityGroupClass, model.DN);
            var childHighdensityGroupKey = childHighdensityGroup[this.PartGroupKey].Value.ToString();
            discoveryData.Add(childHighdensityGroup);
            model.ChildHighdensitys.ForEach(
                x =>
            {
                var childHighdensity = this.CreateChildHighdensity(x);
                childHighdensity[this.PartGroupKey].Value    = childHighdensityGroupKey;
                childHighdensity[this.ComputerKey].Value     = model.DN;
                childHighdensity[this.HuaweiServerKey].Value = model.DN;
                discoveryData.Add(childHighdensity);
                var childHighdensityKey = this.ChildHighdensityClass.PropertyCollection["DN"];

                #region CPU

                var cpuGroup = this.CreateLogicalChildGroup(this.CpuGroupClass, model.DN, x.DN);

                cpuGroup[childHighdensityKey].Value = x.DN;
                cpuGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                discoveryData.Add(cpuGroup);
                x.CPUList.ForEach(
                    y =>
                {
                    var cpu = this.CreateCpu(y);
                    cpu[this.PartChildGroupKey].Value = cpuGroup[this.PartChildGroupKey].Value;
                    cpu[childHighdensityKey].Value    = x.DN;
                    cpu[this.PartGroupKey].Value      = childHighdensityGroupKey;
                    cpu[this.ComputerKey].Value       = model.DN;
                    cpu[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(cpu);
                });

                #endregion

                #region Memory

                var memoryGroup = this.CreateLogicalChildGroup(this.MemoryGroupClass, model.DN, x.DN);
                memoryGroup[childHighdensityKey].Value = x.DN;
                memoryGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                discoveryData.Add(memoryGroup);
                x.MemoryList.ForEach(
                    y =>
                {
                    var memory = this.CreateMemory(y);
                    memory[this.PartChildGroupKey].Value =
                        memoryGroup[this.PartChildGroupKey].Value;
                    memory[childHighdensityKey].Value  = x.DN;
                    memory[this.PartGroupKey].Value    = childHighdensityGroupKey;
                    memory[this.ComputerKey].Value     = model.DN;
                    memory[this.HuaweiServerKey].Value = model.DN;
                    discoveryData.Add(memory);
                });

                #endregion

                #region Disk

                var diskGroup = this.CreateLogicalChildGroup(this.DiskGroupClass, model.DN, x.DN);
                diskGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                diskGroup[childHighdensityKey].Value = x.DN;
                discoveryData.Add(diskGroup);
                x.DiskList.ForEach(
                    y =>
                {
                    var disk = this.CreateDisk(y);
                    disk[this.PartChildGroupKey].Value = diskGroup[this.PartChildGroupKey].Value;
                    disk[childHighdensityKey].Value    = x.DN;
                    disk[this.PartGroupKey].Value      = childHighdensityGroupKey;
                    disk[this.ComputerKey].Value       = model.DN;
                    disk[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(disk);
                });

                #endregion

                #region Raid

                var raidGroup = this.CreateLogicalChildGroup(this.RaidGroupClass, model.DN, x.DN);
                raidGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                raidGroup[childHighdensityKey].Value = x.DN;
                discoveryData.Add(raidGroup);
                x.RaidList.ForEach(
                    y =>
                {
                    var raid = this.CreateRaidControl(y);
                    raid[this.PartChildGroupKey].Value = raidGroup[this.PartChildGroupKey].Value;
                    raid[childHighdensityKey].Value    = x.DN;
                    raid[this.PartGroupKey].Value      = childHighdensityGroupKey;
                    raid[this.HuaweiServerKey].Value   = model.DN;
                    raid[this.ComputerKey].Value       = model.DN;
                    discoveryData.Add(raid);
                });

                #endregion
            });

            #endregion

            if (!this.ExsitsHighdensityServer(model.DN))
            {
                discoveryData.Commit(this.MontioringConnector);
            }
            else
            {
                discoveryData.Overwrite(this.MontioringConnector);
            }
        }
Example #12
0
        /// <summary>
        /// Application Entry Point
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Write Header
            Console.WriteLine("AP.F5.LTM.Discovery, ©A.Patrick 2017-2018");
            Console.WriteLine("Discovers F5 LTM Classes for SCOM.");
            Console.WriteLine("");

            // First Thing is to get the Managment Server Name from the config file (if it exists).
            m_managementServer = GetManagementServer();

            // Get Devices (If Device File Exists
            if (File.Exists(m_deviceFileName))
            {
                // Write Discovered Data to SCOM Database ( For Relationships
                log.Info("Creating Inbound Connector to " + m_managementServer + "...");

                // Get Management Group
                SCOM.m_managementGroup = new ManagementGroup(m_managementServer);

                // Create Our Inbound Connector
                SCOM.CreateConnector();
                log.Info("Inbound Connector Created..." + m_managementServer + "...");

                // Has Conenctor been created successfully
                if (SCOM.m_monitoringConnector.Initialized)
                {
                    // Log Progress
                    log.Info("Starting Device Discovery...");
                    Console.WriteLine();
                    // Get Devices from SCOM
                    SCOM_DeviceList = new SCOM_Devices();
                    // Get Devices from CSV
                    GetDevices();
                    // Log Progress
                    log.Info(SCOM_DeviceList.Items.Count + " Devices Found in SCOM...");
                    log.Info(DeviceList.Count + " Devices Found in CSV...");
                    Console.WriteLine();

                    // Get Device Groups / Traffic Groups
                    log.Info("Get Device Groups / Traffic Groups from...");
                    GetDeviceGroups();

                    // Create Discovery Data
                    Console.WriteLine();
                    log.Info("Creating Discovery Data...");
                    // Add Data to Discovery Data
                    AddDataToDiscoveryData();
                    // Write Discovery Data
                    log.Info("Writing Discovery Data to " + m_managementServer);
                    discoData.Overwrite(SCOM.m_monitoringConnector);

                    // Write Discovered Relationship Data to SCOM Database
                    Console.WriteLine();
                    log.Info("Creating Relationship Data...");
                    CreateRelationships();
                    // Write Relationship Discovery Data
                    log.Info("Writing Relationship Data to " + m_managementServer);
                    relationshipData.Overwrite(SCOM.m_monitoringConnector);


                    Console.WriteLine();
                }
                else
                {
                    log.Fatal("Couldn't Initialize Inbound SCOM Connector!");
                }

                // Free Connector
                SCOM.m_monitoringConnector.Uninitialize();
                SCOM.m_monitoringConnector = null;
            }
            else
            {
                log.Fatal("Couldn't Initialize Inbound SCOM Connector!");
                Environment.Exit(5);
            }
        }
Example #13
0
        private void PerformRelationshipCleanup(ManagementPackClass seedClass, CreatableEnterpriseManagementObject seedInstance, MonitoringObject monitoringObject)
        {
            // it's so complex, because the new instance may not exist
            EnterpriseManagementObject realSeedInstance;

            string criteriaString = string.Empty;

            foreach (var property in seedInstance.GetProperties())
            {
                if (property.Key)
                {
                    if (criteriaString == string.Empty)
                    {
                        criteriaString = property.Name + "='" + seedInstance[property] + "'";
                    }
                    else
                    {
                        criteriaString += " AND " + property.Name + "='" + seedInstance[property] + "'";
                    }
                }
            }

            var searchQuery          = new EnterpriseManagementObjectCriteria(criteriaString, seedClass);
            var realSeedInstanceList = _managementGroup.EntityObjects.GetObjectReader <EnterpriseManagementObject>(searchQuery, ObjectQueryOptions.Default);

            realSeedInstance = realSeedInstanceList.FirstOrDefault();

            if (realSeedInstance == null)
            {
                return;
            }

            var removalDiscovery = new IncrementalDiscoveryData();

            // Management Point
            bool commitOverwrite = false;
            var  allMAPRelations = _managementGroup.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(realSeedInstance.Id, _relToClearMap, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);
            var  allHSRelations  = _managementGroup.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(realSeedInstance.Id, _relToClearHs, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);

            foreach (var rel in allMAPRelations)
            {
                if (rel.SourceObject.Id != monitoringObject.Id)
                {
                    // remove this relationship
                    removalDiscovery.Remove(rel);
                    commitOverwrite = true;
                }
            }

            foreach (var rel in allHSRelations)
            {
                if (rel.SourceObject.Id != monitoringObject.Id)
                {
                    // remove this relationship
                    removalDiscovery.Remove(rel);
                    commitOverwrite = true;
                }
            }

            if (commitOverwrite)
            {
                removalDiscovery.Overwrite(_managementGroup);
            }
        }
        /// <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);
            }
        }
Example #15
0
        /// <summary>
        /// Main Application Entry Point
        /// </summary>
        /// <param name="args">None</param>
        static void Main(string[] args)
        {
            // Write Header
            Console.WriteLine("AP.F5.Base.Discovery, ©A.Patrick 2017-2018");
            Console.WriteLine("Discovers F5 Devices for SCOM.");
            Console.WriteLine("");

            // First Thing is to get the Managment Server Name from the config file (if it exists).
            LoadConfig();

            // Get Devices (If Device File Exists
            if (File.Exists(m_deviceFileName))
            {
                // Write Discovered Data to SCOM Database ( For Relationships
                log.Info("Creating Inbound Connector to " + m_managementServer + "...");

                // Get Management Group
                SCOM_Functions.m_managementGroup = new ManagementGroup(m_managementServer);
                // Create Our Inbound Connector
                SCOM_Functions.CreateConnector();
                if (SCOM_Functions.m_monitoringConnector.Initialized)
                {
                    // Get Devices (and add to Discovery Data)
                    log.Info("Starting Device Discovery...");
                    GetDevices();

                    try
                    {
                        // Write Discovered Data to SCOM Database
                        log.Info("Writing Discovery Data to " + m_managementServer);
                        if (m_discoveryType == "snapshot")
                        {
                            snapshotDiscoveryData.Overwrite(SCOM_Functions.m_monitoringConnector);
                        }
                        else
                        {
                            incrementalDiscoveryData.Overwrite(SCOM_Functions.m_monitoringConnector);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                    }

                    // Free Connector
                    SCOM_Functions.m_monitoringConnector.Uninitialize();
                    SCOM_Functions.m_monitoringConnector = null;
                }
                else
                {
                    log.Fatal("Couldn't Initialize Inbound SCOM Connector!");
                    Environment.Exit(5);
                }
            }
            else
            {
                log.Fatal("Could not find device file, " + m_deviceFileName);
                Environment.Exit(5);
            }

            log.Info("Discovery Finished...");
        }
        /// <summary>
        /// The insert detials.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public void InsertDetials(RackServer model)
        {
            var discoveryData = new IncrementalDiscoveryData();
            var baseComputer  = this.GetComputerByDeviceId(model.DeviceId);

            // 存在则更新
            if (baseComputer != null)
            {
                this.UpdateRack(model);
                return;
            }
            else
            {
                var newBaseComputer = this.CreateComputer(model.DeviceId);
                discoveryData.Add(newBaseComputer);
            }

            var rackServer = this.CreateRackServer(model);

            rackServer[this.ComputerKey].Value = model.DeviceId;
            discoveryData.Add(rackServer);

            #region Fan

            var fanGroup = this.CreateLogicalGroup(this.FanGroupClass, model.DeviceId);
            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.DeviceId;
                fan[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(fan);
            });

            #endregion

            #region PSU

            var powerSupplyGroup = this.CreateLogicalGroup(this.PowerSupplyGroupClass, model.DeviceId);
            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.DeviceId;
                powerSupply[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(powerSupply);
            });

            #endregion

            #region Raid

            var raidGroup = this.CreateLogicalGroup(this.RaidGroupClass, model.DeviceId);
            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.DeviceId;
                raid[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(raid);
            });

            #endregion

            #region CPU

            var cpuGroup = this.CreateLogicalGroup(this.CpuGroupClass, model.DeviceId);
            discoveryData.Add(cpuGroup);
            model.CPUList.ForEach(
                x =>
            {
                var cpu = this.CreateCpu(x);
                cpu[this.PartGroupKey].Value    = cpuGroup[this.PartGroupKey].Value;
                cpu[this.HuaweiServerKey].Value = model.DeviceId;
                cpu[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(cpu);
            });

            #endregion

            #region Memory

            var memoryGroup = this.CreateLogicalGroup(this.MemoryGroupClass, model.DeviceId);
            discoveryData.Add(memoryGroup);
            model.MemoryList.ForEach(
                x =>
            {
                var memory = this.CreateMemory(x);
                memory[this.PartGroupKey].Value    = memoryGroup[this.PartGroupKey].Value;
                memory[this.HuaweiServerKey].Value = model.DeviceId;
                memory[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(memory);
            });

            #endregion

            #region Disk

            var diskGroup = this.CreateLogicalGroup(this.PhysicalDiskGroupClass, model.DeviceId);
            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.DeviceId;
                disk[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(disk);
            });

            #endregion

            if (!this.ExsitsRackServer(model.DeviceId))
            {
                discoveryData.Commit(this.MontioringConnector);
            }
            else
            {
                discoveryData.Overwrite(this.MontioringConnector);
            }
        }
        /// <summary>
        /// Updates the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="isPolling">if set to <c>true</c> [is polling].</param>
        /// <exception cref="System.Exception"></exception>
        public void Sync(Appliance model, bool isPolling)
        {
            try
            {
                HWLogger.Service.Debug($"Start UpdateAppliance. [isPolling:{isPolling}]");
                var devices        = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(ApplianceClass, ObjectQueryOptions.Default).ToList();
                var exsitAppliance = devices.FirstOrDefault();
                if (exsitAppliance == null)
                {
                    throw new Exception($"Can not find the Appliance ");
                }
                var discoveryData = new IncrementalDiscoveryData();
                this.UpdateAppliance(model, exsitAppliance);
                discoveryData.Add(exsitAppliance);

                #region EnclosureCollection
                var enclosureCollections = exsitAppliance.GetRelatedMonitoringObjects(this.EnclosureCollectionClass);
                if (enclosureCollections.Any())
                {
                    var exsit = enclosureCollections.First();
                    this.UpdateEnclosureCollection(model.EnclosureCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var enclosureCollection = this.CreateEnclosureCollection(model.EnclosureCollection);
                    discoveryData.Add(enclosureCollection);
                }
                #endregion

                #region ServerCollection
                var serverCollections = exsitAppliance.GetRelatedMonitoringObjects(this.ServerCollectionClass);
                if (serverCollections.Any())
                {
                    var exsit = serverCollections.First();
                    this.UpdateServerCollection(model.ServerCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var serverCollection = this.CreateServerCollection(model.ServerCollection);
                    discoveryData.Add(serverCollection);
                }
                #endregion

                #region EventCollection
                var eventCollections = exsitAppliance.GetRelatedMonitoringObjects(this.EventCollectionClass);
                if (eventCollections.Any())
                {
                    var exsit = eventCollections.First();
                    this.UpdateEventCollection(model.EventCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var eventCollection = this.CreateEventCollection(model.EventCollection);
                    discoveryData.Add(eventCollection);
                }
                #endregion

                #region PerformanceCollection
                var performanceCollections = exsitAppliance.GetRelatedMonitoringObjects(this.PerformanceCollectionClass);
                if (performanceCollections.Any())
                {
                    var exsit = performanceCollections.First();
                    this.UpdatePerformanceCollection(model.PerformanceCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var performanceCollection = this.CreatePerformanceCollection(model.PerformanceCollection);
                    discoveryData.Add(performanceCollection);
                }
                #endregion

                #region FusionDirectorCollection
                var fusionDirectorCollections = exsitAppliance.GetRelatedMonitoringObjects(this.FusionDirectorCollectionClass);
                if (fusionDirectorCollections.Any())
                {
                    var exsit = fusionDirectorCollections.First();
                    this.UpdateFusionDirectorCollection(model.FusionDirectorCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var fusionDirectorCollection = this.CreateFusionDirectorCollection(model.FusionDirectorCollection);
                    discoveryData.Add(fusionDirectorCollection);
                }
                #endregion

                discoveryData.Overwrite(this.MontioringConnector);
                HWLogger.Service.Info($"UpdateAppliance finish.");
            }
            catch (Exception e)
            {
                HWLogger.Service.Error(e, $"Update Appliance Error. [isPolling:{isPolling}]");
            }
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                if (RetentionDays == 0)
                {
                    throw new ArgumentNullException("No retention days set.");
                }

                //setup event log access
                if (!EventLog.SourceExists(strEventLogTitle))
                {
                    EventLog.CreateEventSource(strEventLogTitle, "Operations Manager");
                }

                EventLog.WriteEntry(strEventLogTitle, "Starting Project CI grooming...");

                emg = new EnterpriseManagementGroup("localhost");

                var licenseExpiration = checkLicense(); //method will throw an exception if no license exists.
                EventLog.WriteEntry(strEventLogTitle, string.Format("License Expiration: {0}", licenseExpiration));

                //Cireson Project (Cireson.ProjectAutomation.Library) (Cireson.ProjectAutomation.Project) (dabf07ea-6047-b6d7-f8d3-e88ac1d260e9)
                ManagementPackClass mpcProject = emg.EntityTypes.GetClass(new Guid("dabf07ea-6047-b6d7-f8d3-e88ac1d260e9"));

                var oldProjects = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(new EnterpriseManagementObjectCriteria(
                                                                                                     "LastModified < '" + DateTime.Now.AddDays(-RetentionDays).ToUniversalTime() + "'", mpcProject), ObjectQueryOptions.Default);
                IncrementalDiscoveryData iddDeletePending = new IncrementalDiscoveryData();

                EventLog.WriteEntry("Checking for Project CIs with a last modified date older than: {0}", DateTime.Now.AddDays(-RetentionDays).ToUniversalTime().ToString());

                //get PendingDelete enum
                //Pending Delete (System.Library) (System.ConfigItem.ObjectStatusEnum.PendingDelete) (47101e64-237f-12c8-e3f5-ec5a665412fb)
                var pendingDelete = emg.EntityTypes.GetEnumeration(new Guid("47101e64-237f-12c8-e3f5-ec5a665412fb"));

                exceptionsList = new List <Exception>();

                foreach (EnterpriseManagementObject project in oldProjects)
                {
                    try
                    {
                        project[null, "ObjectStatus"].Value = pendingDelete;
                        iddDeletePending.Add(project);
                    }
                    catch (EnterpriseManagementException ex)
                    {
                        exceptionsList.Add(new ProjectCIGroomingException(string.Format("Failed to set 'Pending Delete' object status on {0}.", project.Name), ex));
                    }
                }

                iddDeletePending.Overwrite(emg);

                if (exceptionsList.Count > 0)
                {
                    throw new AggregateException("One or more errors occured grooming Project CIs.", exceptionsList);
                }
            }
            catch (AggregateException ex)
            {
                TrackData(ex.Message);

                StringBuilder exceptionStrings = new StringBuilder();
                foreach (var innerEx in ex.InnerExceptions)
                {
                    exceptionStrings.AppendLine(string.Format(strExceptionMessage, innerEx.Message, innerEx.InnerException, innerEx.StackTrace, innerEx.Source));
                }

                EventLog.WriteEntry(strEventLogTitle, string.Format(ex.Message + "\r\n\r\n" + "The following projects failed:\r\n\r\n" + exceptionStrings.ToString()));
            }
            catch (EnterpriseManagementException ex)
            {
                TrackData(ex);
                TrackData(ex.Message);
                throw;
            }
            finally
            {
                if (emg != null)
                {
                    emg.Dispose();
                }
            }

            return(ActivityExecutionStatus.Closed);
        }
        /// <summary>
        /// The update kun lun.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <exception cref="Exception">Can not find the server</exception>
        public void UpdateKunLun(KunLunServer model)
        {
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateKunLun");
            var oldServer = this.GetKunLunServer(model.DN);

            if (oldServer == null)
            {
                throw new Exception($"Can not find the server:{model.DN}");
            }
            var propertys     = this.KunLunClass.PropertyCollection; // 获取到class的属性
            var discoveryData = new IncrementalDiscoveryData();

            oldServer[this.DisplayNameField].Value     = model.Name;
            oldServer[propertys["Status"]].Value       = model.Status;
            oldServer[propertys["Vendor"]].Value       = "HUAWEI";
            oldServer[propertys["Manufacturer"]].Value = model.Manufacturer;
            oldServer[propertys["UUID"]].Value         = model.UUID;
            oldServer[propertys["IPAddress"]].Value    = model.IpAddress;

            // oldBlade[propertys["iBMCVersion"]].Value = model.Version;
            oldServer[propertys["CPLDVersion"]].Value    = string.Empty;
            oldServer[propertys["UbootVersion"]].Value   = string.Empty;
            oldServer[propertys["ProductSn"]].Value      = model.ProductSN;
            oldServer[propertys["MemoryCapacity"]].Value = model.MemoryCapacity;
            oldServer[propertys["CPUNums"]].Value        = model.CPUNums;
            oldServer[propertys["CPUCores"]].Value       = model.CPUCores;

            // oldBlade[propertys["ServerName"]].Value = model.ServerName;
            oldServer[propertys["BMCMacAddr"]].Value = model.BmcMacAddr;
            oldServer[propertys["eSight"]].Value     = model.ESight;
            discoveryData.Add(oldServer);

            var fanGroup = oldServer.GetRelatedMonitoringObjects(this.FanGroupClass).First();

            discoveryData.Add(fanGroup);

            var relatedFanObjects = fanGroup.GetRelatedMonitoringObjects(this.FanClass);
            var deleteFan         = relatedFanObjects.Where(
                x => model.FanList.All(y => y.UUID != x[this.FanClass.PropertyCollection["UUID"]].Value.ToString()))
                                    .ToList();

            deleteFan.ForEach(x => { discoveryData.Remove(x); });

            model.FanList.ForEach(
                x =>
            {
                var fan = this.UpdateFan(x);
                if (fan == null)
                {
                    var newFan = this.CreateFan(x);
                    newFan[this.ComputerKey].Value     = model.DN;
                    newFan[this.HuaweiServerKey].Value = model.DN;
                    newFan[this.PartGroupKey].Value    = fanGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newFan);
                }
                else
                {
                    discoveryData.Add(fan);
                }
            });

            #region PSU

            var psuGroup = oldServer.GetRelatedMonitoringObjects(this.PowerSupplyGroupClass).First();
            discoveryData.Add(psuGroup);

            var relatedPsuObjects = psuGroup.GetRelatedMonitoringObjects(this.PowerSupplyClass);
            var deletePsu         = relatedPsuObjects.Where(
                x => model.PowerSupplyList.All(
                    y => y.UUID != x[this.PowerSupplyClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deletePsu.ForEach(x => { discoveryData.Remove(x); });
            model.PowerSupplyList.ForEach(
                x =>
            {
                var psu = this.UpdatePowerSupply(x);
                if (psu == null)
                {
                    var newpsu = this.CreatePowerSupply(x);
                    newpsu[this.ComputerKey].Value     = model.DN;
                    newpsu[this.HuaweiServerKey].Value = model.DN;
                    newpsu[this.PartGroupKey].Value    = psuGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newpsu);
                }
                else
                {
                    discoveryData.Add(psu);
                }
            });

            #endregion

            #region Disk

            var diskGroup = oldServer.GetRelatedMonitoringObjects(this.PhysicalDiskGroupClass).First();
            discoveryData.Add(diskGroup);

            var relatedDiskObjects = diskGroup.GetRelatedMonitoringObjects(this.PhysicalDiskClass);
            var deleteDisk         = relatedDiskObjects.Where(
                x => model.DiskList.All(
                    y => y.UUID != x[this.PhysicalDiskClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deleteDisk.ForEach(x => { discoveryData.Remove(x); });
            model.DiskList.ForEach(
                y =>
            {
                var disk = this.UpdateDisk(y);
                if (disk == null)
                {
                    var newDisk = this.CreateDisk(y);
                    newDisk[this.ComputerKey].Value     = model.DN;
                    newDisk[this.HuaweiServerKey].Value = model.DN;
                    newDisk[this.PartGroupKey].Value    = diskGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newDisk);
                }
                else
                {
                    discoveryData.Add(disk);
                }
            });

            #endregion

            #region Raid

            var raidGroup = oldServer.GetRelatedMonitoringObjects(this.RaidGroupClass).First();
            discoveryData.Add(raidGroup);

            var relatedRaidObjects = raidGroup.GetRelatedMonitoringObjects(this.RaidClass);
            var deleteRaid         = relatedRaidObjects.Where(
                x => model.RaidList.All(
                    y => y.UUID != x[this.RaidClass.PropertyCollection["UUID"]].Value.ToString()))
                                     .ToList();
            deleteRaid.ForEach(x => { discoveryData.Remove(x); });
            model.RaidList.ForEach(
                y =>
            {
                var raid = this.UpdateRaidControl(y);
                if (raid == null)
                {
                    var newRaid = this.CreateRaidControl(y);
                    newRaid[this.ComputerKey].Value     = model.DN;
                    newRaid[this.HuaweiServerKey].Value = model.DN;
                    newRaid[this.PartGroupKey].Value    = raidGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newRaid);
                }
                else
                {
                    discoveryData.Add(raid);
                }
            });

            #endregion

            discoveryData.Overwrite(this.MontioringConnector);
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateKunLun");
        }
Example #20
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                //setup event log access
                if (!EventLog.SourceExists(strEventLogTitle))
                {
                    EventLog.CreateEventSource(strEventLogTitle, "Operations Manager");
                }

                startTime = DateTime.UtcNow; //set the start time

                EventLog.WriteEntry(strEventLogTitle, string.Format("Starting {0}.", strEventLogTitle));

                exceptionsList = new List <Exception>();

                #region setup connection to EMG and get objects
                emg = new EnterpriseManagementGroup("localhost");

                //sleep so I can debug...
                //System.Threading.Thread.Sleep(10000);

                setupEnterpriseManagementObjects();

                #endregion

                var licenseExpiration = checkLicense();
                EventLog.WriteEntry(strEventLogTitle, string.Format("License Expiration: {0}", licenseExpiration));

                #region Connect to Project Server.
                //get connector credentails
                NetworkCredential creds = NetworkCredentialsHelper.GetProjectCredentials(emoConnector[null, "RunAsAccount"].Value.ToString(), emoConnector[null, "Id"].ToString(), emg.Name);
                projectConnector = new ProjectConnector(emoConnector[null, "ProjectServerURL"].Value.ToString(), creds);
                projectConnector.Connect();
                #endregion


                //setup the bucket
                iddBucket = new IncrementalDiscoveryData();

                if ((bool)emoProjectAutomationSettings[null, "IsChangeProcessingEnabled"].Value)
                {
                    processChangeRequests();
                }
                else
                {
                    processReleaseRecords();
                }

                iddBucket.Overwrite(emg); //commit changes to DB and dispose connection.

                if (exceptionsList.Count > 0)
                {
                    throw new AggregateException("Errors occured while processing Project Tasks.", exceptionsList);
                }

                EventLog.WriteEntry(strEventLogTitle, string.Format("Ending {0}.  Elapsed Time: {1} seconds", strEventLogTitle, getRunTime(startTime).Seconds));
            }
            catch (AggregateException ex)
            {
                TrackData(ex.Message);

                StringBuilder exceptionStrings = new StringBuilder();
                foreach (var innerEx in ex.InnerExceptions)
                {
                    exceptionStrings.AppendLine(string.Format(strExceptionMessage, innerEx.Message, innerEx.InnerException, innerEx.StackTrace, innerEx.Source));
                }

                EventLog.WriteEntry(strEventLogTitle, string.Format("{0}\r\n\r\nElapsed Time: {1} seconds.\r\n\r\nExceptions List: {2}", ex.Message, getRunTime(startTime).Seconds, exceptionsList.ToString()));
            }
            catch (EnterpriseManagementException ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                throw;
            }
            catch (Exception ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                throw;
            }
            finally
            {
                if (emg != null)
                {
                    emg.Dispose();
                }
            }
            return(ActivityExecutionStatus.Closed);
        }