void setProjectConnectorRelationship(ref CreatableEnterpriseManagementObject project)
        {
            CreatableEnterpriseManagementRelationshipObject cemroConnector =
                new CreatableEnterpriseManagementRelationshipObject(emg, mprRelationships.First(r => r.Name == "System.ProjectConfigItemRelatesToProjectConnector"));

            cemroConnector.SetSource(emoConnector);
            cemroConnector.SetTarget(project);
            iddObjects.Add(cemroConnector);
        }
예제 #2
0
        private void brd_Loc_Add_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (LocationTreeView.SelectedItem != null)
                {
                    Guid guid = new Guid("2d30268b-c9d8-b9f5-93ff-5b95b2cd3e4d");
                    Collection <IDataItem> ItemsCol = new Collection <IDataItem>();
                    Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.LaunchAddInstancePickerDialog(ItemsCol, guid);
                    if (ItemsCol.Count() == 1)
                    {
                        TreeViewItem TR = (TreeViewItem)LocationTreeView.SelectedItem;
                        // Get an object by GUID
                        Guid G = new Guid(TR.Tag.ToString());
                        EnterpriseManagementObject treeviewEMO = emg.EntityObjects.GetObject <EnterpriseManagementObject>(G, ObjectQueryOptions.Default);

                        IDataItem targetInstanceIDataItem = ItemsCol[0];
                        //IDataItem targetInstanceIDataItem = this.LocPiker.Instance;
                        Guid gId = (Guid)targetInstanceIDataItem["$Id$"];
                        Trace.WriteLine(DateTime.Now + " : " + "Id : " + gId); //+ " ID : " + targetInstanceIDataItem["ID"]);
                        EnterpriseManagementObject pickerEMO = emg.EntityObjects.GetObject <EnterpriseManagementObject>(gId, ObjectQueryOptions.Default);
                        Trace.WriteLine(DateTime.Now + " : " + "Values for create Rel : " + treeviewEMO.DisplayName + " : " + pickerEMO.DisplayName + " picker.Id : " + pickerEMO.Id.ToString());
                        CreatableEnterpriseManagementRelationshipObject relationship = new CreatableEnterpriseManagementRelationshipObject(emg, relationClass);
                        relationship.SetSource(treeviewEMO);
                        relationship.SetTarget(pickerEMO);
                        relationship.Commit();

                        //FillTreeView.Now(emg, locationClass, relationClass, LocationTreeView);
                        Fill();
                    }
                    else if (ItemsCol.Count() > 1)
                    {
                        MessageBox.Show("Please select only ONE location!", "Multiselection!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else if (ItemsCol.Count() == 0)
                    {
                        MessageBox.Show("Please select location!", "No location selected!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("Please select location!", "No location selected!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    Trace.WriteLine(DateTime.Now + " : " + "Not have Values for create Rel");
                }
            }
            catch (Exception exc)
            {
                Trace.WriteLine(DateTime.Now + " : " + "Error in Picker Dialog " + exc.Message);
            }
        }
        void setProjectHasOwnerRelationship(string nameId, ref CreatableEnterpriseManagementObject cemoProject)
        {
            //get the owner of the project as an EMO.
            EnterpriseManagementObjectCriteria ecoOwnerCriteria = new EnterpriseManagementObjectCriteria(string.Format(xmlOwnerCriteria, nameId),
                                                                                                         mpcClasses.First(mpc => mpc.Name == "Microsoft.AD.UserBase"), managementPacks.First(mp => mp.Name == "Microsoft.Windows.Library"), emg);
            EnterpriseManagementObject emoOwner = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(ecoOwnerCriteria, ObjectQueryOptions.Default).FirstOrDefault();

            if (emoOwner != null)
            {
                //set up the relationship between project owner and project.
                CreatableEnterpriseManagementRelationshipObject cemroOwner =
                    new CreatableEnterpriseManagementRelationshipObject(emg, mprRelationships.First(r => r.Name == "Cireson.ProjectAutomation.ProjectHasOwner"));
                cemroOwner.SetSource(cemoProject);
                cemroOwner.SetTarget(emoOwner);
                iddObjects.Add(cemroOwner);
            }
        }
예제 #4
0
        private void OnSubmitted(object sender, FormCommandExecutedEventArgs e)
        {
            //try
            //{
            //    CurrentDataItem = this.DataContext as IDataItem;

            //    if (!((bool)CurrentDataItem["$IsNew$"]))
            //    {
            //        CurrentEMO = emg.EntityObjects.GetObject<EnterpriseManagementObject>((Guid)CurrentDataItem["$Id$"], ObjectQueryOptions.Default);


            //    }
            //    else
            //    {

            //    }
            //}
            //catch (Exception exc)
            //{
            //    System.Windows.MessageBox.Show(DateTime.Now + " : " + "Error in OnSubmitted() " + exc.Message);
            //}


            try
            {
                CurrentDataItem = this.DataContext as IDataItem;
                CurrentEMO      = emg.EntityObjects.GetObject <EnterpriseManagementObject>((Guid)CurrentDataItem["$Id$"], ObjectQueryOptions.Default);
                //Связываем добавленные CI
                if (CItoAddСollection.Count > 0)
                {
                    foreach (EnterpriseManagementObject CI_EMO in CItoAddСollection)
                    {
                        CreatableEnterpriseManagementRelationshipObject relationHAtoCI = new CreatableEnterpriseManagementRelationshipObject(emg, relConfigItemRefRack);
                        relationHAtoCI.SetSource(CI_EMO);
                        relationHAtoCI.SetTarget(CurrentEMO);
                        relationHAtoCI.Commit();
                    }
                }
            }
            catch (Exception exc)
            {
                Trace.WriteLine(DateTime.Now + " : " + "Error in OnSubmitted() " + exc.Message);
            }
        }
예제 #5
0
        //После создания HA - привязываем к нему CI из коллекции CItoAddCollection
        private void OnSubmitted(object sender, FormCommandExecutedEventArgs e)
        {
            try
            {
                CurrentDataItem = this.DataContext as IDataItem;
                CurrentEMO      = emg.EntityObjects.GetObject <EnterpriseManagementObject>((Guid)CurrentDataItem["$Id$"], ObjectQueryOptions.Default);
                //Связываем добавленные CI
                if (CItoAddСollection.Count > 0)
                {
                    foreach (EnterpriseManagementObject CI_EMO in CItoAddСollection)
                    {
                        CreatableEnterpriseManagementRelationshipObject relationHAtoCI = new CreatableEnterpriseManagementRelationshipObject(emg, relationHAtoCIClass);
                        relationHAtoCI.SetSource(CurrentEMO);
                        relationHAtoCI.SetTarget(CI_EMO);
                        relationHAtoCI.Commit();
                    }
                }



                //CurrentEMO.DisplayName = CurrentEMO[null,"AssetKey"].Value.ToString() + this.TemplateCatalogItem.sip.Instance["MakeModel"].ToString();
                //CurrentEMO.Commit();


                //Link Model
                //ManagementPack mpHA = emg.GetManagementPack("SMCenter.HardwareAssetManagement.Library", "75b45bd6835084b1", new Version());
                //HAClass = emg.EntityTypes.GetClass("SMCenter.HardwareAsset", mpHA);
                //ManagementPack mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version());
                //ConfItemClass = emg.EntityTypes.GetClass("System.ConfigItem", mpSystem);
                //ManagementPackRelationship relationHAtoModelClass = emg.EntityTypes.GetRelationshipClass("SMCenter.HardwareAssetIsHardwareCatalogItem", mpHA);
                //CreatableEnterpriseManagementRelationshipObject relationHAtoModel = new CreatableEnterpriseManagementRelationshipObject(emg, relationHAtoModelClass);
                //Trace.WriteLine(DateTime.Now + " : " + "CurrentEmo " + CurrentEMO.FullName);
                //Trace.WriteLine(DateTime.Now + " : " + "CurrentModelEmo " + CurrentModelEMO.FullName);
                //relationHAtoModel.SetSource(CurrentEMO);
                //relationHAtoModel.SetTarget(CurrentModelEMO);
                //relationHAtoModel.Commit();
            }
            catch (Exception exc)
            {
                Trace.WriteLine(DateTime.Now + " : " + "Error in OnSubmitted() " + exc.Message);
            }
        }
예제 #6
0
        private void brd_Loc_Create_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (LocationTreeView.SelectedItem != null)
            {
                CreatableEnterpriseManagementObject newLocation = new CreatableEnterpriseManagementObject(emg, locationClass);

                //Add some property values
                newLocation[locationClass, "DisplayName"].Value = "Add some info";
                newLocation.Commit();

                //Treeview Item - Parent Item
                TreeViewItem TR = (TreeViewItem)LocationTreeView.SelectedItem;
                // Get an object by GUID
                Guid G = new Guid(TR.Tag.ToString());
                EnterpriseManagementObject treeviewEMO = emg.EntityObjects.GetObject <EnterpriseManagementObject>(G, ObjectQueryOptions.Default);

                CreatableEnterpriseManagementRelationshipObject relationship = new CreatableEnterpriseManagementRelationshipObject(emg, relationClass);
                relationship.SetSource(treeviewEMO);
                relationship.SetTarget(newLocation);
                relationship.Commit();

                //FillTreeView.Now(emg, locationClass, relationClass, LocationTreeView);
                Fill();


                //Convert EnterpriseManagementObject to IDataItem
                EnterpriseManagementObjectDataType dataType = new EnterpriseManagementObjectDataType(locationClass);
                IDataItem newlocationDataItem = dataType.CreateProxyInstance(newLocation);

                //Open Console form for created object
                //ConsoleContextHelper.Instance.PopoutForm(itemIdentity);
                Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(newlocationDataItem);
            }
            else
            {
                MessageBox.Show("Please select parent location!", "No location selected", MessageBoxButton.OK, MessageBoxImage.Warning);
                Trace.WriteLine(DateTime.Now + " : " + "Not have Values for create Rel");
            }
        }
예제 #7
0
        private void lbOk_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //IDataItem DI = this.TemplateSoftwareTitle.sipInstance;
                //Guid CurrentNodeId = (Guid)DI["$Id$"];
                //EnterpriseManagementObject SoftwareTitle_EMO = emg.EntityObjects.GetObject<EnterpriseManagementObject>(CurrentNodeId, ObjectQueryOptions.Default);
                //MessageBox.Show(SoftwareTitle_EMO.Name);
                //MessageBox.Show(TemplateSoftwareTitle.mpClass.Name);

                if (this.txtDisplayName.Text != "" && this.txtDisplayName.Text != null)
                {
                    //ManagementPackClass classTask = ManagementGroup.EntityTypes.GetClass(“Task”, testMP)
                    CreatableEnterpriseManagementObject Version = new CreatableEnterpriseManagementObject(emg, classSoftwareVersion);
                    //Version [classTask, “Id”].Value = Guid.NewGuid().ToString();
                    Version[classSoftwareVersion, "DisplayName"].Value = this.txtDisplayName.Text;

                    CreatableEnterpriseManagementRelationshipObject relationshipObject = new CreatableEnterpriseManagementRelationshipObject(emg, relSoftwareTitleHasSoftwareVersion);
                    relationshipObject.SetSource(EMO_SoftwareTitle);
                    relationshipObject.SetTarget(Version);

                    IncrementalDiscoveryData dd = new IncrementalDiscoveryData();
                    dd.Add(Version);            //target object
                    dd.Add(relationshipObject); //relationship object
                    dd.Commit(emg);
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Type SoftwareVersion DisplayName!", "Warning!!!", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Ok_MouseDown void error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }
        }
 private void OnSubmitted(object sender, FormCommandExecutedEventArgs e)
 {
     try
     {
         CurrentDataItem = this.DataContext as IDataItem;
         CurrentEMO      = emg.EntityObjects.GetObject <EnterpriseManagementObject>((Guid)CurrentDataItem["$Id$"], ObjectQueryOptions.Default);
         //Связываем добавленные User Objects
         Trace.WriteLine(DateTime.Now + " : " + "toAddCollection.Count " + toAddСollection.Count.ToString());
         if (toAddСollection.Count > 0)
         {
             foreach (EnterpriseManagementObject User_EMO in toAddСollection)
             {
                 CreatableEnterpriseManagementRelationshipObject userrelation = new CreatableEnterpriseManagementRelationshipObject(emg, userrelationClass);
                 userrelation.SetSource(User_EMO);
                 userrelation.SetTarget(CurrentEMO);
                 userrelation.Commit();
             }
         }
     }
     catch (Exception exc)
     {
         Trace.WriteLine(DateTime.Now + " : " + "Error in OnSubmitted() " + exc.Message);
     }
 }
예제 #9
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            //Used for idataitem (form mode, 1=new form, 2=edit form);
            int iMode = 0;

            //Set title for messageboxes
            string sAppTitle = "Assign Incident Directly To Analyst";

            //Connect to MG
            IServiceContainer       isContainer = (IServiceContainer)FrameworkServices.GetService(typeof(IServiceContainer));
            IManagementGroupSession imgSession  = (IManagementGroupSession)isContainer.GetService(typeof(IManagementGroupSession));

            if (imgSession == null)
            {
                MessageBox.Show("Failed to connect to the current session", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            EnterpriseManagementGroup emg = imgSession.ManagementGroup;

            //Get the incident class (System.WorkItem.Incident)
            ManagementPackClass classIncident = emg.EntityTypes.GetClass(new Guid("A604B942-4C7B-2FB2-28DC-61DC6F465C68"));

            //Microsoft.Windows.Library
            ManagementPack mpWindows =
                emg.ManagementPacks.GetManagementPack(new Guid("545131F0-58DE-1914-3A82-4FCAC9100A33"));

            //Get the Microsoft.AD.User class
            ManagementPackClass mpcADUser = emg.EntityTypes.GetClass("Microsoft.AD.User", mpWindows);

            //Return the currently selected incident reference
            NavigationModelNodeBase selincident = nodes[0];

            //Form mode (not new)?
            if (selincident.Location.AbsoluteUri.IndexOf("FormDisplay", 0) > 0)
            {
                iMode = 2;
            }

            //Get objects
            EnterpriseManagementObject emoSelIncident = null;
            IDataItem i = ConsoleContextHelper.Instance.GetFormDataContext(nodes[0]);

            //Get the analyst settings class and MP
            ManagementPack      mpSetting     = emg.ManagementPacks.GetManagementPack(new Guid("56d5c2d6-7e19-59ff-7a81-ac8a331fcb3f"));
            ManagementPackClass classSettings = mpSetting.GetClass("AssignSettingsClass");

            //Get the emo for the settings
            EnterpriseManagementObject emoSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(classSettings.Id, ObjectQueryOptions.Default);

            //TP names
            string sAssignedTo = "AssignedUser";
            string sActionLog  = "ActionLogs";

            if (emoSettings[classSettings, "AssignedUserAlias"].Value != null)
            {
                sAssignedTo = emoSettings[classSettings, "AssignedUserAlias"].Value.ToString();
            }
            if (emoSettings[classSettings, "ActionLogAlias"].Value != null)
            {
                sActionLog = emoSettings[classSettings, "ActionLogAlias"].Value.ToString();
            }

            //Check if new
            if (!(bool)i["$IsNew$"])
            {
                //Now get the guid of the selected workitem. Depending on the view type, the return will be different, so take it after the last "."
                //There are lots of ways of doing this, this is not the best way but it was the first I learnt and it works
                string strGuid = selincident.GetId().Substring(selincident.GetId().LastIndexOf('.') + 1);

                //Get the emo of the workitem via it's guid
                emoSelIncident = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strGuid), ObjectQueryOptions.Default);
            }
            //Creating new incident
            else
            {
                iMode = 1;
            }

            //Was task was run from an workitem opened for editing, as opposed to a list or view?
            if (selincident.Location.AbsoluteUri.IndexOf("FormDisplay", 0) != -1)
            {
                iMode = 2;
            }

            //Get the status guid
            Guid gStatus = Guid.NewGuid();

            try
            {
                //"New" status will throw an exception to must catch here
                if (i["Status"] != null)
                {
                    gStatus = (Guid)(i["Status"] as IDataItem)["Id"];
                }
            }
            catch
            {
            }

            //Get the incident class (System.WorkItem.Incident)
            ManagementPackClass mpcIncident = emg.EntityTypes.GetClass(new Guid("a604b942-4c7b-2fb2-28dc-61dc6f465c68"));

            //Check if the incident is closed
            if (gStatus == new Guid("bd0ae7c4-3315-2eb3-7933-82dfc482dbaf"))
            {
                MessageBox.Show("This incident cannot be reassigned as it has been closed.", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //Note - we are alllowing resolved incidents to be re-assigned, to prevent this, uncomment the following block:

            /*else if (gStatus == new Guid("2b8830b6-59f0-f574-9c2a-f4b4682f1681"))
             * {
             *  MessageBox.Show("This incident cannot be reassigned as it has been resolved.", sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
             *  return;
             * }
             */

            //Current assignee and Id
            string sId       = "";
            string sUser     = "";
            string sTierGuid = "";

            if (iMode == 0)
            {
                //View mode
                sUser = this.GetProperty(ref emg, emoSelIncident, ref mpcADUser, "DisplayName");
                sId   = emoSelIncident[mpcIncident, "Id"].Value.ToString();
                if (emoSelIncident[mpcIncident, "TierQueue"].Value != null)
                {
                    sTierGuid = ((ManagementPackEnumeration)emoSelIncident[mpcIncident, "TierQueue"].Value).Id.ToString();
                }
            }
            else
            {
                //New or edit form mode
                try
                {
                    //Get display name of current assignee
                    if (i[sAssignedTo] == null)
                    {
                        sUser = "******";
                    }
                    else
                    {
                        sUser = (string)(i[sAssignedTo] as IDataItem)["DisplayName"];
                    }
                }
                catch
                {
                    //Set no assignee
                    sUser = "******";
                }
                sId = (string)i["Id"];
                try
                {
                    //Check current tier queue enum value
                    if (i["TierQueue"] != null)
                    {
                        sTierGuid = ((Guid)(i["TierQueue"] as IDataItem)["Id"]).ToString();
                    }
                }
                catch
                {
                }
            }

            //Create a new instance of the form and set it up
            AssignForm af = new AssignForm();

            af.sTierGuid        = sTierGuid;
            af.Text             = "Assign incident " + sId + " directly to Analyst - currently assigned to " + sUser;
            af.textDefault.Text = sUser;
            af.emg = emg;

            //Show the analyst/tier selection form
            DialogResult dr = af.ShowDialog();

            if (dr != DialogResult.Cancel)
            {
                //Get the samaccountname from the right hand part of the combobox.text after the !
                string sADUserName = af.comboAnalysts.Text.Substring(af.comboAnalysts.Text.LastIndexOf("(") + 1);
                //Remove last )
                sADUserName = sADUserName.Substring(0, sADUserName.Length - 1);

                //Format to get the display name only from the left part - this is used for the actionlog entry
                string sADUserDisplayName = af.comboAnalysts.Text.Substring(0, af.comboAnalysts.Text.LastIndexOf("(")).Trim();

                try
                {
                    //Set the query for the user - note - usernames are assumed unique across configured domains
                    //If this is not the case, you need to customise these criteria to include a domain
                    string sADUserCriteria = String.Format(@"
                        <Criteria xmlns=""http://Microsoft.EnterpriseManagement.Core.Criteria/"">
                        <Reference Id=""Microsoft.Windows.Library"" PublicKeyToken=""{0}"" Version=""{1}"" Alias=""MSWinLib"" />
                        <Expression>
                        <SimpleExpression>
                        <ValueExpressionLeft>
                        <Property>$Target/Property[Type='MSWinLib!Microsoft.AD.User']/UserName$</Property>
                        </ValueExpressionLeft>
                        <Operator>Equal</Operator>
                        <ValueExpressionRight>
                        <Value>" + sADUserName + @"</Value>
                        </ValueExpressionRight>
                        </SimpleExpression>
                        </Expression>
                        </Criteria>
                        ", mpWindows.KeyToken, mpWindows.Version.ToString());

                    //Object query options
                    ObjectQueryOptions objQueryOpts = new ObjectQueryOptions();
                    objQueryOpts.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered;
                    objQueryOpts.DefaultPropertyRetrievalBehavior = ObjectPropertyRetrievalBehavior.All;
                    //We are searching via samAccountName so there will be only 1 item
                    objQueryOpts.MaxResultCount = 1;

                    //Get the AD User CI object
                    EnterpriseManagementObjectCriteria emocADUser =
                        new EnterpriseManagementObjectCriteria(sADUserCriteria, mpcADUser, emg);
                    IObjectReader <EnterpriseManagementObject> orADUser = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emocADUser, objQueryOpts);
                    EnterpriseManagementObject emoAssignToUser          = orADUser.ElementAt(0);

                    if (iMode == 0)
                    {
                        //View mode - create a new assigned to user relationship
                        ManagementPackRelationship relAssignedToUser =
                            emg.EntityTypes.GetRelationshipClass(new Guid("15e577a3-6bf9-6713-4eac-ba5a5b7c4722"));
                        CreatableEnterpriseManagementRelationshipObject cemroAssignedToUser =
                            new CreatableEnterpriseManagementRelationshipObject(emg, relAssignedToUser);

                        //Set the source and target...
                        cemroAssignedToUser.SetSource(emoSelIncident);
                        cemroAssignedToUser.SetTarget(emoAssignToUser);

                        //Save
                        cemroAssignedToUser.Commit();

                        //Add a new comment
                        this.AddActionLogEntry(emg, emoSelIncident, "Incident was assigned to " + sADUserDisplayName, af.textComment.Text);

                        //Check tier
                        if (af.bShowTier)
                        {
                            if (af.comboTier.Text == "")
                            {
                                emoSelIncident[classIncident, "TierQueue"].Value = null;
                            }
                            else
                            {
                                ManagementPackEnumeration mpeTier = emg.EntityTypes.GetEnumeration(new Guid(af.comboTierGuids.Items[af.comboTier.SelectedIndex].ToString()));
                                emoSelIncident[classIncident, "TierQueue"].Value = mpeTier;
                            }
                            emoSelIncident.Commit();
                        }

                        //Refresh the current incident view
                        this.RequestViewRefresh();
                    }
                    else
                    {
                        //Note - IDataItem property names depend on the type projection being used and may differ from these

                        //Form mode, create a proxy to the emo user object to set on the form
                        EnterpriseManagementObjectDataType dataType = new EnterpriseManagementObjectDataType(mpcADUser);
                        IDataItem iUser = dataType.CreateProxyInstance(emoAssignToUser);
                        i[sAssignedTo] = iUser;

                        //Check tier
                        if (af.bShowTier)
                        {
                            if (af.comboTier.Text == "")
                            {
                                //Remove tier
                                i["TierQueue"] = null;
                            }
                            else
                            {
                                //Set tier, get enum first
                                ManagementPackEnumeration mpeTier = emg.EntityTypes.GetEnumeration(new Guid(af.comboTierGuids.Items[af.comboTier.SelectedIndex].ToString()));
                                i["TierQueue"] = mpeTier;
                            }
                        }
                        //Uncommenting this will cause the IDataItem to be saved and thus update the actual object in the database, normally you don't want to do this
                        //as you want the user to click OK or cancel on the form instead
                        //EnterpriseManagementObjectProjectionDataType.UpdateDataItem(i);

                        //IDataItem Action log
                        //
                        //Get the System.WorkItem.Library mp
                        ManagementPack mpWorkItemLibrary = emg.ManagementPacks.GetManagementPack(new Guid("405D5590-B45F-1C97-024F-24338290453E"));
                        //Get the actionlog class
                        ManagementPackClass mpcActionLog =
                            emg.EntityTypes.GetClass("System.WorkItem.TroubleTicket.ActionLog", mpWorkItemLibrary);

                        //Create a new action log entry as an idataitem
                        CreatableEnterpriseManagementObject cemoActionLog =
                            new CreatableEnterpriseManagementObject(emg, mpcActionLog);
                        EnterpriseManagementObjectDataType dataTypeLog = new EnterpriseManagementObjectDataType(mpcActionLog);
                        IDataItem iLog = dataTypeLog.CreateProxyInstance(cemoActionLog);

                        //Setup the new action log entry
                        iLog["Id"]          = Guid.NewGuid().ToString();
                        iLog["Description"] = af.textComment.Text;
                        iLog["Title"]       = "Reassignment Comment";
                        iLog["EnteredBy"]   = UserPrincipal.Current.DisplayName;
                        iLog["EnteredDate"] = DateTime.Now.ToUniversalTime();

                        //Set action type (this also adds the icon and is required)
                        ManagementPackEnumeration enumActionLog =
                            mpWorkItemLibrary.GetEnumerations().GetItem("System.WorkItem.ActionLogEnum.TaskExecuted");
                        iLog["ActionType"] = enumActionLog;

                        //This adds the new idataitem log entry to the entries displayed on the form, it does not over-write the existing entries
                        i[sActionLog] = iLog;
                    }
                }
                catch (System.Exception e)
                {
                    //Oops
                    MessageBox.Show(e.Message + "\n\n" + e.StackTrace, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }
        }
예제 #10
0
        protected virtual IncrementalDiscoveryData PrepareScomDiscoveryData(ScomDiscoveryType direction, IEnumerable <T> objects)
        {
            // create object for both incremental and full discovery
            var result = new IncrementalDiscoveryData();

            foreach (var @object in objects)
            {
                if ([email protected](_seedClass, _actionPointClass).IsValid)
                {
                    throw new Exception($"Instance has invalid properties or missing required properties");
                }

                var newSeedInstance = new CreatableEnterpriseManagementObject(_managementGroup, _seedClass);
                CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;

                foreach (var classProperty in _seedClass.PropertyCollection)
                {
                    try
                    {
                        newSeedInstance[classProperty].Value = @object[classProperty.Id];
                    }
                    catch (KeyNotFoundException) // ignore situations, when non-key or non-required fields are not available
                    {
                        if (classProperty.Required || classProperty.Key)
                        {
                            throw;
                        }
                    }
                }

                // Set displayname
                try
                {
                    newSeedInstance[_displayNamePropertyId].Value = @object[_displayNamePropertyId];
                }
                catch (Exception ex)
                {
                }

                //Unhosted, with specific action point
                if (!_seedClass.Hosted && _actionPointClass != null && @object.ActionPoint != null)
                {
                    if (_relMapShouldManageEntity != null)
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(_managementGroup, _relMapShouldManageEntity);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(@object.ActionPoint);
                    }

                    // sometimes when specific Health Service is deleted, relationship may revert to All Management Server Pool
                    if (_relHsShouldManageEntity != null && [email protected](_managementGroup.EntityTypes.GetClass(_managementServicePoolClassId)))
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(_managementGroup, _relHsShouldManageEntity);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(@object.ActionPoint);
                    }
                    if (_relMapShouldManageEntity == null && _relHsShouldManageEntity == null)
                    {
                        throw new NotSupportedException("Scenario not supported.");
                    }
                }
                // Hosted, in this case myActionPointClass is the hosing class
                if (_seedClass.Hosted && _actionPointClass != null && @object.ActionPoint != null)
                {
                    //Doesn't break reference most likely, needs to be tested
                    var hostClass = _actionPointClass;

                    while (hostClass != null)
                    {
                        foreach (var hostProperty in hostClass.PropertyCollection)
                        {
                            if (hostProperty.Key)
                            {
                                newSeedInstance[hostProperty].Value = @object.ActionPoint[hostProperty].Value;
                            }
                        }

                        hostClass = hostClass.FindHostClass();
                    }
                }

                switch (direction)
                {
                case ScomDiscoveryType.Insert:
                case ScomDiscoveryType.Update:
                    result.Add(newSeedInstance);
                    if (newSomethingShouldManageInstance != null)
                    {
                        result.Add(newSomethingShouldManageInstance);
                    }
                    // don't need Hosted==True check, newSomethingShouldManageInstance will be null for hosted classes
                    if (newSomethingShouldManageInstance != null && direction == ScomDiscoveryType.Update)
                    {
                        PerformRelationshipCleanup(_seedClass, newSeedInstance, @object.ActionPoint);
                    }
                    //if (mySeedClass.Hosted) { }
                    break;

                case ScomDiscoveryType.Delete:
                    result.Remove(newSeedInstance);
                    if (newSomethingShouldManageInstance != null)
                    {
                        result.Remove(newSomethingShouldManageInstance);
                    }
                    break;

                default:
                    throw new Exception("Unknown direction, unable to prepare discovery");
                }
            }

            return(result);
        }
        protected virtual IncrementalDiscoveryData PrepareSCOMDiscoveryData(SCOMDiscoveryType direction, IList <T> objects)
        {
            IncrementalDiscoveryData result = new IncrementalDiscoveryData();
            // create object for both incremental and full discovery
            bool hasData = false;

            foreach (T newObject in objects)
            {
                if (!HasAllRequiredProperties(newObject))
                {
                    continue;
                }
                hasData = true;
                CreatableEnterpriseManagementObject             newSeedInstance = new CreatableEnterpriseManagementObject(myMG, mySeedClass);
                CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;
                foreach (var classProperty in mySeedClass.PropertyCollection)
                {
                    try
                    {
                        newSeedInstance[classProperty].Value = newObject[classProperty.Id];
                    }
                    catch (KeyNotFoundException) // ignore situations, when non-key or non-required fields are not available
                    {
                        if (classProperty.Required || classProperty.Key)
                        {
                            throw;
                        }
                    }
                }
                // also try to set DisplayName if available
                try
                {
                    newSeedInstance[SystemId.EntityClassProperties.DisplayNamePropertyId].Value = newObject.GetClassInstanceProperty(SystemId.EntityClassProperties.DisplayNamePropertyId);
                }
                catch (KeyNotFoundException) { } // ignore

                // Unhosted, with specific action point
                if (!mySeedClass.Hosted && myActionPointClass != null && newObject.ActionPoint != null)
                {
                    if (relMAPShouldManageEntity != null)
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(myMG, relMAPShouldManageEntity);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(newObject.ActionPoint);
                    }
                    // sometimes when specific Health Service is deleted, relationship may revert to All Management Server Pool
                    if (relHSShouldManageEntiry != null && !newObject.ActionPoint.IsInstanceOf(myMG.EntityTypes.GetClass(SystemCenterId.ManagementServicePoolClassId)))
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(myMG, relHSShouldManageEntiry);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(newObject.ActionPoint);
                    }
                    if (relMAPShouldManageEntity == null && relHSShouldManageEntiry == null)
                    {
                        throw new NotSupportedException("Scenario not supported.");
                    }
                }
                // Hosted, in this case myActionPointClass is the hosing class
                if (mySeedClass.Hosted && myActionPointClass != null && newObject.ActionPoint != null)
                {
                    ManagementPackClass hostClass = myActionPointClass;
                    while (hostClass != null)
                    {
                        foreach (ManagementPackProperty hostProperty in hostClass.PropertyCollection)
                        {
                            if (hostProperty.Key)
                            {
                                newSeedInstance[hostProperty].Value = newObject.ActionPoint[hostProperty].Value;
                            }
                        }
                        hostClass = hostClass.FindHostClass();
                    }
                }
                if (hasData)
                {
                    switch (direction)
                    {
                    case SCOMDiscoveryType.Insert:
                    case SCOMDiscoveryType.Update:
                        result.Add(newSeedInstance);
                        if (newSomethingShouldManageInstance != null)
                        {
                            result.Add(newSomethingShouldManageInstance);
                        }
                        // don't need Hosted==True check, newSomethingShouldManageInstance will be null for hosted classes
                        if (newSomethingShouldManageInstance != null && direction == SCOMDiscoveryType.Update)
                        {
                            PerformRelationshipCleanup(mySeedClass, newSeedInstance, newObject.ActionPoint);
                        }
                        if (mySeedClass.Hosted)
                        {
                        }
                        break;

                    case SCOMDiscoveryType.Delete:
                        result.Remove(newSeedInstance);
                        if (newSomethingShouldManageInstance != null)
                        {
                            result.Remove(newSomethingShouldManageInstance);
                        }
                        break;
                    }
                }
            }
            return(result);
        }
