Esempio n. 1
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //try
            //{
            GetSession();

            mpCore = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
            mpNA   = emg.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version());


            classLocation = emg.EntityTypes.GetClass("SMCenter.Location", mpCore);
            //classNetworkMap = emg.EntityTypes.GetClass("SMCenter.NetworkMap", mpNA);

            relLoctoLoc = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mpCore);

            //Fill Templates

            this.TemplateLocationItem.emg                 = emg;
            this.TemplateLocationItem.PathString          = "LinkedLocation";
            this.TemplateLocationItem.mpClass             = classLocation;
            this.TemplateLocationItem.mpRelationshipClass = relLoctoLoc;
            this.TemplateLocationItem.criteria            = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", classLocation);


            //////Handlers
            this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted));
            this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit));
            //}
            //catch (Exception ex)
            //{
            //    System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message);
            //}
        }
        private void FillListView()
        {
            try
            {
                ListViewImages.ItemsSource = null;
                ListViewImages.Items.Clear();
                ObservableCollection <ManagementPackImage> ImagesCol = new ObservableCollection <ManagementPackImage>();
                ManagementPack mp = emg.GetManagementPack("SMCenter.AssetManagement.Resources", "75b45bd6835084b1", new Version());

                //ManagementPackImage Im = new ManagementPackImage(mp, "ItamHardwareFolder48x48", ManagementPackAccessibility.Internal);

                foreach (ManagementPackResource Res in mp.GetResources <ManagementPackResource>())
                {
                    if (Res is Microsoft.EnterpriseManagement.Configuration.ManagementPackImage)
                    {
                        ManagementPackImage Im = (ManagementPackImage)Res;
                        ImagesCol.Add(Im);
                        //System.Drawing.Image II = System.Drawing.Image.FromStream(Im.ImageData);
                    }
                }
                this.ListViewImages.ItemsSource = ImagesCol;
            }
            catch (Exception exc)
            {
                Trace.WriteLine(DateTime.Now + " : " + "Error in FillListViewImages() " + exc.Message);
            }
        }
        private void UpdateConnectorInstance()
        {
            //Get the server name to connect to and connect
            String strServerName          = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

            //Get the Connectors MP and AA Connector Class
            ManagementPack      mpConnectors     = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0"));
            ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");

            //Get the Connector object using the object ID
            EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default);

            //Set the property values to the new values
            emoAAConnector[classAAConnector, "DisplayName"].Value          = this.DisplayName;
            emoAAConnector[classAAConnector, "AutomationAccount"].Value    = this.AutomationAccount;
            emoAAConnector[classAAConnector, "SubscriptionID"].Value       = this.SubscriptionID;
            emoAAConnector[classAAConnector, "ResourceGroup"].Value        = this.ResourceGroup;
            emoAAConnector[classAAConnector, "RunAsAccountName"].Value     = this.RunAsAccountName;
            emoAAConnector[classAAConnector, "RunAsAccountPassword"].Value = this.RunAsAccountPassword;
            emoAAConnector[classAAConnector, "RefreshIntervalHours"].Value = this.RefreshIntervalHours;



            //Update Connector instance
            emoAAConnector.Commit();

            mpConnectors.AcceptChanges();
        }
Esempio n. 4
0
        private static void getServiceManagerBrandingProperties(string managementServerName, string netbiosComputerName, ref string attestationFrequency,
                                                                ref string ChargebackGroup, ref string Description, ref string NotificationGroup,
                                                                ref string ServerOwner1, ref string ServiceLevel, ref string VirtualCenter)
        {
            //Connect to Management Group
            EnterpriseManagementGroup mg = new EnterpriseManagementGroup(managementServerName);
            ManagementPack            mp = mg.GetManagementPack("GMI.SM.BaseClasses.Extension", "c17ba471fb087385", new Version());

            ManagementPackClass requestClass = mp.GetClass("ClassExtension_c270fe5b_740f_4a9c_828c_b35e8fe739a9");

            EnterpriseManagementObjectCriteria         criteria = new EnterpriseManagementObjectCriteria(String.Format("NetbiosComputerName='{0}'", netbiosComputerName), requestClass);
            IObjectReader <EnterpriseManagementObject> reader   = mg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(criteria, ObjectQueryOptions.Default);

            foreach (EnterpriseManagementObject item in reader)
            {
                foreach (ManagementPackProperty mpp in item.GetProperties())
                {
                    switch (mpp.Name)
                    {
                    case "AttestationFrequency":
                        try { attestationFrequency = item[mpp].Value.ToString(); }
                        catch { ChargebackGroup = String.Empty; }
                        break;

                    case "ChargebackGroup":
                        try { ChargebackGroup = item[mpp].Value.ToString(); }
                        catch { ChargebackGroup = String.Empty; }
                        break;

                    case "Description":
                        try { Description = item[mpp].Value.ToString(); }
                        catch { Description = String.Empty; }
                        break;

                    case "NotificationGroup":
                        try { NotificationGroup = item[mpp].Value.ToString(); }
                        catch { ChargebackGroup = String.Empty; }
                        break;

                    case "ServerOwner1":
                        try { ServerOwner1 = item[mpp].Value.ToString(); }
                        catch { ChargebackGroup = String.Empty; }
                        break;

                    case "ServiceLevel":
                        try { ServiceLevel = item[mpp].Value.ToString(); }
                        catch { ChargebackGroup = String.Empty; }
                        break;

                    case "VirtualCenter":
                        try { VirtualCenter = item[mpp].Value.ToString(); }
                        catch { ChargebackGroup = String.Empty; }
                        break;
                    }
                }
            }
        }
Esempio n. 5
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                GetSession();

                mpCore = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
                mpNA   = emg.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version());
                mpNetworkManagementLibrary = emg.GetManagementPack("System.NetworkManagement.Library", "31bf3856ad364e35", new Version());

                classLocation   = emg.EntityTypes.GetClass("SMCenter.Location", mpCore);
                classRack       = emg.EntityTypes.GetClass("SMCenter.Rack", mpNA);
                classPatchPanel = emg.EntityTypes.GetClass("SMCenter.PatchPanel", mpNA);
                //classPPPort = emg.EntityTypes.GetClass("SMCenter.PatchPanelPort", mpNA);
                classNAPort = emg.EntityTypes.GetClass("System.NetworkManagement.NetworkAdapter", mpNetworkManagementLibrary);
                //classNetworkMap = emg.EntityTypes.GetClass("SMCenter.NetworkMap", mpNA);


                relLoctoLoc = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mpCore);

                relConfigItemRefRack = emg.EntityTypes.GetRelationshipClass("SMCenter.ConfigItemRefRack", mpNA);
                relNodetoPort        = emg.EntityTypes.GetRelationshipClass("System.NetworkManagement.NodeComposedOfNetworkAdapter", mpNetworkManagementLibrary);

                //Fill Templates

                //this.TemplateLocationItem.emg = emg;
                //this.TemplateLocationItem.PathString = "LinkedLocation";
                //this.TemplateLocationItem.mpClass = classLocation;
                //this.TemplateLocationItem.mpRelationshipClass = relLoctoLoc;
                //this.TemplateLocationItem.criteria = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", classLocation);

                this.TemplateRackItem.PathString = "Rack";
                this.TemplateRackItem.mpClass    = classRack;

                //////Handlers
                this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted));
                this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message);
            }
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                GetSession();
                ManagementPack mp       = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
                ManagementPack mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version());
                organizationClass = emg.EntityTypes.GetClass("SMCenter.Organization", mp);
                UserClass         = emg.EntityTypes.GetClass("System.Domain.User", mpSystem);
                relationClass     = emg.EntityTypes.GetRelationshipClass("SMCenter.OrganizationContainsChildOrganization", mp);
                userrelationClass = emg.EntityTypes.GetRelationshipClass("SMCenter.UserHasOrganization", mp);
                FillTreeView.Now(emg, organizationClass, relationClass, OrganizationTreeView);

                this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message);
            }
        }
Esempio n. 7
0
        private void UpdateConnectorInstance()
        {
            //Get the server name to connect to and connect
            String strServerName          = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

            //Get the Connectors MP and CSV Connector Class
            ManagementPack      mpConnectors      = emg.GetManagementPack("Microsoft.Demo.Connectors", null, new Version("1.0.0.0"));
            ManagementPackClass classCSVConnector = mpConnectors.GetClass("Microsoft.Demo.Connectors.CSVConnector");

            //Get the Connector object using the object ID
            EnterpriseManagementObject emoCSVConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default);

            //Set the property values to the new values
            emoCSVConnector[classCSVConnector, "DisplayName"].Value     = this.DisplayName;
            emoCSVConnector[classCSVConnector, "DataFilePath"].Value    = this.DataFilePath;
            emoCSVConnector[classCSVConnector, "DataFilePath"].Value    = this.DataFilePath;
            emoCSVConnector[classCSVConnector, "MappingFilePath"].Value = this.MappingFilePath;
            emoCSVConnector[classCSVConnector, "NumberMinutes"].Value   = this.NumberMinutes;

            //Update Connector instance
            emoCSVConnector.Commit();

            //Get the rule using the Connector ID and then update the data source and write action module configuration
            ManagementPackRule ruleConnector = mpConnectors.GetRule(this.ConnectorID);

            ruleConnector.DataSourceCollection[0].Configuration =
                "<Scheduler>" +
                "<SimpleReccuringSchedule>" +
                "<Interval Unit=\"Minutes\">" + this.NumberMinutes + "</Interval>" +
                "</SimpleReccuringSchedule>" +
                "<ExcludeDates />" +
                "</Scheduler>";

            ruleConnector.WriteActionCollection[0].Configuration =
                "<Subscription>" +
                "<WindowsWorkflowConfiguration>" +
                "<AssemblyName>CSVConnectorWorkflow</AssemblyName>" +
                "<WorkflowTypeName>WorkflowAuthoring.CSVConnectorWorkflow</WorkflowTypeName>" +
                "<WorkflowParameters>" +
                "<WorkflowParameter Name=\"DataFilePath\" Type=\"string\">" + this.DataFilePath + "</WorkflowParameter>" +
                "<WorkflowParameter Name=\"FormatFilePath\" Type=\"string\">" + this.MappingFilePath + "</WorkflowParameter>" +
                "</WorkflowParameters>" +
                "<RetryExceptions />" +
                "<RetryDelaySeconds>60</RetryDelaySeconds>" +
                "<MaximumRunningTimeSeconds>300</MaximumRunningTimeSeconds>" +
                "</WindowsWorkflowConfiguration>" +
                "</Subscription>";

            ruleConnector.Status = ManagementPackElementStatus.PendingUpdate;
            mpConnectors.AcceptChanges();
        }
