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();
        }
 void updateWorkflowStatus(bool isFinished, double percentComplete = 0)
 {
     //Finished Success (ServiceManager.LinkingFramework.Library) (Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.FinishedSuccess) (c277e4d1-d44a-0f6d-5f04-eda27ac426f8)
     //Finished With Error (ServiceManager.LinkingFramework.Library) (Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.FinishedWithError) (ef06aee3-cc98-264d-b265-748a36b685de)
     //Running (ServiceManager.LinkingFramework.Library) (Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.Running) (d34da32a-5ea5-40c0-8afe-06388cf97bf3)
     try
     {
         if (!isFinished)
         {
             emoStatus[null, "SyncPercent"].Value = percentComplete;
         }
         else
         {
             emoStatus[null, "LastRunFinishTime"].Value = DateTime.UtcNow;
             if (hasImportFailure)
             {
                 emoStatus[null, "Status"].Value = mpeSyncStatusEnums.First(mpe => mpe.Name == "Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.FinishedWithError");
             }
             else
             {
                 emoStatus[null, "Status"].Value      = mpeSyncStatusEnums.First(mpe => mpe.Name == "Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.FinishedSuccess");
                 emoStatus[null, "SyncPercent"].Value = percentComplete;
             }
         }
         emoStatus.Commit();
     }
     catch
     { }
 }
        private void OnSubmitted(object sender, FormCommandExecutedEventArgs e)
        {
            try
            {
                CurrentDataItem = this.DataContext as IDataItem;

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

                    if (DrawingImage != null)
                    {
                        MemoryStream ms = new MemoryStream();
                        DrawingImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                        CurrentEMO[classNetworkMap, "Image"].Value = ms;
                        CurrentEMO.Commit();
                        ms.Close();
                    }
                    else
                    {
                        CurrentEMO[classNetworkMap, "Image"].Value = null;
                        CurrentEMO.Commit();
                    }
                }
                else
                {
                    if (DrawingImage != null)
                    {
                        MemoryStream ms = new MemoryStream();
                        DrawingImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                        CreatableEnterpriseManagementObject CreateNetworkMap = new CreatableEnterpriseManagementObject(emg, classNetworkMap);
                        CreateNetworkMap[classNetworkMap, "Image"].Value = ms;
                        CreateNetworkMap.Commit();
                        ms.Close();
                    }
                }
            }
            catch (Exception exc)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "Error in OnSubmitted() " + exc.Message);
            }
        }
Example #4
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            //Getting the emg
            Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>();
            EnterpriseManagementGroup  mg          = session.ManagementGroup;
            EnterpriseManagementObject SWConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("2338f5c9-020a-9c82-28bb-e955ad8751a7"), ObjectQueryOptions.Default);

            SWConnector[null, "SyncNow"].Value = (bool)true;
            SWConnector.Commit();
            MessageBox.Show("Software Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK);
        }
Example #5
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            //Getting the emg
            Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>();
            EnterpriseManagementGroup  mg           = session.ManagementGroup;
            EnterpriseManagementObject LicConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("21c88509-5a22-365b-bdb3-a2122ea4508a"), ObjectQueryOptions.Default);

            LicConnector[null, "SyncNow"].Value = (bool)true;
            LicConnector.Commit();
            MessageBox.Show("License Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK);
        }
Example #6
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            //Getting the emg
            Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>();
            EnterpriseManagementGroup  mg          = session.ManagementGroup;
            EnterpriseManagementObject HWConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("6ec06321-f6c7-6d8c-fa80-cb4df7d63f48"), ObjectQueryOptions.Default);

            HWConnector[null, "SyncNow"].Value = (bool)true;
            HWConnector.Commit();
            MessageBox.Show("Hardware Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK);
        }
Example #7
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            //Getting the emg
            Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession session = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)FrameworkServices.GetService <Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession>();
            EnterpriseManagementGroup  mg           = new EnterpriseManagementGroup("localhost");
            EnterpriseManagementObject OMSConnector = mg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("a34fe17a-0ca7-4b85-08c2-2039ac41ca44"), ObjectQueryOptions.Default);

            OMSConnector[null, "SyncNow"].Value = (bool)true;
            OMSConnector.Commit();
            MessageBox.Show("OMS FUll Synchronization will Start in a while...", "IT Asset Management", MessageBoxButtons.OK);
        }
Example #8
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();
        }
        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;
        }