예제 #12
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
            }
        }
예제 #13
0
        /// <summary>
        /// Create Relationships
        /// </summary>
        private static void CreateRelationships()
        {
            foreach (SyncFailoverGroup sfog in SyncFailoverGroupList)
            {
                // Get SyncFailover Group Object
                EnterpriseManagementObject syncFailoverGroupObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(sfog.SCOM_Object.Id, ObjectQueryOptions.Default);

                // Add Device Relationship
                foreach (f5Device dev in sfog.DeviceList)
                {
                    // Create SyncFailoverGroup->Device Containment Relationship Object
                    ManagementPackRelationship mpr_SyncFailoverGroupContainsDevice = SCOM.GetManagementPackRelationship("AP.F5.LTM.SyncFailoverGroupContainsDevices");
                    CreatableEnterpriseManagementRelationshipObject obj_SyncFailoverGroupContainsDevice = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_SyncFailoverGroupContainsDevice);
                    obj_SyncFailoverGroupContainsDevice.SetSource(syncFailoverGroupObject);
                    obj_SyncFailoverGroupContainsDevice.SetTarget(dev.SCOM_DeviceObject);
                    relationshipData.Add(obj_SyncFailoverGroupContainsDevice);
                }

                // Loop Through Traffic Groups
                foreach (TrafficGroup tg in sfog.TrafficGroupList)
                {
                    // Add Device Relationship
                    foreach (f5Device dev in tg.DeviceGroup.DeviceList)
                    {
                        // Create TrafficGroup->Device Containment Relationship Object
                        ManagementPackRelationship mpr_TrafficGroupContainsDevices = SCOM.GetManagementPackRelationship("AP.F5.LTM.TrafficGroupContainsDevices");
                        CreatableEnterpriseManagementRelationshipObject obj_TrafficGroupContainsDevice = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_TrafficGroupContainsDevices);
                        obj_TrafficGroupContainsDevice.SetSource(tg.SCOM_Object);
                        obj_TrafficGroupContainsDevice.SetTarget(dev.SCOM_DeviceObject);
                        relationshipData.Add(obj_TrafficGroupContainsDevice);
                    }
                }


                // Loop Through Partitions
                foreach (Partition p in sfog.PartitionList)
                {
                    // Create ClientSslProfile -> Certificate Containment
                    foreach (ProfileClientSSL profile in p.ClientSslProfileList)
                    {
                        if (profile.CertificateList.Count > 0)
                        {
                            // Get Client SSL Object
                            EnterpriseManagementObject profile_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);

                            foreach (Certificate cert in profile.CertificateList)
                            {
                                // Get Certificate Object
                                EnterpriseManagementObject cert_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(cert.SCOM_Object.Id, ObjectQueryOptions.Default);

                                // Create Relationship
                                ManagementPackRelationship mpr_Containment = SCOM.GetManagementPackRelationship("AP.F5.LTM.ProfileClientSSL.ContainsCertificates");
                                CreatableEnterpriseManagementRelationshipObject obj_Containment = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_Containment);
                                obj_Containment.SetSource(profile_Object);
                                obj_Containment.SetTarget(cert_Object);
                                relationshipData.Add(obj_Containment);
                            }
                        }
                    }

                    // Create ServerSslProfile -> Certificate Containment
                    foreach (ProfileServerSSL profile in p.ServerSslProfileList)
                    {
                        if (profile.CertificateList.Count > 0)
                        {
                            // Get Client SSL Object
                            EnterpriseManagementObject profile_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);

                            foreach (Certificate cert in profile.CertificateList)
                            {
                                // Get Certificate Object
                                EnterpriseManagementObject cert_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(cert.SCOM_Object.Id, ObjectQueryOptions.Default);

                                // Create Relationship
                                ManagementPackRelationship mpr_Containment = SCOM.GetManagementPackRelationship("AP.F5.LTM.ProfileServerSSL.ContainsCertificates");
                                CreatableEnterpriseManagementRelationshipObject obj_Containment = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_Containment);
                                obj_Containment.SetSource(profile_Object);
                                obj_Containment.SetTarget(cert_Object);
                                relationshipData.Add(obj_Containment);
                            }
                        }
                    }

                    // Add Virtual Server Containments
                    foreach (VirtualServer vs in p.VirtualServerList)
                    {
                        // Get Traffic Group Object
                        EnterpriseManagementObject vipObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(vs.SCOM_Object.Id, ObjectQueryOptions.Default);

                        // Do Client SSL Profiles
                        foreach (ProfileClientSSL profile in vs.ProfileClientSslList)
                        {
                            // Get Profile Object
                            EnterpriseManagementObject profileObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);
                            // Create VirtualServer->ProfileClientSSL Containment Relationship Object
                            ManagementPackRelationship mpr_VirtualServerContainsProfile = SCOM.GetManagementPackRelationship("AP.F5.LTM.VirtualServerContainsProfileClientSSL");
                            CreatableEnterpriseManagementRelationshipObject obj_VirtualServerContainsProfile = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_VirtualServerContainsProfile);
                            obj_VirtualServerContainsProfile.SetSource(vipObject);
                            obj_VirtualServerContainsProfile.SetTarget(profileObject);
                            relationshipData.Add(obj_VirtualServerContainsProfile);
                        }
                        // Do Server SSL Profiles
                        foreach (ProfileServerSSL profile in vs.ProfileServerSslList)
                        {
                            // Get Profile Object
                            EnterpriseManagementObject profileObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);
                            // Create VirtualServer->ProfileServerSSL Containment Relationship Object
                            ManagementPackRelationship mpr_VirtualServerContainsProfile = SCOM.GetManagementPackRelationship("AP.F5.LTM.VirtualServerContainsProfileServerSSL");
                            CreatableEnterpriseManagementRelationshipObject obj_VirtualServerContainsProfile = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_VirtualServerContainsProfile);
                            obj_VirtualServerContainsProfile.SetSource(vipObject);
                            obj_VirtualServerContainsProfile.SetTarget(profileObject);
                            relationshipData.Add(obj_VirtualServerContainsProfile);
                        }


                        // Do Pools
                        if (vs.DefaultPool != null)
                        {
                            // Get Pool Object
                            EnterpriseManagementObject poolObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(vs.DefaultPool.SCOM_Object.Id, ObjectQueryOptions.Default);
                            // Create VirtualServer->Pool Containment Relationship Object
                            ManagementPackRelationship mpr_VirtualServerContainsPools = SCOM.GetManagementPackRelationship("AP.F5.LTM.VirtualServerContainsPools");
                            CreatableEnterpriseManagementRelationshipObject obj_VirtualServerContainsPools = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_VirtualServerContainsPools);
                            obj_VirtualServerContainsPools.SetSource(vipObject);
                            obj_VirtualServerContainsPools.SetTarget(poolObject);
                            relationshipData.Add(obj_VirtualServerContainsPools);
                        }
                    }
                }
            }
        }