Esempio n. 8
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                GetSession();

                mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version());
                mpCore   = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
                mpNA     = emg.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version());
                mpSoft   = emg.GetManagementPack("SMCenter.SoftwareAssetManagement.Library", "75b45bd6835084b1", new Version());

                classCompany = emg.EntityTypes.GetClass("SMCenter.Company", mpCore);
                classVersion = emg.EntityTypes.GetClass("SMCenter.SoftwareVersion", mpSoft);
                relPublisherHasSoftwareTitle       = emg.EntityTypes.GetRelationshipClass("SMCenter.PublisherHasSoftwareTitle", mpSoft);        //SMCenter.PublisherHasSoftwareTitle
                relSoftwareTitleHasSoftwareVersion = emg.EntityTypes.GetRelationshipClass("SMCenter.SoftwareTitleHasSoftwareVersion", mpSoft);; //SMCenter.SoftwareTitleHasSoftwareVersion

                //Fill Templates

                //this.TemplatePublisher.eemg = emg;
                this.TemplatePublisher.PathString = "Publisher";
                this.TemplatePublisher.mpClass    = classCompany;
                //this.TemplatePublisher.mpRelationshipClass = relLoctoLoc;
                //this.TemplateLocationItem.criteria = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", classLocation);


                //////Handlers
                this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted));
                this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit));

                FillListViewCI();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message);
            }
        }
Esempio n. 9
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            string userName = (System.Security.Principal.WindowsIdentity.GetCurrent().Name).Replace("\\", "_");

            //string strlog = @"c:\Temp\SMCLog_" + userName + ".txt";
            //Debug.WriteLine(strlog);
            //TextWriterTraceListener TL = new TextWriterTraceListener(strlog);
            //Trace.Listeners.Add(TL);
            //Trace.AutoFlush = true;
            GetSession();
            ManagementPack mp = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());

            locationClass = emg.EntityTypes.GetClass("SMCenter.Location", mp);
            relationClass = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mp);
            //FillTreeView.Now(emg, locationClass, relationClass, LocationTreeView);
            Fill();
        }
Esempio n. 10
0
        internal CSVConnectorWizardData(EnterpriseManagementObject emoCSVConnector)
        {
            //Get the server name to connect to
            String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();

            //Conneect to the server
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

            ManagementPack      mpConnectors      = emg.GetManagementPack("Microsoft.Demo.Connectors", null, new Version("1.0.0.0"));
            ManagementPackClass classCSVConnector = mpConnectors.GetClass("Microsoft.Demo.Connectors.CSVConnector");

            this.EnterpriseManagementObjectID = emoCSVConnector.Id;
            this.DisplayName     = emoCSVConnector.DisplayName;
            this.DataFilePath    = emoCSVConnector[classCSVConnector, "DataFilePath"].ToString();
            this.MappingFilePath = emoCSVConnector[classCSVConnector, "MappingFilePath"].ToString();
            this.NumberMinutes   = emoCSVConnector[classCSVConnector, "NumberMinutes"].ToString();
            this.ConnectorID     = emoCSVConnector[classCSVConnector, "Id"].ToString();
        }
        internal IncidentSLASettingsWizardData(EnterpriseManagementObject emoIncidentSLASettings, EnterpriseManagementGroup emg)
        {
            //Get the IncidentSLAManagement MP so you can get the Admin Setting class
            ManagementPack      mpIncidentSLAManagement            = emg.GetManagementPack("Microsoft.Demo.IncidentSLAManagement.Library", "9396306c2be7fcc4", new Version("1.0.0.0"));
            ManagementPackClass classIncidentSLAManagementSettings = mpIncidentSLAManagement.GetClass("Microsoft.Demo.IncidentSLAManagement.Settings.ClassType");

            Int32 intResult;
            bool  bIsNumber = Int32.TryParse(emoIncidentSLASettings[classIncidentSLAManagementSettings, "IncidentSLABreachWarningThreshold"].ToString(), out intResult);

            if (bIsNumber)
            {
                this.intWarningThreshold = intResult;
            }
            else
            {
                this.intWarningThreshold = 0;
            }
            this.EnterpriseManagementObjectID = emoIncidentSLASettings.Id;
        }
        public override void AcceptChanges(WizardMode wizardMode)
        {
            //Get the server name to connect to and connect
            String strServerName          = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

            //Get the AdminSettings MP so you can get the Admin Setting class
            ManagementPack      mpIncidentSLAManagement            = emg.GetManagementPack("Microsoft.Demo.IncidentSLAManagement.Library", "9396306c2be7fcc4", new Version("1.0.0.0"));
            ManagementPackClass classIncidentSLAManagementSettings = mpIncidentSLAManagement.GetClass("Microsoft.Demo.IncidentSLAManagement.Settings.ClassType");

            //Get the object using the object ID
            EnterpriseManagementObject emoIncidentSLASettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default);

            //Set the property value to the new value
            emoIncidentSLASettings[classIncidentSLAManagementSettings, "IncidentSLABreachWarningThreshold"].Value = this.WarningThreshold;

            //Update object
            emoIncidentSLASettings.Commit();

            this.WizardResult = WizardResult.Success;
        }
        internal AzureAutomationWizardData(EnterpriseManagementObject emoAAConnector)
        {
            //Get the server name to connect to
            String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();

            //Connect to the server
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

            ManagementPack      mpConnectors     = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0"));
            ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");

            this.EnterpriseManagementObjectID = emoAAConnector.Id;
            this.DisplayName          = emoAAConnector.DisplayName;
            this.ConnectorID          = emoAAConnector[classAAConnector, "Id"].ToString();
            this.AutomationAccount    = emoAAConnector[classAAConnector, "AutomationAccount"].ToString();
            this.SubscriptionID       = emoAAConnector[classAAConnector, "SubscriptionID"].ToString();
            this.ResourceGroup        = emoAAConnector[classAAConnector, "ResourceGroup"].ToString();
            this.RunAsAccountName     = emoAAConnector[classAAConnector, "RunAsAccountName"].ToString();
            this.RunAsAccountPassword = emoAAConnector[classAAConnector, "RunAsAccountPassword"].ToString();
            this.RefreshIntervalHours = emoAAConnector[classAAConnector, "RefreshIntervalHours"].ToString();
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                string userName            = (System.Security.Principal.WindowsIdentity.GetCurrent().Name).Replace("\\", "_");
                string strlog              = @"c:\Temp\SMCLog_" + userName + ".txt";
                TextWriterTraceListener TL = new TextWriterTraceListener(strlog);
                Trace.Listeners.Add(TL);
                Trace.AutoFlush = true;
                GetSession();


                ManagementPack mpCore = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
                //ManagementPack mpHA = emg.GetManagementPack("SMCenter.HardwareAssetManagement.Library", "75b45bd6835084b1", new Version());
                //ManagementPack mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version());

                //HAClass = emg.EntityTypes.GetClass("SMCenter.HardwareAsset", mpHA);
                //ConfItemClass = emg.EntityTypes.GetClass("System.ConfigItem", mpSystem);
                //LocationClass = emg.EntityTypes.GetClass("SMCenter.Location", mpCore);
                //CatalogItemClass = emg.EntityTypes.GetClass("SMCenter.HardwareCatalogItem", mpHA);



                //Fill Templates
                ManagementPackClass ManufacturerClass = emg.EntityTypes.GetClass("SMCenter.Company", mpCore);
                this.TemplateManufacturer.PathString = "Manufacturer";
                this.TemplateManufacturer.mpClass    = ManufacturerClass;

                ManagementPackClass PreferredSuplierClass = emg.EntityTypes.GetClass("SMCenter.Company", mpCore);
                this.TemplatePreferredSuplier.PathString = "PreferredSupplier";
                this.TemplatePreferredSuplier.mpClass    = PreferredSuplierClass;

                //Handlers
                this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit));
            }
            catch (Exception ex)
            {
                Trace.WriteLine(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message);
            }
        }