Example #10
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                // Obtain the MG object from the SCSM Workflow framework
                emg = ServerContextHelper.Instance.ManagementGroup;
                // Get class and enum definitions to correctly process the activity
                mpcWebhookActivity   = emg.EntityTypes.GetClass(new Guid("80bc2a93-1ce0-9773-c37d-f7c59fe7c963"));
                mpeActivityCompleted = emg.EntityTypes.GetEnumeration(new Guid("9de908a1-d8f1-477e-c6a2-62697042b8d9"));
                mpeActivityFailed    = emg.EntityTypes.GetEnumeration(new Guid("144bcd52-a710-2778-2a6e-c62e0c8aae74"));
                // Retrieve the Activity from the SDK
                emoWebhookActivity = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(InstanceId), ObjectQueryOptions.Default);
                // NameValueCollection is an alternative of using JSON, but it would post plaintext data to the webhook instead of a defined structure. This would make it harder to parse the data in the runbook.
                NameValueCollection nvcParameters = new NameValueCollection();
                // Setup the JSON Writer: http://www.newtonsoft.com/json/help/html/ReadingWritingJSON.htm
                StringBuilder sb = new StringBuilder();
                StringWriter  sw = new StringWriter(sb);
                JsonWriter    jw = new JsonTextWriter(sw);
                jw.WriteStartObject();
                for (int i = 1; i <= 10; i++)
                {
                    // Capture all Activity Parameter Name/Value sets that are not null and put them in the JSON array
                    if (emoWebhookActivity[mpcWebhookActivity, "ParameterName" + i].Value != null)
                    {
                        string parameter = emoWebhookActivity[mpcWebhookActivity, "ParameterName" + i].Value.ToString();
                        string value     = emoWebhookActivity[mpcWebhookActivity, "ParameterValue" + i].Value.ToString();
                        nvcParameters.Add(parameter, value);
                        jw.WritePropertyName(parameter);
                        jw.WriteValue(value);
                    }
                }

                // If specified in the activity, add the activity id in there too
                if ((bool)emoWebhookActivity[mpcWebhookActivity, "IncludeActivityId"].Value == true)
                {
                    string parameter = emoWebhookActivity[mpcWebhookActivity, "ActivityIdParameterName"].Value.ToString();
                    string value     = emoWebhookActivity.Id.ToString();
                    nvcParameters.Add(parameter, value);
                    jw.WritePropertyName(parameter);
                    jw.WriteValue(value);
                }

                jw.WriteEndObject();

                // Submit the data to the webhook using a WebClient
                Uri          uri       = new Uri(emoWebhookActivity[mpcWebhookActivity, "URL"].Value.ToString());
                UTF8Encoding _encoding = new UTF8Encoding();
                using (WebClient wc = new WebClient())
                {
                    var response = wc.UploadString(uri, "POST", sb.ToString());
                    //var stringResponse = _encoding.GetString(response);

                    var matches = Regex.Match(response, Regex.Escape("{") + "\"JobIds\"" + Regex.Escape(":") + Regex.Escape("[") + "\"([^\"]+)\"" + Regex.Escape("]") + Regex.Escape("}"));
                    if (matches.Captures.Count < 1)
                    {
                        throw new InvalidOperationException("Unknown Webhook failure");
                    }
                    else
                    {
                        var  jobId = matches.Captures[0];
                        bool ok    = false;
                        int  retry = 5;
                        // obsolete code to prevent colission issues, not needed anymore as the bug was fixed in the workflow MP
                        while (!ok && retry > 0)
                        {
                            try
                            {
                                // Update the activity with the job info returned from the webhook call
                                emoWebhookActivity[mpcWebhookActivity, "StatusText"].Value = "Webhook Triggered with Job ID '" + jobId + "'";
                                ok = true;
                            }
                            catch (Microsoft.EnterpriseManagement.Common.DiscoveryDataModificationCollisionException ex)
                            {
                                retry--;
                                emoWebhookActivity = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(InstanceId), ObjectQueryOptions.Default);
                            }
                        }
                    }
                }
                // If the activity must wait for the runbook to update it, end here. Else, set the activity to completed.
                if (!(bool)emoWebhookActivity[mpcWebhookActivity, "WaitForCallBack"].Value)
                {
                    emoWebhookActivity[mpcWebhookActivity, "Status"].Value = mpeActivityCompleted;
                }
                return(ActivityExecutionStatus.Closed);
            } catch (Exception ex)
            {
                // in case of troubles, update the activity accordingly
                emoWebhookActivity[mpcWebhookActivity, "StatusText"].Value = ex.Message;

                emoWebhookActivity[mpcWebhookActivity, "Status"].Value = mpeActivityFailed;
                return(ActivityExecutionStatus.Closed);
            }
            finally
            {
                // in both OK and NOK situations, save the status info back to the activity
                emoWebhookActivity.Commit();
            }
        }