예제 #14
0
        EnterpriseManagementObject buildTaskActivity(PublishedTask task,
                                                     EnterpriseManagementObject releaseRecord,
                                                     EnterpriseManagementObject taskActivity,
                                                     EnterpriseManagementObject project,
                                                     ref int sequenceId)
        {
            var activityClass = mpcClasses.First(mpc => mpc.Name == "Cireson.ProjectAutomation.ProjectTask.Activity");

            #region set properties
            if (taskActivity.IsNew)
            {
                taskActivity[activityClass, "Id"].Value       = sTaskActivityPrefix + taskActivity[activityClass, "Id"].Value as string;
                taskActivity[activityClass, "TaskGUID"].Value = task.Id;
                if (releaseRecord[null, "Status"].Value == releaseStatusEnums.First(e => e.Name == "ReleaseStatusEnum.InProgress")) //if RR in progress, set initial status to pending.
                {
                    taskActivity[activityClass, "Status"].Value = activityStatusEnums.First(e => e.Name == "ActivityStatusEnum.Ready");
                }
                else if (releaseRecord[null, "Status"].Value == releaseStatusEnums.First(e => e.Name == "ReleaseStatusEnum.Editing")) // if RR in editing mode, set initial status to on-hold.
                {
                    taskActivity[activityClass, "Status"].Value = activityStatusEnums.First(e => e.Name == "ActivityStatusEnum.OnHold");
                }
            }

            taskActivity[activityClass, "PercentComplete"].Value = task.PercentComplete as int?;
            taskActivity[activityClass, "Title"].Value           = task.Name + " : " + taskActivity[activityClass, "PercentComplete"].Value + "% " +
                                                                   mpManagementPacks.First(mp => mp.Name == "Cireson.ProjectAutomation.Library").GetStringResource("strComplete").DisplayName;
            taskActivity[activityClass, "Description"].Value        = task.Notes;
            taskActivity[activityClass, "ScheduledStartDate"].Value = task.ScheduledStart;
            taskActivity[activityClass, "ScheduledEndDate"].Value   = task.ScheduledFinish;
            taskActivity[activityClass, "SequenceId"].Value         = sequenceId;
            taskActivity[activityClass, "DisplayName"].Value        = taskActivity[activityClass, "Id"].Value;
            #endregion

            #region status enums
            //set a status
            //Activity Status (System.WorkItem.Activity.Library) (ActivityStatusEnum) (57db4880-000e-20bb-2f9d-fe4e8aca3cf6)
            //Cancelled (System.WorkItem.Activity.Library) (ActivityStatusEnum.Cancelled) (89465302-2a23-d2b6-6906-74f03d9b7b41)
            //Completed (System.WorkItem.Activity.Library) (ActivityStatusEnum.Completed) (9de908a1-d8f1-477e-c6a2-62697042b8d9)
            //Failed (System.WorkItem.Activity.Library) (ActivityStatusEnum.Failed) (144bcd52-a710-2778-2a6e-c62e0c8aae74)
            //In Progress (System.WorkItem.Activity.Library) (ActivityStatusEnum.Active) (11fc3cef-15e5-bca4-dee0-9c1155ec8d83)
            //On Hold (System.WorkItem.Activity.Library) (ActivityStatusEnum.OnHold) (d544258f-24da-1cf3-c230-b057aaa66bed)
            //Pending (System.WorkItem.Activity.Library) (ActivityStatusEnum.Ready) (50c667cf-84e5-97f8-f6f8-d8acd99f181c)
            //Rerun (System.WorkItem.Activity.Library) (ActivityStatusEnum.Rerun) (baa948b5-cc6a-57d7-4b56-d2012721b2e5)
            //Skipped (System.WorkItem.Activity.Library) (ActivityStatusEnum.Skipped) (eaec5899-b13c-d107-3e1a-955da6bf9fa7)


            if (task.PercentComplete == 100 && releaseRecord[null, "Status"].Value == releaseStatusEnums.First(e => e.Name == "ReleaseStatusEnum.InProgress")) // only set status if RR is in progress
            {
                taskActivity[activityClass, "Status"].Value = activityStatusEnums.First(e => e.Name == "ActivityStatusEnum.Completed");
            }
            #endregion

            #region set  workitem and CI relationships
            CreatableEnterpriseManagementRelationshipObject cemroReleaseContainsActivity = new CreatableEnterpriseManagementRelationshipObject(
                emg, mprRelationships.First(r => r.Name == "System.WorkItemContainsActivity"));
            cemroReleaseContainsActivity.SetSource(releaseRecord);
            cemroReleaseContainsActivity.SetTarget(taskActivity);
            iddBucket.Add(cemroReleaseContainsActivity);

            CreatableEnterpriseManagementRelationshipObject cemroActivityHasProject = new CreatableEnterpriseManagementRelationshipObject(
                emg, mprRelationships.First(r => r.Name == "Cireson.ProjectAutomation.WorkItemHasProject"));
            cemroActivityHasProject.SetSource(taskActivity);
            cemroActivityHasProject.SetTarget(project);
            iddBucket.Add(cemroActivityHasProject);

            CreatableEnterpriseManagementRelationshipObject cemroRelatedProject = new CreatableEnterpriseManagementRelationshipObject(
                emg, mprRelationships.First(r => r.Name == "Cireson.ProjectAutomation.ProjectHasTask"));
            cemroRelatedProject.SetSource(project);
            cemroRelatedProject.SetTarget(taskActivity);
            iddBucket.Add(cemroRelatedProject);
            #endregion

            #region set activity implemeter and resources
            var userClass = mpcClasses.First(mpc => mpc.Name == "Microsoft.AD.UserBase");

            var taskOwner = task.Assignments.FirstOrDefault();
            if (taskOwner != null && taskOwner.Resource.DefaultAssignmentOwner.ServerObjectIsNull != true) //bug fix.  We needed to check the server if the default owner is null too.
            {
                string activityImplementerSID = taskOwner.Resource.DefaultAssignmentOwner.UserId.NameId;

                EnterpriseManagementObjectCriteria emoCriteria = new EnterpriseManagementObjectCriteria(string.Format(xmlResourceCriteria, activityImplementerSID),
                                                                                                        userClass, mpManagementPacks.First(mp => mp.Name == "Microsoft.Windows.Library"), emg);
                EnterpriseManagementObject emoImplementer = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emoCriteria, ObjectQueryOptions.Default).FirstOrDefault();

                if (emoImplementer != null && (bool)emoProjectAutomationSettings[null, "CanAssignActivityImplementer"].Value)
                {
                    CreatableEnterpriseManagementRelationshipObject cemroActivityImplementer = new CreatableEnterpriseManagementRelationshipObject(
                        emg, mprRelationships.First(r => r.Name == "System.WorkItemAssignedToUser"));
                    cemroActivityImplementer.SetSource(taskActivity);
                    cemroActivityImplementer.SetTarget(emoImplementer);
                    iddBucket.Add(cemroActivityImplementer);
                }

                foreach (var assignment in task.Assignments)
                {
                    //get the user SID
                    if (assignment.Resource.DefaultAssignmentOwner.ServerObjectIsNull == true)
                    {
                        continue;
                    }

                    var resourceSid = assignment.Resource.DefaultAssignmentOwner.UserId.NameId;
                    emoCriteria = new EnterpriseManagementObjectCriteria(string.Format(xmlResourceCriteria, resourceSid),
                                                                         userClass, mpManagementPacks.First(mp => mp.Name == "Microsoft.Windows.Library"), emg);
                    EnterpriseManagementObject emoResource = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emoCriteria, ObjectQueryOptions.Default).FirstOrDefault();

                    if (emoResource != null)
                    {
                        CreatableEnterpriseManagementRelationshipObject cemroResource = new CreatableEnterpriseManagementRelationshipObject(
                            emg, mprRelationships.First(r => r.Name == "System.WorkItemRelatesToConfigItem"));
                        cemroResource.SetSource(taskActivity);
                        cemroResource.SetTarget(emoResource);
                        iddBucket.Add(cemroResource);
                    }
                }
            }
            #endregion

            sequenceId++;
            return(taskActivity);
        }