Esempio n. 15
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            // getting the Management Group Connection that is used by the Console (as it should already be open)

            ConsoleSdkConnection.IManagementGroupSession session = FrameworkServices.GetService <ConsoleSdkConnection.IManagementGroupSession>();
            EnterpriseManagementGroup emg = session.ManagementGroup;

            // verifying if the MG Connection is closed and reconnecting if needed

            if (!emg.IsConnected)
            {
                emg.Reconnect();
            }

            // getting some types we need and which we are going to use further in our code in the actual processing

            ManagementPack incidentMp         = emg.GetManagementPack(ManagementPacks.incidentLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version);
            ManagementPack wiLibraryMp        = emg.GetManagementPack(ManagementPacks.workItemLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version);
            ManagementPack incidentSettingsMp = emg.GetManagementPack(ManagementPacks.incidentManagementLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version);
            ManagementPack activityLibMp      = emg.GetManagementPack(ManagementPacks.activityLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version);

            ManagementPackClass incidentClass       = emg.EntityTypes.GetClass(ClassTypes.incident, incidentMp);
            ManagementPackClass analystCommentClass = emg.EntityTypes.GetClass(ClassTypes.analystCommentLog, wiLibraryMp);
            ManagementPackEnumerationCriteria incidentClosedEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", EnumTypes.incidentStatusClosed));
            ManagementPackEnumeration         incidentClosedStatus       = emg.EntityTypes.GetEnumerations(incidentClosedEnumCriteria).FirstOrDefault();
            ManagementPackTypeProjection      incidentProjection         = emg.EntityTypes.GetTypeProjection(TypeProjections.incidentAdvanced, incidentSettingsMp);

            // this is needed in order to know which Activities map to which Activity Profix types
            // this is the case because each Activity can have a different type, but the Prefix used is saved in the same class-object (System.GlobalSetting.ActivitySettings)

            IDictionary <string, string> activityPrefixMapping = new Dictionary <string, string>
            {
                { ActivityTypes.dependent, ActivityPrefixes.dependent },
                { ActivityTypes.manual, ActivityPrefixes.manual },
                { ActivityTypes.parallel, ActivityPrefixes.parallel },
                { ActivityTypes.review, ActivityPrefixes.review },
                { ActivityTypes.sequential, ActivityPrefixes.sequential },
                { ActivityTypes.runbook, ActivityPrefixes.runbook }
            };

            // setting up the (string) variables which we are going to use to decide what type of WorkItem we are going to create and different options/aspects of it

            string workItemClassName         = string.Empty;
            string workItemMpName            = string.Empty;
            string workItemSettingClassName  = string.Empty;
            string workItemSettingPrefixName = string.Empty;
            string workItemSettingMpName     = string.Empty;
            string workItemTemplateName      = string.Empty;
            string workItemStatusName        = string.Empty;
            string workItemUrgencyName       = string.Empty;
            string workItemImpactName        = string.Empty;
            string workItemCategoryName      = string.Empty;

            // if/elseif code to set the variables that define the differences between what WorkItem type we need to create based on the parameter passed by the Task

            if (parameters.Contains(TaskActions.Service))
            {
                workItemClassName         = ClassTypes.service;
                workItemMpName            = ManagementPacks.serviceLibrary;
                workItemSettingClassName  = WorkItemSettings.service;
                workItemSettingPrefixName = WorkItemPrefixes.service;
                workItemSettingMpName     = ManagementPacks.serviceManagementLibrary;
                workItemTemplateName      = WorkItemTemplates.service;
                workItemStatusName        = EnumTypes.serviceStatusNew;
            }
            else if (parameters.Contains(TaskActions.Change))
            {
                workItemClassName         = ClassTypes.change;
                workItemMpName            = ManagementPacks.changeLibrary;
                workItemSettingClassName  = WorkItemSettings.change;
                workItemSettingPrefixName = WorkItemPrefixes.change;
                workItemSettingMpName     = ManagementPacks.changeManagementLibrary;
                workItemTemplateName      = WorkItemTemplates.change;
                workItemStatusName        = EnumTypes.changeStatusNew;
            }
            else if (parameters.Contains(TaskActions.Problem))
            {
                workItemClassName         = ClassTypes.problem;
                workItemMpName            = ManagementPacks.problemLibrary;
                workItemSettingClassName  = WorkItemSettings.problem;
                workItemSettingPrefixName = WorkItemPrefixes.problem;
                workItemSettingMpName     = ManagementPacks.problemLibrary;
                workItemTemplateName      = WorkItemTemplates.problem;
                workItemStatusName        = EnumTypes.problemStatusActive;
                workItemUrgencyName       = EnumTypes.problemUrgencyLow;
                workItemImpactName        = EnumTypes.problemImpactLow;
                workItemCategoryName      = EnumTypes.problemCategoryDefault;
            }
            else if (parameters.Contains(TaskActions.Release))
            {
                workItemClassName         = ClassTypes.release;
                workItemMpName            = ManagementPacks.releaseLibrary;
                workItemSettingClassName  = WorkItemSettings.release;
                workItemSettingPrefixName = WorkItemPrefixes.release;
                workItemSettingMpName     = ManagementPacks.releaseManagementLibrary;
                workItemTemplateName      = WorkItemTemplates.release;
                workItemStatusName        = EnumTypes.releaseStatusNew;
            }

            // here is the code that does the actual work
            // we wrap this around a try/catch block to handle any exception that may happen and display it in case of failure

            try
            {
                // getting the types we need based on the string variables we have filled earlier based on the WorkItem type we need to create

                ManagementPack workItemMp         = emg.GetManagementPack(workItemMpName, Constants.mpKeyTocken, Constants.mpSMR2Version);
                ManagementPack mpSettings         = emg.GetManagementPack(workItemSettingMpName, Constants.mpKeyTocken, Constants.mpSMR2Version);
                ManagementPack knowledgeLibraryMp = emg.GetManagementPack(ManagementPacks.knowledgeLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version);

                ManagementPackClass workItemClass        = emg.EntityTypes.GetClass(workItemClassName, workItemMp);
                ManagementPackClass workItemClassSetting = emg.EntityTypes.GetClass(workItemSettingClassName, mpSettings);

                EnterpriseManagementObject generalSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(workItemClassSetting.Id, ObjectQueryOptions.Default);

                // here is the foreach loop that processes each class-object (in this case Incident) that was multi-selected in the view before executing the Task

                foreach (NavigationModelNodeBase node in nodes)
                {
                    // we need to setup an IList which contains only 1 GUID that correspons to the Incident we are currently working on (node["Id"])
                    // this is needed because we are using the IObjectProjectionReader.GetData(...) which gets an IList<Guid> as parameter in order to retreive the class-objects we want from the db

                    IList <Guid> bmeIdsList = new List <Guid>();
                    bmeIdsList.Add(new Guid(node[Constants.nodePropertyId].ToString()));

                    // we are setting up the ObjectProjectionCriteria using the "System.WorkItem.Incident.ProjectionType" Type Projection as we need to get all the Relationships of the Incident
                    // we will use ObjectRetrievalOptions.Buffered so that we don't get any data from the db which we don't need - we will only get the data one we call the IObjectProjectionReader.GetData(...) method
                    // we are getting the data reader object using GetObjectProjectionReader(...) and setting its PageSize to 1 because we only need 1 object retrieved here

                    ObjectProjectionCriteria incidentObjectProjection = new ObjectProjectionCriteria(incidentProjection);
                    ObjectQueryOptions       queryOptions             = new ObjectQueryOptions(ObjectPropertyRetrievalBehavior.All);
                    queryOptions.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered;
                    IObjectProjectionReader <EnterpriseManagementObject> incidentReader = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(incidentObjectProjection, queryOptions);
                    incidentReader.PageSize = 1;

                    // we are using EnterpriseManagementObjectProjection for the Incident we are getting from the db instead of EnterpriseManagementObject
                    // this is because we are getting a (Type) Projection object (class-object together with its Relationships & relationship class-objects

                    EnterpriseManagementObjectProjection incident = incidentReader.GetData(bmeIdsList).FirstOrDefault();

                    // we are doing the same for the new WorkItem class-object we are creating because we want to add Relationships (with their relationship class-objects from the Incident) here as well
                    // if we would only have created the new WorkItem class and nothing else with it (no Relationships), we could have used the CreatableEnterpriseManagementObject class (which needs to be used when a new class-object is getting created)

                    EnterpriseManagementObjectProjection workItem = new EnterpriseManagementObjectProjection(emg, workItemClass);

                    // now we need to assign some Template to the new WorkItem (if a default/standard Template exists) in order to already have some Activities created
                    // the Activities and all other Properties of the new WorkItem can be adjusted by modifying the default/standard Template for each WorkItem type

                    if (!string.IsNullOrEmpty(workItemTemplateName))
                    {
                        ManagementPackObjectTemplateCriteria templateCriteria = new ManagementPackObjectTemplateCriteria(string.Format("Name = '{0}'", workItemTemplateName));
                        ManagementPackObjectTemplate         template         = emg.Templates.GetObjectTemplates(templateCriteria).FirstOrDefault();

                        if (template != null)
                        {
                            // if a Template with this name exists, we apply it to the new WorkItem by calling ApplyTemplate(...) on it

                            workItem.ApplyTemplate(template);

                            // if we have a Template, we also need to process each Activity that it contains in order to set the Prefix for each Activity (based on its type)
                            // we are using the activityPrefixMapping variable we defined above in oder to map each Prefix based on each Activity class-type

                            ManagementPack             activityManagementMp = emg.GetManagementPack(ManagementPacks.activityManagementLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version);
                            ManagementPackRelationship workItemContainsActivityRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemContainsActivity, activityLibMp);
                            ManagementPackClass        activitySettingsClass = emg.EntityTypes.GetClass(ClassTypes.activitySettings, activityManagementMp);

                            EnterpriseManagementObject activitySettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(activitySettingsClass.Id, ObjectQueryOptions.Default);

                            // for each Activity that exists in the Template we applied, we are going to get its Prefix setting and apply it to its ID in the format: "PREFIX{0}"
                            // "{0}" is the string pattern we need to set for any new WorkItem (including Activity) class-object we are creating as this will be replaced by the next ID available for the new WorkItem

                            foreach (IComposableProjection activity in workItem[workItemContainsActivityRelationshipClass.Target])
                            {
                                ManagementPackClass activityClass = activity.Object.GetClasses(BaseClassTraversalDepth.None).FirstOrDefault();
                                string prefix = activitySettings[null, activityPrefixMapping[activityClass.Name]].Value as string;
                                activity.Object[null, ActivityProperties.Id].Value = string.Format("{0}{1}", prefix, Constants.workItemPrefixPattern);
                            }
                        }
                    }

                    // we are setting the Properties for the new WorkItem class-object here from some Properties of the inital Incident (add more as needed)
                    // it is of highest importance that we also set its status to New/Active (depending on WorkItem class-type) in order for it to be properly processed by the internal workflows on creation
                    // if we don't set the the correct "creation" Status here, it will never be able to progress into a working state and will remain stuck in a "pending" state

                    ManagementPackEnumerationCriteria workItemStatusNewEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemStatusName));
                    ManagementPackEnumeration         workItemStatusNew             = emg.EntityTypes.GetEnumerations(workItemStatusNewEnumCriteria).FirstOrDefault();

                    workItem.Object[workItemClass, WorkItemProperties.Id].Value          = string.Format("{0}{1}", generalSetting[workItemClassSetting, workItemSettingPrefixName], Constants.workItemPrefixPattern);
                    workItem.Object[workItemClass, WorkItemProperties.Title].Value       = string.Format("{0} ({1})", incident.Object[incidentClass, WorkItemProperties.Title].Value, incident.Object[incidentClass, WorkItemProperties.Id].Value);
                    workItem.Object[workItemClass, WorkItemProperties.Description].Value = incident.Object[incidentClass, WorkItemProperties.Description].Value;
                    workItem.Object[workItemClass, WorkItemProperties.Status].Value      = workItemStatusNew.Id;


                    // due to the fact that the Problem WorkItem does not have any Template we can use to create it, we need to handle this special case
                    // we need to populate all the required fields when creating the Problem WorkItem, or creating it will fail (Urgency, Impact, Category)

                    if (!string.IsNullOrEmpty(workItemUrgencyName))
                    {
                        ManagementPackEnumerationCriteria workItemUrgencyEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemUrgencyName));
                        ManagementPackEnumeration         workItemUrgency             = emg.EntityTypes.GetEnumerations(workItemUrgencyEnumCriteria).FirstOrDefault();
                        workItem.Object[workItemClass, WorkItemProperties.Urgency].Value = workItemUrgency.Id;
                    }

                    if (!string.IsNullOrEmpty(workItemImpactName))
                    {
                        ManagementPackEnumerationCriteria workItemImpactEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemImpactName));
                        ManagementPackEnumeration         workItemImpact             = emg.EntityTypes.GetEnumerations(workItemImpactEnumCriteria).FirstOrDefault();
                        workItem.Object[workItemClass, WorkItemProperties.Impact].Value = workItemImpact.Id;
                    }

                    if (!string.IsNullOrEmpty(workItemCategoryName))
                    {
                        ManagementPackEnumerationCriteria workItemCategoryEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", workItemCategoryName));
                        ManagementPackEnumeration         workItemCategory             = emg.EntityTypes.GetEnumerations(workItemCategoryEnumCriteria).FirstOrDefault();
                        workItem.Object[workItemClass, WorkItemProperties.Category].Value = workItemCategory.Id;
                    }


                    // we are adding the initial Incident to this new WorkItem as related WorkItem (System.WorkItemRelatesToWorkItem)

                    ManagementPackRelationship workItemToWorkItemRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemRelatesToWorkItem, wiLibraryMp);
                    workItem.Add(incident.Object, workItemToWorkItemRelationshipClass.Target);

                    // we are closing the current Incident by setting its Status to Closed and setting a closed date

                    incident.Object[incidentClass, IncidentProperties.Status].Value     = incidentClosedStatus.Id;
                    incident.Object[incidentClass, IncidentProperties.ClosedDate].Value = DateTime.Now.ToUniversalTime();

                    // we create a new (analyst) comment (System.WorkItem.TroubleTicket.AnalystCommentLog) and we add it to the Incident in oder to comment the fact that it was closed tue to this WorkItem Transfomr Task

                    CreatableEnterpriseManagementObject analystComment = new CreatableEnterpriseManagementObject(emg, analystCommentClass);
                    analystComment[analystCommentClass, AnalystCommentProperties.Id].Value          = Guid.NewGuid().ToString();
                    analystComment[analystCommentClass, AnalystCommentProperties.Comment].Value     = string.Format(Constants.incidentClosedComment, workItemClass.Name, workItem.Object.Id.ToString());
                    analystComment[analystCommentClass, AnalystCommentProperties.EnteredBy].Value   = EnterpriseManagementGroup.CurrentUserName;
                    analystComment[analystCommentClass, AnalystCommentProperties.EnteredDate].Value = DateTime.Now.ToUniversalTime();

                    ManagementPackRelationship incidentHasAnalystCommentRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemHasAnalystComment, wiLibraryMp);
                    incident.Add(analystComment, incidentHasAnalystCommentRelationshipClass.Target);

                    // we create an IList of RelationshipTypes we want to transfer from the Incident to the new WorkItem
                    // this is the place we can add any new/custom RelationshipTypes which we want to transfer
                    // just make sure that the RelationshipType can be transfered from an Incident to any other WorkItem class-type

                    IList <ManagementPackRelationship> relationshipsToAddList = new List <ManagementPackRelationship>()
                    {
                        workItemToWorkItemRelationshipClass,
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.createdByUser, wiLibraryMp),
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.affectedUser, wiLibraryMp),
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.assignedToUser, wiLibraryMp),
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemHasAttachment, wiLibraryMp),
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemAboutConfigItem, wiLibraryMp),
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemRelatesToConfigItem, wiLibraryMp),
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.entityToArticle, knowledgeLibraryMp),
                        emg.EntityTypes.GetRelationshipClass(RelationshipTypes.workItemHasCommentLog, wiLibraryMp),
                    };

                    // we are getting an instance of the "System.Membership" RelationshipType as we need to handle RelationshipTypes derived from it as a special case
                    // the reason for this, is that Target class-objects of the "System.Membership" RelationshipType are bound to their Source class-objects
                    // being bound, means that Target class-objects of membership relationships cannot belong to 2 different (Source) class-objects
                    // because of this, we need to make a copy (using "CreatableEnterpriseManagementObject" to create a new object and copying the Properties) of the existing Target class-object
                    // and add that to the new WorkItem instead of adding the already existing Target class-object

                    ManagementPack             systemLibraryMp             = emg.GetManagementPack(ManagementPacks.systemLibrary, Constants.mpKeyTocken, Constants.mpSMR2Version);
                    ManagementPackRelationship membershipRelationshipClass = emg.EntityTypes.GetRelationshipClass(RelationshipTypes.membership, systemLibraryMp);

                    // we are going through each Target & Source Relationships of the Incident as defined in the relationshipsToAddList variable and adding them to the new WorkItem
                    // we are handling the Target RelationshipTypes which are derived from "System.Membership" as a special case as explained above
                    // notice that we are also removing these Relationships from the Incident by calling Remove()
                    // we are removing the Relationships from the Incident for performance purposes - in order to have less Relationships (less data) in the db
                    // comment the "itemProjection.Remove();" in order to keep the Relationships to the Incident as well if needed for some reason

                    foreach (ManagementPackRelationship relationship in relationshipsToAddList)
                    {
                        if (incident[relationship.Target].Any())
                        {
                            foreach (IComposableProjection itemProjection in incident[relationship.Target])
                            {
                                // create a new Target class-object (CreatableEnterpriseManagementObject) and add it to the projection as it is a member of a Membership RelationshipType (as explained above)
                                // notice that we DON'T remove such a Target class-object Relationship because it will also remove the class-object itself (because it is a Membership RelationshipType object and it cannot exist without this Relationship)
                                // we need it to exist because we are copying data from it and it needs to still exist in the db (ex. Attachments - we still need the binary data to exist in the db when we create the new Attachment object)
                                // we could of course delete it after we create the new WorkItem with its Relationships when calling "workItem.Overwrite()", but I chose not to do it

                                if (relationship.IsSubtypeOf(membershipRelationshipClass))
                                {
                                    CreatableEnterpriseManagementObject instance = new CreatableEnterpriseManagementObject(emg, itemProjection.Object.GetClasses(BaseClassTraversalDepth.None).FirstOrDefault());
                                    foreach (ManagementPackProperty property in itemProjection.Object.GetProperties())
                                    {
                                        instance[property.Id].Value = itemProjection.Object[property.Id].Value;
                                    }

                                    instance[null, Constants.entityId].Value = Guid.NewGuid().ToString();

                                    workItem.Add(instance, relationship.Target);
                                }

                                // just add the existing Target object-class as it is not a member of a Membership RelationshipType (as explained above)

                                else
                                {
                                    workItem.Add(itemProjection.Object, relationship.Target);
                                    itemProjection.Remove();
                                }
                            }
                        }

                        if (incident[relationship.Source].Any())
                        {
                            // we just create the new Relationship of the Source class-object to the new WorkItem because this is not affected by the Membership RelationshipType

                            foreach (IComposableProjection itemProjection in incident[relationship.Source])
                            {
                                workItem.Add(itemProjection.Object, relationship.Source);
                                itemProjection.Remove();
                            }
                        }
                    }

                    // this is where we actually save (write) the new data to the db, when calling "Overwrite()" - here saving the Incident we modified (set Status to Closed & deleted Relationships)
                    // before we have just created the new objects and relationships in-memory
                    // this is also the point when almost all of the code validation is being done
                    // if there are any issues really creating/editing/adding these objects/realtionships, this is where we would get the errors

                    incident.Overwrite();

                    // we are want to handle the error here of saving the new WorkItem and its Relationships because we want to re-open the Incident in case there is an issue when creating the new WorkItem

                    try
                    {
                        // this is where we actually save (write) the new data to the db, when calling "Overwrite()" - here saving the new WorkItem we created with its Relationships we added (from the Incident)

                        workItem.Overwrite();
                    }
                    catch (Exception ex)
                    {
                        // if we faild to create the new WorkItem with its Relationships, we want to revert to setting the Incident to an Active Status (we re-open the Incident)

                        ManagementPackEnumerationCriteria incidentActiveEnumCriteria = new ManagementPackEnumerationCriteria(string.Format("Name = '{0}'", EnumTypes.incidentStatusActive));
                        ManagementPackEnumeration         incidentActiveStatus       = emg.EntityTypes.GetEnumerations(incidentActiveEnumCriteria).FirstOrDefault();

                        incident.Object[incidentClass, IncidentProperties.Status].Value     = incidentActiveStatus.Id;
                        incident.Object[incidentClass, IncidentProperties.ClosedDate].Value = null;

                        // again, after applying the new modifications in memory, we need to actually write them to the db using "Overwrite()"

                        incident.Overwrite();

                        // no need to show this because we are just passing it (throwing) to the wrapped try/catch block so it will be displayed and handled there

                        throw ex;
                    }
                }

                // if everything succeeds, we want to refresh the View (in this case, some View that shows Incidents as this is where we are calling our Task from)
                // we want to refresh the view to show the new Status of the Incient (as Closed in this case) - if the View only shows non-Closed Incidents, it will dissapear from the View

                RequestViewRefresh();
            }
            catch (Exception ex)
            {
                // we want to handle all Exceptions here so that the Console does not crash
                // we also want to show a MessageBox window with the Exception details for troubleshooting purposes

                MessageBox.Show(string.Format("Error: {0}: {1}\n\n{2}", ex.GetType().ToString(), ex.Message, ex.StackTrace));
            }
        }
        public override void ExecuteCommand(IList<NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection<string> parameters)
        {
            if (parameters.Contains("Create"))
            {
                WizardStory wizard = new WizardStory();

                //set the icon and title bar
                ResourceManager rm = new ResourceManager("SCSM.Azureautomation.WPF.Connector.Resources", typeof(Resources).Assembly);
                Bitmap bitmap = (Bitmap)rm.GetObject("AzureAutomation2x32");
                IntPtr ptr = bitmap.GetHbitmap();
                BitmapSource bitmapsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                wizard.StoryImage = bitmapsource;
                wizard.WizardWindowTitle = "Create Azure Automation Connector";

                WizardData data = new AzureAutomationWizardData();
                wizard.WizardData = data;

                //add th pages
                wizard.AddLast(new WizardStep("Welcome", typeof(AzureAutomationWelcomePage), wizard.WizardData));
                wizard.AddLast(new WizardStep("Configuration", typeof(AzureAutomationConfigurationPage), wizard.WizardData));
                wizard.AddLast(new WizardStep("Summary", typeof(AzureAutomationSummaryPage), wizard.WizardData));
                wizard.AddLast(new WizardStep("Results", typeof(AzureAutomationResultPage), wizard.WizardData));

                //Create a wizard window and show it
                WizardWindow wizardwindow = new WizardWindow(wizard);
                // this is needed so that WinForms will pass messages on to the hosted WPF control
                System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(wizardwindow);
                wizardwindow.ShowDialog();

                //Update the view when done with the wizard so that the new connector shows
                if (data.WizardResult == WizardResult.Success)
                {
                    RequestViewRefresh();
                }
            }
            else if (parameters.Contains("Edit"))
            {
                //Get the server name to connect to and connect to the server
                String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

                //Get the object using the selected node ID
                String strID = String.Empty;
                foreach (NavigationModelNodeBase node in nodes)
                {
                    strID = node["$Id$"].ToString();
                }
                EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject<EnterpriseManagementObject>(new Guid(strID), ObjectQueryOptions.Default);

                //Create a new "wizard" (also used for property dialogs as in this case), set the title bar, create the data, and add the pages
                WizardStory wizard = new WizardStory();
                wizard.WizardWindowTitle = "Edit Azure Automation Connector";
                WizardData data = new AzureAutomationWizardData(emoAAConnector);
                wizard.WizardData = data;
                wizard.AddLast(new WizardStep("Configuration", typeof(AzureAutomationConfigurationPage), wizard.WizardData));

                //Show the property page
                PropertySheetDialog wizardWindow = new PropertySheetDialog(wizard);

                //Update the view when done so the new values are shown
                bool? dialogResult = wizardWindow.ShowDialog();
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    RequestViewRefresh();
                }
            }
            else if (parameters.Contains("Delete") || parameters.Contains("Disable") || parameters.Contains("Enable"))
            {
                //Get the server name to connect to and create a connection
                String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

                //Get the object using the selected node ID
                String strID = String.Empty;
                foreach (NavigationModelNodeBase node in nodes)
                {
                    strID = node["$Id$"].ToString();
                }
                EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject<EnterpriseManagementObject>(new Guid(strID), ObjectQueryOptions.Default);

                if (parameters.Contains("Delete"))
                {
                    //Remove the object from the database
                    IncrementalDiscoveryData idd = new IncrementalDiscoveryData();
                    idd.Remove(emoAAConnector);
                    idd.Commit(emg);
                }

                //Get the rule using the connector ID
                ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", null, new Version("1.0.0.0"));
                ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");
                String strConnectorID = emoAAConnector[classAAConnector, "Id"].ToString();
                ManagementPackRule ruleConnector = mpConnectors.GetRule(strConnectorID);

                //Update the Enabled property or delete as appropriate
                if (parameters.Contains("Delete"))
                {
                    ruleConnector.Status = ManagementPackElementStatus.PendingDelete;
                }
                else if (parameters.Contains("Disable"))
                {
                    emoAAConnector[classAAConnector, "Enabled"].Value = false;
                    ruleConnector.Enabled = ManagementPackMonitoringLevel.@false;
                    ruleConnector.Status = ManagementPackElementStatus.PendingUpdate;
                }
                else if (parameters.Contains("Enable"))
                {
                    emoAAConnector[classAAConnector, "Enabled"].Value = true;
                    ruleConnector.Enabled = ManagementPackMonitoringLevel.@true;
                    ruleConnector.Status = ManagementPackElementStatus.PendingUpdate;
                }

                //Commit the changes to the connector object and rule
                emoAAConnector.Commit();
                mpConnectors.AcceptChanges();

                //Update the view when done so the item is either removed or the updated Enabled value shows
                RequestViewRefresh();
            }
        }
        private void UpdateConnectorInstance()
        {
            //Get the server name to connect to and connect
            String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

            //Get the Connectors MP and AA Connector Class
            ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", null, new Version("1.0.0.0"));
            ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");

            //Get the Connector object using the object ID
            EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject<EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default);

            //Set the property values to the new values
            emoAAConnector[classAAConnector, "DisplayName"].Value = this.DisplayName;
            emoAAConnector[classAAConnector, "AutomationAccount"].Value = this.AutomationAccount;
            emoAAConnector[classAAConnector, "SubscriptionID"].Value = this.SubscriptionID;
            emoAAConnector[classAAConnector, "ResourceGroup"].Value = this.ResourceGroup;
            emoAAConnector[classAAConnector, "RunAsAccountName"].Value = this.RunAsAccountName;
            emoAAConnector[classAAConnector, "RunAsAccountPassword"].Value = this.RunAsAccountPassword;

            //Update Connector instance
            emoAAConnector.Commit();

            mpConnectors.AcceptChanges();
        }
        private void CreateConnectorInstance()
        {
            try
            {
                //Get the server name to connect to
                String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();

                //Conneect to the server
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

                //Get the System MP so we can get the system key token and version so we can get other MPs using that info
                ManagementPack mpSystem = emg.ManagementPacks.GetManagementPack(SystemManagementPack.System);
                Version verSystemVersion = mpSystem.Version;
                string strSystemKeyToken = mpSystem.KeyToken;

                //Also get the System Center and Connector MPs - we'll need things from those MPs later
                ManagementPack mpSystemCenter = emg.ManagementPacks.GetManagementPack(SystemManagementPack.SystemCenter);
                ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", null, new Version("1.0.0.0"));

                //Get the AzureAutomationConnector class in the Connectors MP
                ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");

                //Create a new CreatableEnterpriseManagementObject.  We'll set the properties on this and then post it to the database.
                EnterpriseManagementObject cemoAAConnector = new CreatableEnterpriseManagementObject(emg, classAAConnector);

                //Sytem.Entity properties
                cemoAAConnector[classAAConnector, "DisplayName"].Value = this.DisplayName;            //Required

                //Microsoft.SystemCenter.Connector properties
                //This is just a tricky way to create a unique ID which conforms to the syntax rules for MP element ID attribute values.
                String strConnectorID = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", "AAConnector", Guid.NewGuid().ToString("N"));
                cemoAAConnector[classAAConnector, "Id"].Value = strConnectorID;                       //Required; Key

                //System.LinkingFramework.DataSource properties
                cemoAAConnector[classAAConnector, "DataProviderDisplayName"].Value = "Azure Automation Connector"; //Optional, shown in Connectors view
                cemoAAConnector[classAAConnector, "Enabled"].Value = true;                            //Optional, shown in Connectors view
                cemoAAConnector[classAAConnector, "Name"].Value = this.DisplayName;

                //SCSM.AzureAutomation.Connecto properties
                cemoAAConnector[classAAConnector, "AutomationAccount"].Value = this.AutomationAccount;
                cemoAAConnector[classAAConnector, "SubscriptionID"].Value = this.SubscriptionID;
                cemoAAConnector[classAAConnector, "ResourceGroup"].Value = this.ResourceGroup;
                cemoAAConnector[classAAConnector, "RunAsAccountName"].Value = this.RunAsAccountName;
                cemoAAConnector[classAAConnector, "RunAsAccountPassword"].Value = this.RunAsAccountPassword;

                //Create Connector instance
                cemoAAConnector.Commit();

                //Accept the rule changes which updates the database
                mpConnectors.AcceptChanges();

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + e.InnerException.Message);
            }
        }
        internal AzureAutomationWizardData(EnterpriseManagementObject emoAAConnector)
        {
            //Get the server name to connect to
            String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();

            //Connect to the server
            EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

            ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", null, new Version("1.0.0.0"));
            ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");

            this.EnterpriseManagementObjectID = emoAAConnector.Id;
            this.DisplayName = emoAAConnector.DisplayName;
            this.ConnectorID = emoAAConnector[classAAConnector, "Id"].ToString();
            this.AutomationAccount = emoAAConnector[classAAConnector, "AutomationAccount"].ToString();
            this.SubscriptionID = emoAAConnector[classAAConnector, "SubscriptionID"].ToString();
            this.ResourceGroup = emoAAConnector[classAAConnector, "ResourceGroup"].ToString();
            this.RunAsAccountName = emoAAConnector[classAAConnector, "RunAsAccountName"].ToString();
            this.RunAsAccountPassword = emoAAConnector[classAAConnector, "RunAsAccountPassword"].ToString();
        }
        public ConnectionsForm(IDataItem Node)
        {
            InitializeComponent();

            try
            {
                emg                                    = GetSession();
                mpWindows                              = emg.ManagementPacks.GetManagementPack("Microsoft.Windows.Library", "31bf3856ad364e35", new Version());
                mpAssetCore                            = emg.ManagementPacks.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
                mpNetworkAssetLibrary                  = emg.ManagementPacks.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version());
                mpNetworkLibrary                       = emg.GetManagementPack("System.NetworkManagement.Library", "31bf3856ad364e35", new Version());
                mpCMLibrary                            = emg.ManagementPacks.GetManagementPack("Microsoft.SystemCenter.ConfigurationManager", "31bf3856ad364e35", new Version());
                classModule                            = emg.EntityTypes.GetClass("SMCenter.Module", mpNetworkAssetLibrary);
                classWindowsComputer                   = emg.EntityTypes.GetClass("SMCenter.WindowsComputer", mpNetworkAssetLibrary);
                classDeployedComputer                  = emg.EntityTypes.GetClass("SMCenter.DeployedComputer", mpNetworkAssetLibrary);
                classComputerNetworkAdapter            = emg.EntityTypes.GetClass("Microsoft.Windows.ComputerNetworkAdapter", mpWindows);
                classNode                              = emg.EntityTypes.GetClass("SMCenter.Node", mpNetworkAssetLibrary);
                classNodePort                          = emg.EntityTypes.GetClass("SMCenter.NodePort", mpNetworkAssetLibrary);
                classLocation                          = emg.EntityTypes.GetClass("SMCenter.Location", mpAssetCore);
                classDevice                            = emg.EntityTypes.GetClass("SMCenter.Device", mpNetworkAssetLibrary);
                classDeviceNetworkAdapter              = emg.EntityTypes.GetClass("SMCenter.Device.NetworkAdapter", mpNetworkAssetLibrary);
                classPatchPanel                        = emg.EntityTypes.GetClass("SMCenter.PatchPanel", mpNetworkAssetLibrary);
                classPatchPanelPort                    = emg.EntityTypes.GetClass("SMCenter.PatchPanelPort", mpNetworkAssetLibrary);
                relComputerRunsWindowsComputer         = emg.EntityTypes.GetRelationshipClass("Microsoft.SystemCenter.ConfigurationManager.DeployedComputerRunsWindowsComputer", mpCMLibrary);
                relComputerHostsComputerNetworkAdapter = emg.EntityTypes.GetRelationshipClass("Microsoft.Windows.ComputerHostsComputerNetworkAdapter", mpWindows);
                relLoctoLoc                            = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mpAssetCore);
                //relNetworkAdapterHasChildNetworkAdapter = emg.EntityTypes.GetRelationshipClass("SMCenter.NetworkAdapterHasChildNetworkAdapter", mpNetworkAssetLibrary);
                relChildNetworkAdapterRefParentNetworkAdapter = emg.EntityTypes.GetRelationshipClass("SMCenter.ChildNetworkAdapterRefParentNetworkAdapter", mpNetworkAssetLibrary);
                //relLocationContainsConfigItem = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsConfigItem", mpAssetCore);
                relConfigItemRefLocation        = emg.EntityTypes.GetRelationshipClass("SMCenter.ConfigItemRefLocation", mpAssetCore);
                relNodeComposedOfNetworkAdapter = emg.EntityTypes.GetRelationshipClass("System.NetworkManagement.NodeComposedOfNetworkAdapter", mpNetworkLibrary);
                relDeviceHostNetworkAdapter     = emg.EntityTypes.GetRelationshipClass("SMCenter.DeviceHostsNetworkAdapter", mpNetworkAssetLibrary);

                this.ConnectionsTreeView.Items.Clear();
                this.CabelsTreeView.Items.Clear();
                TreeViewItem treeitem = new TreeViewItem();

                LogFile = new LogFile(@"C:\LogFile.txt", true);

                CablesTree = new CablesTree(emg, relChildNetworkAdapterRefParentNetworkAdapter, classModule, relConfigItemRefLocation, LogFile);

                //Get CurrentNode
                Guid CurrentNodeId = (Guid)Node["$Id$"];
                EMO = emg.EntityObjects.GetObject <EnterpriseManagementObject>(CurrentNodeId, ObjectQueryOptions.Default);

                this.txtTargetObject.Text = EMO.FullName;

                Guid Id_NA = new Guid();
                if (EMO.IsInstanceOf(classModule))
                {
                    this.CabelsTreeView.Items.Add(CablesTree.CreateTreeViewItem(CurrentNodeId));
                }
                else if (EMO.IsInstanceOf(classWindowsComputer))
                {
                    #region
                    var T_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(CurrentNodeId, relComputerHostsComputerNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
                    {
                        Id_NA = relobj.TargetObject.Id;
                    }
                    this.CabelsTreeView.Items.Add(CablesTree.CreateTreeViewItem(Id_NA));

                    treeitem = ConnectionsTree.Create(Id_NA, emg);
                    if (treeitem != null)
                    {
                        this.ConnectionsTreeView.Items.Add(treeitem);
                    }
                    #endregion
                }
                else if (EMO.IsInstanceOf(classDeployedComputer))
                {
                    #region
                    ObservableCollection <Guid> GuidCol = new ObservableCollection <Guid>();
                    var T_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(CurrentNodeId, relComputerRunsWindowsComputer, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
                    {
                        GuidCol.Add(relobj.TargetObject.Id);
                    }
                    //Для каждого WindowsComputer ищем свой NetworkAdapter
                    foreach (Guid id in GuidCol)
                    {
                        T_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(id, relComputerHostsComputerNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                        foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
                        {
                            Id_NA = relobj.TargetObject.Id;
                        }
                        this.CabelsTreeView.Items.Add(CablesTree.Go(Id_NA));
                        treeitem = ConnectionsTree.Create(Id_NA, emg);
                        if (treeitem != null)
                        {
                            this.ConnectionsTreeView.Items.Add(treeitem);
                        }
                    }
                    #endregion
                }
                else if (EMO.IsInstanceOf(classNode))
                {
                    #region
                    ObservableCollection <Guid> GuidCol = new ObservableCollection <Guid>();
                    var T_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(CurrentNodeId, relNodeComposedOfNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
                    {
                        GuidCol.Add(relobj.TargetObject.Id);
                    }
                    foreach (Guid id in GuidCol)
                    {
                        this.CabelsTreeView.Items.Add(CablesTree.Go(id));
                        treeitem = ConnectionsTree.Create(id, emg);
                        if (treeitem != null)
                        {
                            this.ConnectionsTreeView.Items.Add(treeitem);
                        }
                    }
                    #endregion
                }
                else if (EMO.IsInstanceOf(classNodePort))
                {
                    this.CabelsTreeView.Items.Add(CablesTree.Go(CurrentNodeId));
                    treeitem = ConnectionsTree.Create(CurrentNodeId, emg);
                    if (treeitem != null)
                    {
                        this.ConnectionsTreeView.Items.Add(treeitem);
                    }
                }
                else if (EMO.IsInstanceOf(classDevice))
                {
                    #region
                    var T_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(CurrentNodeId, relDeviceHostNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
                    {
                        Id_NA = relobj.TargetObject.Id;
                    }
                    this.CabelsTreeView.Items.Add(CablesTree.Go(Id_NA));
                    treeitem = ConnectionsTree.Create(Id_NA, emg);
                    if (treeitem != null)
                    {
                        this.ConnectionsTreeView.Items.Add(treeitem);
                    }
                    #endregion
                }
                else if (EMO.IsInstanceOf(classDeviceNetworkAdapter))
                {
                    this.CabelsTreeView.Items.Add(CablesTree.Go(CurrentNodeId));
                    treeitem = ConnectionsTree.Create(CurrentNodeId, emg);
                    if (treeitem != null)
                    {
                        this.ConnectionsTreeView.Items.Add(treeitem);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Initialize procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }
        }
Esempio n. 21
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                string userName = (System.Security.Principal.WindowsIdentity.GetCurrent().Name).Replace("\\", "_");
                //string strlog = @"c:\Temp\SMCLog_" + userName + ".txt";
                //TextWriterTraceListener TL = new TextWriterTraceListener(strlog);
                //Trace.Listeners.Add(TL);
                //Trace.AutoFlush = true;
                GetSession();

                ManagementPack mpCore   = emg.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
                ManagementPack mpHA     = emg.GetManagementPack("SMCenter.HardwareAssetManagement.Library", "75b45bd6835084b1", new Version());
                ManagementPack mpSystem = emg.GetManagementPack("System.Library", "31bf3856ad364e35", new Version());

                HAClass          = emg.EntityTypes.GetClass("SMCenter.HardwareAsset", mpHA);
                ConfItemClass    = emg.EntityTypes.GetClass("System.ConfigItem", mpSystem);
                LocationClass    = emg.EntityTypes.GetClass("SMCenter.Location", mpCore);
                CatalogItemClass = emg.EntityTypes.GetClass("SMCenter.HardwareCatalogItem", mpHA);

                relationHAtoCIClass   = emg.EntityTypes.GetRelationshipClass("SMCenter.HardwareAssetReferencesConfigItem", mpHA);
                relationLocationClass = emg.EntityTypes.GetRelationshipClass("SMCenter.LocationContainsChildLocation", mpCore);

                //Fill Templates
                this.TemplateCatalogItem.PathString = "CatalogItem";
                this.TemplateCatalogItem.mpClass    = CatalogItemClass;

                ManagementPackClass WarrantyClass = emg.EntityTypes.GetClass("SMCenter.WarrantyContract", mpCore);
                this.TemplateWarranty.PathString = "Warranty";
                this.TemplateWarranty.mpClass    = WarrantyClass;

                ManagementPackClass SupportContractClass = emg.EntityTypes.GetClass("SMCenter.SupportContract", mpCore);
                this.TemplateSupportContract.PathString = "SupportContract";
                this.TemplateSupportContract.mpClass    = SupportContractClass;

                ManagementPackClass OrganizationClass = emg.EntityTypes.GetClass("SMCenter.Organization", mpCore);
                this.TemplateOrganization.PathString = "Organization";
                this.TemplateOrganization.mpClass    = OrganizationClass;

                this.TemplateLocationItem.emg                 = emg;
                this.TemplateLocationItem.PathString          = "Location";
                this.TemplateLocationItem.mpClass             = LocationClass;
                this.TemplateLocationItem.mpRelationshipClass = relationLocationClass;
                this.TemplateLocationItem.criteria            = new EnterpriseManagementObjectCriteria("LocationType = '0A607435-3D34-23D1-B38E-B89DDE0A558D'", LocationClass);

                ManagementPackClass CostCenterClass = emg.EntityTypes.GetClass("SMCenter.CostCenter", mpCore);
                this.TemplateCostCenter.PathString = "CostCenter";
                this.TemplateCostCenter.mpClass    = CostCenterClass;

                ManagementPackClass LeaseClass = emg.EntityTypes.GetClass("SMCenter.LeaseContract", mpCore);
                this.TemplateLease.PathString = "Lease";
                this.TemplateLease.mpClass    = LeaseClass;

                ManagementPackClass SupplierClass = emg.EntityTypes.GetClass("SMCenter.Company", mpCore);
                this.TemplateSupplier.PathString = "Supplier";
                this.TemplateSupplier.mpClass    = SupplierClass;

                //Handlers
                this.AddHandler(FormEvents.SubmittedEvent, new EventHandler <FormCommandExecutedEventArgs>(this.OnSubmitted));
                this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler <PreviewFormCommandEventArgs>(this.OnPreviewSubmit));
                //this.AddHandler(FormEvents.SubmittedEvent, new EventHandler<PreviewFormCommandEventArgs>(this.OnSubmitted));
            }
            catch (Exception ex)
            {
                Trace.WriteLine(DateTime.Now + " : " + "UserControl_Loaded Error : " + ex.Message);
            }
        }
        private void CreateConnectorInstance()
        {
            try
            {
                //Get the server name to connect to
                String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();

                //Conneect to the server
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

                //Get the System MP so we can get the system key token and version so we can get other MPs using that info
                ManagementPack mpSystem = emg.ManagementPacks.GetManagementPack(SystemManagementPack.System);
                string strSystemKeyToken = mpSystem.KeyToken;
                ManagementPack mpSubscriptions = emg.GetManagementPack("Microsoft.SystemCenter.Subscriptions", strSystemKeyToken, new Version("1.0.0.0"));

                //Also get the System Center and Connector MPs - we'll need things from those MPs later
                ManagementPack mpSystemCenter = emg.ManagementPacks.GetManagementPack(SystemManagementPack.SystemCenter);
                ManagementPack mpConnectors = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0"));
                ManagementPack mpAAConnectorWorkflows = emg.GetManagementPack("SCSM.AzureAutomation.Workflows", null, new Version("1.0.0.0"));

                //Get the AzureAutomationConnector class in the Connectors MP
                ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");

                //Create a new CreatableEnterpriseManagementObject.  We'll set the properties on this and then post it to the database.
                EnterpriseManagementObject cemoAAConnector = new CreatableEnterpriseManagementObject(emg, classAAConnector);

                //Sytem.Entity properties
                cemoAAConnector[classAAConnector, "DisplayName"].Value = this.DisplayName;            //Required

                //Microsoft.SystemCenter.Connector properties
                //This is just a tricky way to create a unique ID which conforms to the syntax rules for MP element ID attribute values.
                String strConnectorID = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", "AAConnector", Guid.NewGuid().ToString("N"));
                cemoAAConnector[classAAConnector, "Id"].Value = strConnectorID;                       //Required; Key

                //System.LinkingFramework.DataSource properties
                cemoAAConnector[classAAConnector, "DataProviderDisplayName"].Value = "Azure Automation Connector"; //Optional, shown in Connectors view
                cemoAAConnector[classAAConnector, "Enabled"].Value = true;                            //Optional, shown in Connectors view
                cemoAAConnector[classAAConnector, "Name"].Value = this.DisplayName;

                //SCSM.AzureAutomation.Connector properties
                cemoAAConnector[classAAConnector, "AutomationAccount"].Value = this.AutomationAccount;
                cemoAAConnector[classAAConnector, "SubscriptionID"].Value = this.SubscriptionID;
                cemoAAConnector[classAAConnector, "ResourceGroup"].Value = this.ResourceGroup;
                cemoAAConnector[classAAConnector, "RunAsAccountName"].Value = this.RunAsAccountName;
                cemoAAConnector[classAAConnector, "RunAsAccountPassword"].Value = this.RunAsAccountPassword;
                cemoAAConnector[classAAConnector, "RefreshIntervalHours"].Value = this.RefreshIntervalHours;

                //Create Connector instance
                cemoAAConnector.Commit();

                //Now we need to create the CSV Connector rule...

                //Get the Scheduler data source module type from the System MP and the Windows Workflow Task Write Action Module Type from the Subscription MP
                ManagementPackDataSourceModuleType dsmtScheduler = (ManagementPackDataSourceModuleType)mpSystem.GetModuleType("System.Scheduler");
                ManagementPackWriteActionModuleType wamtWindowsWorkflowTaskWriteAction = (ManagementPackWriteActionModuleType)mpSubscriptions.GetModuleType("Microsoft.EnterpriseManagement.SystemCenter.Subscription.WindowsWorkflowTaskWriteAction");

                //Create a new rule for the CSV Connector in the Connectors MP.  Set the name of this rule to be the same as the connector instance ID so there is a pairing between them
                ManagementPackRule ruleAAConnector = new ManagementPackRule(mpAAConnectorWorkflows, strConnectorID);

                //Set the target and other properties of the rule
                ruleAAConnector.Target = mpSystemCenter.GetClass("Microsoft.SystemCenter.SubscriptionWorkflowTarget");

                //Create a new Data Source Module in the new CSV Connector rule
                ManagementPackDataSourceModule dsmSchedule = new ManagementPackDataSourceModule(ruleAAConnector, "DS1");

                //Set the configuration of the data source rule.  Pass in the frequency (number of minutes)
                dsmSchedule.Configuration =
                    "<Scheduler>" +
                        "<SimpleReccuringSchedule>" +
                            "<Interval Unit=\"Hours\">" + strRefreshIntervalHours + "</Interval>" +
                        "</SimpleReccuringSchedule>" +
                        "<ExcludeDates />" +
                    "</Scheduler>";

                //Set the Schedule Data Source Module Type to the Simple Schedule Module Type from the System MP
                dsmSchedule.TypeID = dsmtScheduler;

                //Add the Scheduler Data Source to the Rule
                ruleAAConnector.DataSourceCollection.Add(dsmSchedule);

                //Now repeat essentially the same process for the Write Action module...

                //Create a new Write Action Module in the CSV Connector rule
                ManagementPackWriteActionModule wamAAConnector = new ManagementPackWriteActionModule(ruleAAConnector, "WA1");

                //Set the Configuration XML
                wamAAConnector.Configuration =
                    "<Subscription>" +
                        "<WindowsWorkflowConfiguration>" +
                            //Specify the Windows Workflow Foundation workflow Assembly name here
                            "<AssemblyName>SCSM.AzureAutomation.Workflows.AT</AssemblyName>" +
                            //Specify the type name of the workflow to call in the assembly here:
                            "<WorkflowTypeName>WorkflowAuthoring.RefreshConnector</WorkflowTypeName>" +
                            "<WorkflowParameters>" +
                                //Pass in the parameters here.  In this case the two parameters are the data file path and the mapping file path
                                "<WorkflowParameter Name=\"RefreshConnectorScript_ConnectorId\" Type=\"string\">" + strConnectorID + "</WorkflowParameter>" +
                            "</WorkflowParameters>" +
                            "<RetryExceptions />" +
                            "<RetryDelaySeconds>60</RetryDelaySeconds>" +
                            "<MaximumRunningTimeSeconds>300</MaximumRunningTimeSeconds>" +
                        "</WindowsWorkflowConfiguration>" +
                    "</Subscription>";

                //Set the module type of the module to be the Windows Workflow Task Write Action Module Type from the Subscriptions MP.
                wamAAConnector.TypeID = wamtWindowsWorkflowTaskWriteAction;

                //Add the Write Action Module to the rule
                ruleAAConnector.WriteActionCollection.Add(wamAAConnector);

                //Mark the rule as pending update
                ruleAAConnector.Status = ManagementPackElementStatus.PendingAdd; ;

                //Accept the rule changes which updates the database
                mpAAConnectorWorkflows.AcceptChanges();

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + e.InnerException.Message);
            }
        }
Esempio n. 23
0
        public static TreeViewItem Create(Guid NetworkAdapter_Guid, EnterpriseManagementGroup _emg)
        {
            try
            {
                emg = _emg;
                mpNetworkLibrary       = emg.GetManagementPack("System.NetworkManagement.Library", "31bf3856ad364e35", new Version());
                classNetworkConnection = emg.EntityTypes.GetClass("System.NetworkManagement.NetworkConnection", mpNetworkLibrary);
                relNetworkConnectionConnectedToNetworkAdapter = emg.EntityTypes.GetRelationshipClass("System.NetworkManagement.NetworkConnectionConnectedToNetworkAdapter", mpNetworkLibrary);
                EnterpriseManagementObject E = emg.EntityObjects.GetObject <EnterpriseManagementObject>(NetworkAdapter_Guid, ObjectQueryOptions.Default);
                TreeViewItem mainItem        = new TreeViewItem();
                mainItem.Header     = E.FullName;
                mainItem.Tag        = E.Id;
                mainItem.IsExpanded = true;
                TreeViewItem NCItem     = null;
                Guid         NCItemGuid = new Guid();
                if (NetworkAdapter_Guid != Guid.Empty)
                {
                    //Create NetworkConnection Treeview Item
                    var S_objects = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(NetworkAdapter_Guid, relNetworkConnectionConnectedToNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in S_objects)
                    {
                        NCItem            = new TreeViewItem();
                        NCItem.Header     = relobj.SourceObject[classNetworkConnection, "Key"];
                        NCItem.Tag        = relobj.SourceObject.Id;
                        NCItem.IsExpanded = true;
                        mainItem.Items.Add(NCItem);

                        NCItemGuid = relobj.SourceObject.Id;
                    }
                    var T_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(NCItemGuid, relNetworkConnectionConnectedToNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
                    {
                        //newItem = new TreeViewItem();
                        if (relobj.TargetObject.Id != NetworkAdapter_Guid && NCItem != null)
                        {
                            TreeViewItem NAItem = new TreeViewItem();
                            NAItem.Header     = relobj.TargetObject.FullName;
                            NAItem.Tag        = relobj.TargetObject.Id;
                            NAItem.IsExpanded = true;
                            NCItem.Items.Add(NAItem);
                        }
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("Id Network Adapter is Empty");
                }
                if (NCItem == null)
                {
                    return(null);
                }
                else
                {
                    return(mainItem);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Connections Create procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
                return(null);
            }
        }
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            if (parameters.Contains("Create"))
            {
                WizardStory wizard = new WizardStory();

                //set the icon and title bar
                ResourceManager rm           = new ResourceManager("SCSM.AzureAutomation.WPF.Connector.Resources", typeof(Resources).Assembly);
                Bitmap          bitmap       = (Bitmap)rm.GetObject("AzureAutomation2x24");
                IntPtr          ptr          = bitmap.GetHbitmap();
                BitmapSource    bitmapsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                wizard.StoryImage        = bitmapsource;
                wizard.WizardWindowTitle = "Create Azure Automation Connector";

                WizardData data = new AzureAutomationWizardData();
                wizard.WizardData = data;

                //add th pages
                wizard.AddLast(new WizardStep("Welcome", typeof(AzureAutomationWelcomePage), wizard.WizardData));
                wizard.AddLast(new WizardStep("Configuration", typeof(AzureAutomationConfigurationPage), wizard.WizardData));
                wizard.AddLast(new WizardStep("Summary", typeof(AzureAutomationSummaryPage), wizard.WizardData));
                wizard.AddLast(new WizardStep("Results", typeof(AzureAutomationResultPage), wizard.WizardData));

                //Create a wizard window and show it
                WizardWindow wizardwindow = new WizardWindow(wizard);
                // this is needed so that WinForms will pass messages on to the hosted WPF control
                System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(wizardwindow);
                wizardwindow.ShowDialog();

                //Update the view when done with the wizard so that the new connector shows
                if (data.WizardResult == WizardResult.Success)
                {
                    RequestViewRefresh();
                }
            }
            else if (parameters.Contains("Edit"))
            {
                //Get the server name to connect to and connect to the server
                String strServerName          = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

                //Get the object using the selected node ID
                String strID = String.Empty;
                foreach (NavigationModelNodeBase node in nodes)
                {
                    strID = node["$Id$"].ToString();
                }
                EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strID), ObjectQueryOptions.Default);

                //Create a new "wizard" (also used for property dialogs as in this case), set the title bar, create the data, and add the pages
                WizardStory wizard = new WizardStory();
                wizard.WizardWindowTitle = "Edit Azure Automation Connector";
                WizardData data = new AzureAutomationWizardData(emoAAConnector);
                wizard.WizardData = data;
                wizard.AddLast(new WizardStep("Configuration", typeof(AzureAutomationConfigurationPage), wizard.WizardData));

                //Show the property page
                PropertySheetDialog wizardWindow = new PropertySheetDialog(wizard);

                //Update the view when done so the new values are shown
                bool?dialogResult = wizardWindow.ShowDialog();
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    RequestViewRefresh();
                }
            }
            else if (parameters.Contains("Delete") || parameters.Contains("Disable") || parameters.Contains("Enable"))
            {
                //Get the server name to connect to and create a connection
                String strServerName          = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

                //Get the object using the selected node ID
                String strID = String.Empty;
                foreach (NavigationModelNodeBase node in nodes)
                {
                    strID = node["$Id$"].ToString();
                }
                EnterpriseManagementObject emoAAConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strID), ObjectQueryOptions.Default);

                if (parameters.Contains("Delete"))
                {
                    //Remove the object from the database
                    IncrementalDiscoveryData idd = new IncrementalDiscoveryData();
                    idd.Remove(emoAAConnector);
                    idd.Commit(emg);
                }

                //Get the rule using the connector ID
                ManagementPack      mpConnectors           = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0"));
                ManagementPack      mpAAConnectorWorkflows = emg.GetManagementPack("SCSM.AzureAutomation.Workflows", null, new Version("1.0.0.0"));
                ManagementPackClass classAAConnector       = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");
                String             strConnectorID          = emoAAConnector[classAAConnector, "Id"].ToString();
                ManagementPackRule ruleConnector           = mpAAConnectorWorkflows.GetRule(strConnectorID);

                //Update the Enabled property or delete as appropriate
                if (parameters.Contains("Delete"))
                {
                    ruleConnector.Status = ManagementPackElementStatus.PendingDelete;
                }
                else if (parameters.Contains("Disable"))
                {
                    emoAAConnector[classAAConnector, "Enabled"].Value = false;
                    ruleConnector.Enabled = ManagementPackMonitoringLevel.@false;
                    ruleConnector.Status  = ManagementPackElementStatus.PendingUpdate;
                }
                else if (parameters.Contains("Enable"))
                {
                    emoAAConnector[classAAConnector, "Enabled"].Value = true;
                    ruleConnector.Enabled = ManagementPackMonitoringLevel.@true;
                    ruleConnector.Status  = ManagementPackElementStatus.PendingUpdate;
                }

                //Commit the changes to the connector object and rule
                emoAAConnector.Commit();
                mpAAConnectorWorkflows.AcceptChanges();

                //Update the view when done so the item is either removed or the updated Enabled value shows
                RequestViewRefresh();
            }
        }
        private void CreateConnectorInstance()
        {
            try
            {
                //Get the server name to connect to
                String strServerName = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings", "SDKServiceMachine", "localhost").ToString();

                //Conneect to the server
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup(strServerName);

                //Get the System MP so we can get the system key token and version so we can get other MPs using that info
                ManagementPack mpSystem          = emg.ManagementPacks.GetManagementPack(SystemManagementPack.System);
                string         strSystemKeyToken = mpSystem.KeyToken;
                ManagementPack mpSubscriptions   = emg.GetManagementPack("Microsoft.SystemCenter.Subscriptions", strSystemKeyToken, new Version("1.0.0.0"));

                //Also get the System Center and Connector MPs - we'll need things from those MPs later
                ManagementPack mpSystemCenter         = emg.ManagementPacks.GetManagementPack(SystemManagementPack.SystemCenter);
                ManagementPack mpConnectors           = emg.GetManagementPack("SCSM.AzureAutomation", "ac1fe0583b6c84af", new Version("1.0.0.0"));
                ManagementPack mpAAConnectorWorkflows = emg.GetManagementPack("SCSM.AzureAutomation.Workflows", null, new Version("1.0.0.0"));

                //Get the AzureAutomationConnector class in the Connectors MP
                ManagementPackClass classAAConnector = mpConnectors.GetClass("SCSM.AzureAutomation.Connector");

                //Create a new CreatableEnterpriseManagementObject.  We'll set the properties on this and then post it to the database.
                EnterpriseManagementObject cemoAAConnector = new CreatableEnterpriseManagementObject(emg, classAAConnector);

                //Sytem.Entity properties
                cemoAAConnector[classAAConnector, "DisplayName"].Value = this.DisplayName;            //Required

                //Microsoft.SystemCenter.Connector properties
                //This is just a tricky way to create a unique ID which conforms to the syntax rules for MP element ID attribute values.
                String strConnectorID = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", "AAConnector", Guid.NewGuid().ToString("N"));
                cemoAAConnector[classAAConnector, "Id"].Value = strConnectorID;                       //Required; Key

                //System.LinkingFramework.DataSource properties
                cemoAAConnector[classAAConnector, "DataProviderDisplayName"].Value = "Azure Automation Connector"; //Optional, shown in Connectors view
                cemoAAConnector[classAAConnector, "Enabled"].Value = true;                                         //Optional, shown in Connectors view
                cemoAAConnector[classAAConnector, "Name"].Value    = this.DisplayName;

                //SCSM.AzureAutomation.Connector properties
                cemoAAConnector[classAAConnector, "AutomationAccount"].Value    = this.AutomationAccount;
                cemoAAConnector[classAAConnector, "SubscriptionID"].Value       = this.SubscriptionID;
                cemoAAConnector[classAAConnector, "ResourceGroup"].Value        = this.ResourceGroup;
                cemoAAConnector[classAAConnector, "RunAsAccountName"].Value     = this.RunAsAccountName;
                cemoAAConnector[classAAConnector, "RunAsAccountPassword"].Value = this.RunAsAccountPassword;
                cemoAAConnector[classAAConnector, "RefreshIntervalHours"].Value = this.RefreshIntervalHours;


                //Create Connector instance
                cemoAAConnector.Commit();

                //Now we need to create the CSV Connector rule...

                //Get the Scheduler data source module type from the System MP and the Windows Workflow Task Write Action Module Type from the Subscription MP
                ManagementPackDataSourceModuleType  dsmtScheduler = (ManagementPackDataSourceModuleType)mpSystem.GetModuleType("System.Scheduler");
                ManagementPackWriteActionModuleType wamtWindowsWorkflowTaskWriteAction = (ManagementPackWriteActionModuleType)mpSubscriptions.GetModuleType("Microsoft.EnterpriseManagement.SystemCenter.Subscription.WindowsWorkflowTaskWriteAction");

                //Create a new rule for the CSV Connector in the Connectors MP.  Set the name of this rule to be the same as the connector instance ID so there is a pairing between them
                ManagementPackRule ruleAAConnector = new ManagementPackRule(mpAAConnectorWorkflows, strConnectorID);

                //Set the target and other properties of the rule
                ruleAAConnector.Target = mpSystemCenter.GetClass("Microsoft.SystemCenter.SubscriptionWorkflowTarget");

                //Create a new Data Source Module in the new CSV Connector rule
                ManagementPackDataSourceModule dsmSchedule = new ManagementPackDataSourceModule(ruleAAConnector, "DS1");

                //Set the configuration of the data source rule.  Pass in the frequency (number of minutes)
                dsmSchedule.Configuration =
                    "<Scheduler>" +
                    "<SimpleReccuringSchedule>" +
                    "<Interval Unit=\"Hours\">" + strRefreshIntervalHours + "</Interval>" +
                    "</SimpleReccuringSchedule>" +
                    "<ExcludeDates />" +
                    "</Scheduler>";

                //Set the Schedule Data Source Module Type to the Simple Schedule Module Type from the System MP
                dsmSchedule.TypeID = dsmtScheduler;

                //Add the Scheduler Data Source to the Rule
                ruleAAConnector.DataSourceCollection.Add(dsmSchedule);

                //Now repeat essentially the same process for the Write Action module...

                //Create a new Write Action Module in the CSV Connector rule
                ManagementPackWriteActionModule wamAAConnector = new ManagementPackWriteActionModule(ruleAAConnector, "WA1");

                //Set the Configuration XML
                wamAAConnector.Configuration =
                    "<Subscription>" +
                    "<WindowsWorkflowConfiguration>" +
                    //Specify the Windows Workflow Foundation workflow Assembly name here
                    "<AssemblyName>SCSM.AzureAutomation.Workflows.AT</AssemblyName>" +
                    //Specify the type name of the workflow to call in the assembly here:
                    "<WorkflowTypeName>WorkflowAuthoring.RefreshConnector</WorkflowTypeName>" +
                    "<WorkflowParameters>" +
                    //Pass in the parameters here.  In this case the two parameters are the data file path and the mapping file path
                    "<WorkflowParameter Name=\"RefreshConnectorScript_ConnectorId\" Type=\"string\">" + strConnectorID + "</WorkflowParameter>" +
                    "</WorkflowParameters>" +
                    "<RetryExceptions />" +
                    "<RetryDelaySeconds>60</RetryDelaySeconds>" +
                    "<MaximumRunningTimeSeconds>300</MaximumRunningTimeSeconds>" +
                    "</WindowsWorkflowConfiguration>" +
                    "</Subscription>";

                //Set the module type of the module to be the Windows Workflow Task Write Action Module Type from the Subscriptions MP.
                wamAAConnector.TypeID = wamtWindowsWorkflowTaskWriteAction;

                //Add the Write Action Module to the rule
                ruleAAConnector.WriteActionCollection.Add(wamAAConnector);

                //Mark the rule as pending update
                ruleAAConnector.Status = ManagementPackElementStatus.PendingAdd;;

                //Accept the rule changes which updates the database
                mpAAConnectorWorkflows.AcceptChanges();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + e.InnerException.Message);
            }
        }