Example #11
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            try
            {
                //Connect to MG
                IServiceContainer       isContainer = (IServiceContainer)FrameworkServices.GetService(typeof(IServiceContainer));
                IManagementGroupSession imgSession  = (IManagementGroupSession)isContainer.GetService(typeof(IManagementGroupSession));
                if (imgSession == null)
                {
                    MessageBox.Show("Failed to connect to the current session", "Assign Incident Settings", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                EnterpriseManagementGroup emg = imgSession.ManagementGroup;

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

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

                //Setup form
                AdminForm af = new AdminForm();
                if (emoSettings[classSettings, "AssignDomain1"].Value != null)
                {
                    af.textD1.Text = emoSettings[classSettings, "AssignDomain1"].Value.ToString();
                }
                if (emoSettings[classSettings, "AssignDomain2"].Value != null)
                {
                    af.textD2.Text = emoSettings[classSettings, "AssignDomain2"].Value.ToString();
                }
                if (emoSettings[classSettings, "AssignDomain3"].Value != null)
                {
                    af.textD3.Text = emoSettings[classSettings, "AssignDomain3"].Value.ToString();
                }
                if (emoSettings[classSettings, "AssignGroup1"].Value != null)
                {
                    af.textG1.Text = emoSettings[classSettings, "AssignGroup1"].Value.ToString();
                }
                if (emoSettings[classSettings, "AssignGroup2"].Value != null)
                {
                    af.textG2.Text = emoSettings[classSettings, "AssignGroup2"].Value.ToString();
                }
                if (emoSettings[classSettings, "AssignGroup2"].Value != null)
                {
                    af.textG3.Text = emoSettings[classSettings, "AssignGroup3"].Value.ToString();
                }
                if (emoSettings[classSettings, "AssignShowAccount"].Value != null)
                {
                    if (emoSettings[classSettings, "AssignShowAccount"].Value.ToString() == "1")
                    {
                        af.checkShow.Checked = true;
                    }
                }
                if (emoSettings[classSettings, "AssignShowTier"].Value != null)
                {
                    if (emoSettings[classSettings, "AssignShowTier"].Value.ToString() == "1")
                    {
                        af.checkShowTier.Checked = true;
                    }
                }
                if (emoSettings[classSettings, "AssignedUserAlias"].Value != null)
                {
                    af.textAssignedUserName.Text = emoSettings[classSettings, "AssignedUserAlias"].Value.ToString();
                }
                else
                {
                    af.textAssignedUserName.Text = "AssignedUser";
                }
                if (emoSettings[classSettings, "ActionLogAlias"].Value != null)
                {
                    af.textActionLogName.Text = emoSettings[classSettings, "ActionLogAlias"].Value.ToString();
                }
                else
                {
                    af.textActionLogName.Text = "ActionLogs";
                }

                DialogResult dr = af.ShowDialog();

                if (dr != DialogResult.Cancel)
                {
                    //save settings
                    emoSettings[classSettings, "AssignDomain1"].Value = af.textD1.Text;
                    emoSettings[classSettings, "AssignDomain2"].Value = af.textD2.Text;
                    emoSettings[classSettings, "AssignDomain3"].Value = af.textD3.Text;
                    emoSettings[classSettings, "AssignGroup1"].Value  = af.textG1.Text;
                    emoSettings[classSettings, "AssignGroup2"].Value  = af.textG2.Text;
                    emoSettings[classSettings, "AssignGroup3"].Value  = af.textG3.Text;
                    if (af.checkShow.Checked)
                    {
                        emoSettings[classSettings, "AssignShowAccount"].Value = "1";
                    }
                    else
                    {
                        emoSettings[classSettings, "AssignShowAccount"].Value = "0";
                    }
                    if (af.checkShowTier.Checked)
                    {
                        emoSettings[classSettings, "AssignShowTier"].Value = "1";
                    }
                    else
                    {
                        emoSettings[classSettings, "AssignShowTier"].Value = "0";
                    }
                    emoSettings[classSettings, "AssignedUserAlias"].Value = af.textAssignedUserName.Text;
                    emoSettings[classSettings, "ActionLogAlias"].Value    = af.textActionLogName.Text;
                    emoSettings.Commit();
                }
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
        }
Example #12
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            //Used for idataitem (form mode, 1=new form, 2=edit form);
            int iMode = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        //Save
                        cemroAssignedToUser.Commit();

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

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

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

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

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

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

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

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

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

                        //This adds the new idataitem log entry to the entries displayed on the form, it does not over-write the existing entries
                        i[sActionLog] = iLog;
                    }
                }
                catch (System.Exception e)
                {
                    //Oops
                    MessageBox.Show(e.Message + "\n\n" + e.StackTrace, sAppTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }
        }
        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();
            }
        }
        //This Saves the values that have been set throughout the Wizard Pages back into the management pack so the
        //Advanced Action Log Notifier can read them via ((Get-SCSMObject -Class (Get-SCSMClass -Name "AdhocAdam.Advanced.Action.Log.Notify.AdminSettings$")))
        public override void AcceptChanges(WizardMode wizardMode)
        {
            //Get the server name to connect to and then 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 Advanced Action Notifier class by GUID
            ManagementPackClass adhocAdamAALNClass = emg.EntityTypes.GetClass(new Guid("49a053e7-6080-e211-fd79-ca3607eecce7"));

            //Get the SMLets Exchange Connector Settings object using the object GUID
            EnterpriseManagementObject emoAdminSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(this.EnterpriseManagementObjectID, ObjectQueryOptions.Default);

            //Workflow Status
            //Retrieve the unsealed workflow management pack that contains the workflows, to control whether or not the workflows are enabled/disabled
            //https://marcelzehner.ch/2013/07/04/a-look-at-scsm-workflows-and-notifications-and-how-to-manage-them-by-using-scripts/
            ManagementPack     adhocAdamAALWFClass           = emg.ManagementPacks.GetManagementPack(new Guid("4db18489-38fa-895a-7149-902b675dc752"));
            ManagementPackRule assignedNotificationWF        = adhocAdamAALWFClass.GetRule("AdhocAdam.Advanced.Action.Log.Notify.TroubleTicketAnalystCommentNotification");
            ManagementPackRule affectedNotificationWF        = adhocAdamAALWFClass.GetRule("AdhocAdam.Advanced.Action.Log.Notify.TroubleTicketUserCommentNotification");
            ManagementPackRule workItemCommentNotificationWF = adhocAdamAALWFClass.GetRule("AdhocAdam.Advanced.Action.Log.Notify.WorkItemUserCommentNotification");

            assignedNotificationWF.Status        = ManagementPackElementStatus.PendingUpdate;
            affectedNotificationWF.Status        = ManagementPackElementStatus.PendingUpdate;
            workItemCommentNotificationWF.Status = ManagementPackElementStatus.PendingUpdate;

            //Notify Assigned To
            if (this.IsNotifyAssignedUserEnabled == true)
            {
                assignedNotificationWF.Enabled = ManagementPackMonitoringLevel.@true;
            }
            else
            {
                assignedNotificationWF.Enabled = ManagementPackMonitoringLevel.@false;
            }

            //Notify Affected User
            if (this.IsNotifyAffecteddUserEnabled == true)
            {
                affectedNotificationWF.Enabled = ManagementPackMonitoringLevel.@true;
            }
            else
            {
                affectedNotificationWF.Enabled = ManagementPackMonitoringLevel.@false;
            }

            //Service Request Comments
            if (this.IsNotifyWorkItemCommentsEnabled == true)
            {
                workItemCommentNotificationWF.Enabled = ManagementPackMonitoringLevel.@true;
            }
            else
            {
                workItemCommentNotificationWF.Enabled = ManagementPackMonitoringLevel.@false;
            }

            //save the changes back to the unsealed mp
            adhocAdamAALWFClass.AcceptChanges();

            //Azure Settings
            emoAdminSetting[adhocAdamAALNClass, "EnableAzureTranslate"].Value = this.IsAzureTranslateEnabled;
            emoAdminSetting[adhocAdamAALNClass, "ACSAPIKey"].Value            = this.AzureCognitiveServicesTranslateAPIKey;

            //Templates
            try { emoAdminSetting[adhocAdamAALNClass, "TroubleTicketAnalystCommentTemplate"].Value = this.TroubleTicketAnalystCommentTemplate.Id; }
            catch { }
            try { emoAdminSetting[adhocAdamAALNClass, "TroubleTicketUserCommentTemplate"].Value = this.TroubleTicketUserCommentTemplate.Id; }
            catch { }
            try { emoAdminSetting[adhocAdamAALNClass, "WorkItemCommentTemplate"].Value = this.WorkItemCommentLogTemplate.Id; }
            catch { }

            //Update the MP
            emoAdminSetting.Commit();
            this.WizardResult = WizardResult.Success;
        }