Esempio n. 1
0
        public static ManagementPackClass GetClassByName(string strName, EnterpriseManagementGroup emg)
        {
            ManagementPackClassCriteria mpcc        = new ManagementPackClassCriteria(String.Format("Name = '{0}'", strName));
            IList <ManagementPackClass> listClasses = emg.EntityTypes.GetClasses(mpcc);

            if (listClasses.Count > 0)
            {
                return(listClasses[0]);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 2
0
        public static TreeViewItem Create(Guid NetworkAdapter_Guid, EnterpriseManagementGroup _emg, ManagementPackRelationship _relNetworkAdapterHasChildNetworkAdapter)
        {
            emg = _emg;
            relNetworkAdapterHasChildNetworkAdapter = _relNetworkAdapterHasChildNetworkAdapter;
            //mpNetworkAssetLibrary = emg.ManagementPacks.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version());
            //relNetworkAdapterHasChildNetworkAdapter = emg.EntityTypes.GetRelationshipClass("SMCenter.NetworkAdapterHasChildNetworkAdapter", mpNetworkAssetLibrary);
            TreeViewItem TVI = new TreeViewItem();

            if (NetworkAdapter_Guid != Guid.Empty)
            {
                TVI = CreateChildTree(NetworkAdapter_Guid);
            }
            return(TVI);
        }
Esempio n. 3
0
        public static ManagementPackEnumeration GetEnumerationByName(string strName, EnterpriseManagementGroup emg)
        {
            ManagementPackEnumerationCriteria mpec             = new ManagementPackEnumerationCriteria(String.Format("Name = '{0}'", strName));
            IList <ManagementPackEnumeration> listEnumerations = emg.EntityTypes.GetEnumerations(mpec);

            if (listEnumerations.Count > 0)
            {
                return(listEnumerations[0]);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 4
0
        private void TestGettingIncidentsByEnumCriteria()
        {
            EnterpriseManagementGroup    emg = new EnterpriseManagementGroup(txtServerName.Text);
            ManagementPack               mpIncidentLibrary = Helper.GetManagementPackByName("System.WorkItem.Incident.Library", emg);
            ManagementPackClass          mpcIncident       = Helper.GetClassByName("System.WorkItem.Incident", emg);
            ManagementPackProperty       mppClassification = Helper.GetManagementPackClassPropertyByName("System.WorkItem.Incident", "Classification", emg);
            ManagementPackTypeProjection mptpIncident      = Helper.GetTypeProjectionByName("System.WorkItem.Incident.View.ProjectionType", emg);
            ManagementPackEnumeration    mpeClassificationEnterpriseApp = Helper.GetEnumerationByName("IncidentClassificationEnum.EnterpriseApplications", emg);
            string strCriteria = Helper.SearchObjectByEnumerationCriteriaXml(mpeClassificationEnterpriseApp, mpcIncident, mppClassification);

            IObjectProjectionReader <EnterpriseManagementObject> reader = Helper.GetBufferedObjectProjectionReader(strCriteria, 40, mptpIncident, emg);

            MessageBox.Show(reader.Count.ToString());
        }
Esempio n. 5
0
        //private EnterpriseManagementObject NetworkMap { get; set; }
        //private EnterpriseManagementObject LinkedLocation { get; set; }


        public SearchNetworkMap(EnterpriseManagementGroup _emg, ManagementPackRelationship _relConfigItemRefLocation, ManagementPackRelationship _relNetworkMapRefLocation, ManagementPackRelationship _relLoctoLoc, ManagementPackRelationship _relConfigItemRefRack)
        {
            try
            {
                emg = _emg;
                relNetworkMapRefLocation = _relNetworkMapRefLocation;
                relLoctoLoc = _relLoctoLoc;
                relConfigItemRefLocation = _relConfigItemRefLocation;
                relConfigItemRefRack     = _relConfigItemRefRack;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("SearchNetworkMap class constructor error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Esempio n. 6
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            /*
             * This GUID is generated automatically when you import the Management Pack with the singleton admin setting class in it.
             * You can get this GUID by running a query like:
             * Select BaseManagedEntityID, FullName where FullName like ‘%<enter your class ID here>%’
             * where the GUID you want is returned in the BaseManagedEntityID column in the result set
             */
            /*In this above example I imported the MP, and then used:
             *  Select BaseManagedEntityID, FullName
             *  From BaseManagedEntity
             *  where FullName like 'AdhocAdam%'
             * against the ServiceManager DB to figure out the following strSingletonBaseManagedObjectID. Per
             * https://blogs.technet.microsoft.com/servicemanager/2011/05/26/getting-management-pack-elements-using-the-sdk/
             * the id is always unique and never changes as its based on the MP ID, Element Names, and the key token.
             */

            String strSingletonBaseManagedObjectID = "49a053e7-6080-e211-fd79-ca3607eecce7";

            //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 GUID from above – since this is a singleton object we can get it by GUID
            EnterpriseManagementObject emoAdminSetting = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(strSingletonBaseManagedObjectID), 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 = "AdhocAdam - Advanced Action Log Notifier";
            WizardData data = new AdminSettingWizardData(emoAdminSetting);

            wizard.WizardData = data;
            wizard.AddLast(new WizardStep("General", typeof(AdminSettingsForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("Azure", typeof(AzureSettingsForm), wizard.WizardData));
            wizard.AddLast(new WizardStep("About", typeof(AboutForm), 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();
            }
        }
Esempio n. 7
0
 public static string GetStringFromManagementPack(string resource)
 {
     try
     {
         if (projectMP == null)
         {
             EnterpriseManagementGroup emg = ConsoleContext.GetConsoleEMG();
             projectMP = emg.ManagementPacks.GetManagementPack(new Guid("171d60e8-a0df-e4b2-f032-a5af5c8ebe39"));
         }
         return(projectMP.GetStringResource(resource).DisplayName);
     }
     catch
     {
         return("Localization Error.");
     }
 }
Esempio n. 8
0
        public static List <EnterpriseManagementObject> GetCollection(EnterpriseManagementGroup emg, ManagementPackRelationship classRelationship, ManagementPackClass FilterClass, Guid Id, bool IdObjectIsSource)
        {
            try
            {
                List <EnterpriseManagementObject> _Collection = new List <EnterpriseManagementObject>();
                List <EnterpriseManagementObject> Collection  = new List <EnterpriseManagementObject>();
                if (IdObjectIsSource)
                {
                    var items = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items)
                    {
                        _Collection.Add(rel.TargetObject);
                    }
                }
                else
                {
                    var items = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items)
                    {
                        _Collection.Add(rel.SourceObject);
                    }
                }

                //Filter
                if (FilterClass != null)
                {
                    foreach (EnterpriseManagementObject E in _Collection)
                    {
                        if (E.IsInstanceOf(FilterClass))
                        {
                            Collection.Add(E);
                        }
                    }
                }
                else
                {
                    Collection = _Collection;
                }

                return(Collection);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("_Rel GetCollection procedure error : " + ex.Message, "Service Manager");
                return(null);
            }
        }
Esempio n. 9
0
        //Add action log relationship to passed emo
        private bool AddActionLogEntry(
            EnterpriseManagementGroup emg,
            EnterpriseManagementObject emoIncident,
            string strTitle,
            string strDescription
            )
        {
            try
            {
                //Get the System.WorkItem.Library mp
                ManagementPack mpWorkItemLibrary = emg.ManagementPacks.GetManagementPack(new Guid("405D5590-B45F-1C97-024F-24338290453E"));

                //Get the actionlog class
                ManagementPackClass typeActionLog =
                    emg.EntityTypes.GetClass("System.WorkItem.TroubleTicket.ActionLog", mpWorkItemLibrary);

                //Create a new action log entry
                CreatableEnterpriseManagementObject objectActionLog =
                    new CreatableEnterpriseManagementObject(emg, typeActionLog);

                //Setup the action log entry
                objectActionLog[typeActionLog, "Id"].Value          = Guid.NewGuid().ToString();
                objectActionLog[typeActionLog, "Description"].Value = strDescription + "\n";
                objectActionLog[typeActionLog, "Title"].Value       = strTitle;
                objectActionLog[typeActionLog, "EnteredBy"].Value   = UserPrincipal.Current.DisplayName;
                objectActionLog[typeActionLog, "EnteredDate"].Value = DateTime.Now.ToUniversalTime();

                //Get the enumeration and relationship for the actionlog entry
                ManagementPackEnumeration enumActionLog =
                    mpWorkItemLibrary.GetEnumerations().GetItem("System.WorkItem.ActionLogEnum.TaskExecuted");
                objectActionLog[typeActionLog, "ActionType"].Value = enumActionLog;
                ManagementPackRelationship relActionLog =
                    emg.EntityTypes.GetRelationshipClass("System.WorkItem.TroubleTicketHasActionLog", mpWorkItemLibrary);

                //Get the projection for the incident from the emo
                EnterpriseManagementObjectProjection emopIncident = new EnterpriseManagementObjectProjection(emoIncident);

                //Add relationship and save
                emopIncident.Add(objectActionLog, relActionLog.Target);
                emopIncident.Commit();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 10
0
        private void TestGettingARandomNumberOfIncidents()
        {
            EnterpriseManagementGroup    emg               = new EnterpriseManagementGroup(txtServerName.Text);
            ManagementPackClass          mpcIncident       = Helper.GetClassByName("System.WorkItem.Incident", emg);
            ManagementPack               mpIncidentLibrary = mpcIncident.GetManagementPack();
            ManagementPackTypeProjection mptpIncidentFull  = Helper.GetTypeProjectionByName("System.WorkItem.Incident.ProjectionType", emg);
            string strCriteria = Helper.SearchWorkItemByLikeIDCriteriaXml("2", mpIncidentLibrary.Name, mpIncidentLibrary.Version.ToString(), mpIncidentLibrary.KeyToken, mpcIncident.Name);
            IObjectProjectionReader <EnterpriseManagementObject> reader = Helper.GetBufferedObjectProjectionReader(strCriteria, 30, mptpIncidentFull, emg);
            double dIncidentIDSum = 0;

            foreach (EnterpriseManagementObjectProjection emop in reader)
            {
                string strID = emop.Object[mpcIncident, "Id"].Value.ToString();
                dIncidentIDSum += (double)Int32.Parse(strID);
            }
            MessageBox.Show(dIncidentIDSum.ToString());
        }
Esempio n. 11
0
        private void SetRuleStatus(bool bEnabled)
        {
            EnterpriseManagementGroup emg        = new EnterpriseManagementGroup(txtManagementServer.Text);
            string strRuleCriteria               = "Name LIKE 'NotificationSubscription%'";
            ManagementPackRuleCriteria mprc      = new ManagementPackRuleCriteria(strRuleCriteria);
            IList <ManagementPackRule> listRules = emg.Monitoring.GetRules(mprc);
            double dRulesCount = listRules.Count;
            double i           = 0;

            pbProgress.Value = 0;
            pbProgress.Style = ProgressBarStyle.Continuous;
            pbProgress.Show();
            //TODO: Undo this MP hackery.
            ManagementPack mp = null;

            foreach (ManagementPackRule rule in listRules)
            {
                i++;
                if (rule.Enabled != ManagementPackMonitoringLevel.@false && bEnabled == false)
                {
                    rule.Enabled = ManagementPackMonitoringLevel.@false;
                    rule.Status  = ManagementPackElementStatus.PendingUpdate;
                    //TODO: Undo this MP hackery.
                    mp = rule.GetManagementPack();
                }
                else if (rule.Enabled != ManagementPackMonitoringLevel.@true && bEnabled == true)
                {
                    rule.Enabled = ManagementPackMonitoringLevel.@true;
                    rule.Status  = ManagementPackElementStatus.PendingUpdate;
                    //TODO: Undo this MP hackery.
                    mp = rule.GetManagementPack();
                }
                double dProgress = i / (dRulesCount) * 100;
                pbProgress.Value = (int)dProgress;
            }
            pbProgress.Style = ProgressBarStyle.Marquee;
            lblStatus.Text   = "Accepting changes to MP...";
            mp.AcceptChanges();
            pbProgress.Style    = ProgressBarStyle.Continuous;
            pbProgress.Value    = 100;
            lblStatus.Text      = "Done!";
            lblStatus.ForeColor = Color.Red;
            lblStatus.Height    = lblStatus.Height * 3;

            return;
        }
Esempio n. 12
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();
        }
Esempio n. 13
0
 void GetSession()
 {
     // Get the current session, more info: <span class="skimlinks-unlinked">http://blogs.technet.com/servicemanager/archive/2010/02/11/tasks-part-1-tasks-overview.aspx</span>
     try
     {
         IServiceContainer container = (IServiceContainer)FrameworkServices.GetService(typeof(IServiceContainer));
         Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession curSession = (Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession)container.GetService(typeof(Microsoft.EnterpriseManagement.UI.Core.Connection.IManagementGroupSession));
         if (curSession == null)
         {
             throw new ValueUnavailableException("curSession is null");
         }
         emg = curSession.ManagementGroup;
     }
     catch (Exception e)
     {
         System.Windows.MessageBox.Show(DateTime.Now + " : " + "GetSession Error : " + e.Message);
     }
 }
Esempio n. 14
0
        protected override void OnStart(string[] args)
        {
            #if DEBUG
            System.Threading.Thread.Sleep(1000);
            #endif
            eventLog1.WriteEntry("In OnStart");

            // Update the service state to Start Pending.
            ServiceStatus serviceStatus = new ServiceStatus();
            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint     = 100000;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            // Set up a timer to trigger every minute.
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 60000; // 60 seconds
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();

            //Get the server name to connect to
            String strServerName = "localhost";

            //Registry.GetValue(
            //"HKEY_CURRENT_USER\\Software\\Microsoft\\System Center\\2010\\Service Manager\\Console\\User Settings",
            //"SDKServiceMachine",
            //"localhost").ToString();

            try
            {
                //Connect to the server
                enterpriseMngmtGrp = new EnterpriseManagementGroup(strServerName);

                eventLog1.WriteEntry("Connected to SCSM SDK@" + strServerName);
            }
            catch (Exception e)
            {
                eventLog1.WriteEntry("Unable to connect to SCSM SDK@" + strServerName + "\nError was" + e.Message);
            }

            // FE3B3QW-D22-21730C819N
            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
        }
Esempio n. 15
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            iNumberOfLevelsCreated = 0;
            iNumberOfEnumsCreated  = 0;
            EnterpriseManagementGroup emg     = new EnterpriseManagementGroup(txtSCSMServerName.Text);
            ManagementPackEnumeration mpeBase = Helper.GetEnumerationByName(txtBaseEnumName.Text, emg);
            ManagementPack            mpNew   = new ManagementPack(txtNewMPName.Text, txtNewMPName.Text, new Version("1.0.0.0"), emg);

            iNumberOfLevels        = (int)nudNumberOfLevelsToCreate.Value;
            iNumberOfEnumsPerLevel = (int)nudNumberOfEnumsToCreatePerLevel.Value;
            CreateEnumerationsAtALevel("Enum", ref mpeBase, ref mpNew, iNumberOfEnumsPerLevel);
            DialogResult dr = MessageBox.Show(String.Format("Number of enums to be created: {0}", iNumberOfEnumsCreated.ToString()), "Write to MP XML file?", MessageBoxButtons.YesNo);

            if (dr == DialogResult.Yes)
            {
                mpNew.AcceptChanges();
                ManagementPackXmlWriter mpxw = new ManagementPackXmlWriter(txtFolderToWriteFileTo.Text);
                mpxw.WriteManagementPack(mpNew);
            }
        }
Esempio n. 16
0
        static void Main(string[] Args)
        {
            EnterpriseManagementGroup Emg = new EnterpriseManagementGroup("MIMSCSM");

            Guid g = new Guid(“2D7968F72AE76CE2627354D110A35A8A”);

            ManagementPack mpSystem = Emg.ManagementPacks.GetManagementPack(SystemManagementPack.System);

            ManagementPackRelationship relContainment = mpSystem.GetRelationship(“System.Containment”);

            TraversalDepth tdRecursive = TraversalDepth.Recursive;

            IList <EnterpriseManagementObject> listContainedObjects = Emg.EntityObjects.GetRelatedObjects <EnterpriseManagementObject>(guidObjectID, relContainment, tdRecursive, ObjectQueryOptions.Default);

            foreach (EnterpriseManagementObject emo in listContainedObjects)

            {
                Console.WriteLine(emo.DisplayName);
            }
        }
Esempio n. 17
0
        public static EnterpriseManagementObject GetLoggedInUserAsObject(EnterpriseManagementGroup emg)
        {
            EnterpriseManagementObject emoUserToReturn = null;

            string strUserName = System.Environment.UserName;
            string strDomain   = System.Environment.UserDomainName;
            string strUserByUserNameAndDomainCriteria = string.Format("{0} = '{1}' AND {2} = '{3}'", Constants.strPropertyUserName, strUserName, Constants.strPropertyDomain, strDomain);

            ManagementPackClassCriteria                mpccUser = new ManagementPackClassCriteria(String.Format("{0} = '{1}'", Constants.strMPAttributeName, Constants.strClassUser));
            ManagementPackClass                        mpcUser  = GetManagementPackClassByName(Constants.strClassUser, Constants.strManagementPackSystemLibrary, emg);
            EnterpriseManagementObjectCriteria         emocUserByUserNameAndDomain = new EnterpriseManagementObjectCriteria(strUserByUserNameAndDomainCriteria, mpcUser);
            IObjectReader <EnterpriseManagementObject> emoUsers = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(emocUserByUserNameAndDomain, ObjectQueryOptions.Default);

            foreach (EnterpriseManagementObject emoUser in emoUsers)
            {
                //There will be only one if any
                emoUserToReturn = emoUser;
            }
            return(emoUserToReturn);
        }
Esempio n. 18
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            try
            {
                EnterpriseManagementGroup emg = ConsoleContext.GetConsoleEMG();

                if (parameters.Contains("Create"))
                {
                    //do stuff
                    ProjectConnectorHelpers helper = new ProjectConnectorHelpers();
                    ProjectConnectorData    data   = helper.CreateProjectConnector();
                    if (data.WizardResult == WizardResult.Success)
                    {
                        this.RequestViewRefresh();
                    }
                }
                else if (parameters.Contains("Edit"))
                {
                    //do other stuff
                    ProjectConnectorHelpers helper = new ProjectConnectorHelpers();
                    WizardResult            result = helper.EditProjectConnector(nodes[0]);
                    if (result == WizardResult.Success)
                    {
                        this.RequestViewRefresh();
                    }
                }
                else if (parameters.Contains("Delete"))
                {
                    //delete stuff
                    ProjectConnectorHelpers helper = new ProjectConnectorHelpers();
                    if (helper.DeleteProjectConnector(nodes[0]))
                    {
                        this.RequestViewRefresh();
                    }
                }
            }
            catch (Exception ex)
            {
                ConsoleContextHelper.Instance.ShowErrorDialog(ex, string.Empty, ConsoleJobExceptionSeverity.Error);
            }
        }
        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();
        }
        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;
        }
Esempio n. 21
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);
                classRack     = emg.EntityTypes.GetClass("SMCenter.Rack", mpNA);
                //classNetworkMap = emg.EntityTypes.GetClass("SMCenter.NetworkMap", mpNA);

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

                relConfigItemRefRack = emg.EntityTypes.GetRelationshipClass("SMCenter.ConfigItemRefRack", mpNA);
                //relRackContainsConfigItem = emg.EntityTypes.GetRelationshipClass("SMCenter.RackContainsConfigItem", mpNA);

                //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);
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            string strManagementServer = null;

            CommadLineArgumentParser.Arguments strArrayArguments = new Arguments(args);

            if (strArrayArguments["Server"] != null)
            {
                strManagementServer = strArrayArguments["Server"];
            }
            else
            {
                strManagementServer = "localhost";
            }

            EnterpriseManagementGroup emo = new EnterpriseManagementGroup(strManagementServer);

            foreach (String strIUserName in emo.GetConnectedUserNames())
            {
                Console.WriteLine(strIUserName.ToString());
            }
        }
        //execute the Workflow
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext SMEXCOContext)
        {
            //connect to SCSM and get the SMLets Exchange Connector Settings MP
            EnterpriseManagementGroup  emg = new EnterpriseManagementGroup("localhost");
            EnterpriseManagementObject smexcoAdminSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid("a0022e87-75a8-65ee-4581-d923ff06a564"), ObjectQueryOptions.Default);

            //Retrieve the SMExco File Path from the Settings class
            string smexcoFilePath = smexcoAdminSettings[null, "FilePathSMExcoPS"].Value.ToString();

            //load the script into memory
            string smletsExchangeConnector;

            using (var streamReader = new StreamReader(smexcoFilePath, Encoding.UTF8))
            {
                smletsExchangeConnector = streamReader.ReadToEnd();
            }

            // create a Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();

            // create a pipeline, update variables in PowerShell, then execute it
            Pipeline pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(smletsExchangeConnector);
            pipeline.Runspace.SessionStateProxy.SetVariable("ewsdomain", this.ExchangeDomain);
            pipeline.Runspace.SessionStateProxy.SetVariable("ewsusername", this.ExchangeUsername);
            pipeline.Runspace.SessionStateProxy.SetVariable("ewspassword", this.ExchangePassword);
            pipeline.Runspace.SessionStateProxy.SetVariable("ciresonPortalRunAsUsername", this.CiresonPortalUsername);
            pipeline.Runspace.SessionStateProxy.SetVariable("ciresonPortalRunAsPassword", this.CiresonPortalPassword);
            Collection <PSObject> results = pipeline.Invoke();

            runspace.Close();

            //finish
            return(base.Execute(SMEXCOContext));
        }
Esempio n. 24
0
        private void TestGettingIncidentsByGUIDVsWorkItemID()
        {
            EnterpriseManagementGroup emg               = new EnterpriseManagementGroup(txtServerName.Text);
            ManagementPackClass       mpcIncident       = Helper.GetClassByName("System.WorkItem.Incident", emg);
            ManagementPack            mpIncidentLibrary = mpcIncident.GetManagementPack();
            IObjectReader <EnterpriseManagementObject> readerAllIncidents = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(mpcIncident, ObjectQueryOptions.Default);
            ManagementPackTypeProjection mptpIncidentFull = Helper.GetTypeProjectionByName("System.WorkItem.Incident.ProjectionType", emg);
            double dByGUIDElapsedTime       = 0;
            double dByWorkItemIDElapsedTime = 0;
            double dNumberOfTries           = 1000;
            double i = 0;

            do
            {
                i++;
                int intRandomIncident = Helper.GetRandomNumber(0, readerAllIncidents.Count);
                EnterpriseManagementObject emoIncident = readerAllIncidents.ElementAtOrDefault <EnterpriseManagementObject>(intRandomIncident);
                Guid   guidIncidentId = emoIncident.Id;
                string strWorkItemID  = emoIncident[mpcIncident, "Id"].Value.ToString();

                DateTime dtByGUIDStart = DateTime.Now;
                EnterpriseManagementObjectProjection emopIncident = emg.EntityObjects.GetObjectProjectionWithAccessRights <EnterpriseManagementObject>(emoIncident.Id, mptpIncidentFull);
                DateTime dtByGUIDEnd = DateTime.Now;
                TimeSpan tsByGUID    = dtByGUIDEnd - dtByGUIDStart;
                dByGUIDElapsedTime += tsByGUID.Milliseconds;

                DateTime dtByWorkItemIDStart = DateTime.Now;
                string   strCriteria         = Helper.SearchWorkItemByIDCriteriaXml(strWorkItemID, mpIncidentLibrary.Name, mpIncidentLibrary.Version.ToString(), mpIncidentLibrary.KeyToken, mpcIncident.Name);
                IObjectProjectionReader <EnterpriseManagementObject> readerIncident = Helper.GetBufferedObjectProjectionReader(strCriteria, 1, mptpIncidentFull, emg);
                DateTime dtByWorkItemIDEnd = DateTime.Now;
                TimeSpan tsByWorkItemID    = dtByWorkItemIDEnd - dtByWorkItemIDStart;
                dByWorkItemIDElapsedTime += tsByWorkItemID.Milliseconds;
                pbProgress.Value          = (int)(i / dNumberOfTries * 100);
            }while (i < dNumberOfTries);

            MessageBox.Show(string.Format("By GUID: {0}    By Work Item ID: {1}", dByGUIDElapsedTime.ToString(), dByWorkItemIDElapsedTime.ToString()));
        }
        public MultipleMailboxes(WizardData wizardData)
        {
            //2. Turn the blank instance of AdminSettingsWizardData into the one being used when the form was loaded
            settings = wizardData as AdminSettingWizardData;

            InitializeComponent();
            this.DataContext            = wizardData;
            this.adminSettingWizardData = this.DataContext as MultipleMailboxes;

            //This is less than ideal as it means two connections are made to SCSM when loading the form, this was done so the returned GUID from
            //the Additional Mailbox could be looked up and then set as the Selected Item within the drop down
            //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);

            try
            {
                foreach (var mb in settings.AdditionalMailboxes)
                {
                    MailboxListViewControl.Items.Add(new AdditionalMailbox()
                    {
                        MailboxID           = mb.Id,
                        MailboxAddress      = (String)mb.Values[1].ToString(),
                        MailboxWorkItemType = (String)mb.Values[2].ToString(),
                        MailboxIRTemplate   = emg.Templates.GetObjectTemplate(new Guid(mb.Values[4].ToString())),
                        MailboxIRTemplates  = settings.IncidentTemplates,
                        MailboxSRTemplate   = emg.Templates.GetObjectTemplate(new Guid(mb.Values[6].ToString())),
                        MailboxSRTemplates  = settings.ServiceRequestTemplates,
                        MailboxCRTemplate   = emg.Templates.GetObjectTemplate(new Guid(mb.Values[8].ToString())),
                        MailboxCRTemplates  = settings.ChangeRequestTemplates,
                        MailboxPRTemplate   = emg.Templates.GetObjectTemplate(new Guid(mb.Values[10].ToString())),
                        MailboxPRTemplates  = settings.ProblemTemplates
                    });
                }
            }
            catch { }
        }
Esempio n. 26
0
        public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
        {
            //*** IMPORTANT NOTE: The IManagementGroupSession is not a part of the publicly document/supported official SDK and is subject to change in a future release.
            IManagementGroupSession   session = (IManagementGroupSession)FrameworkServices.GetService <IManagementGroupSession>();
            EnterpriseManagementGroup emg     = session.ManagementGroup;

            if (parameters.Contains("Edit"))
            {
                //There will only ever be one item because we are going to limit this task to single select
                foreach (NavigationModelNodeBase node in nodes)
                {
                    //*** IMPORTANT NOTE: The ConsoleContextHelper class is not a part of the publicly document/supported official SDK and is subject to change in a future release.
                    ConsoleContextHelper.Instance.PopoutForm(node);
                }
            }
            else if (parameters.Contains("Delete"))
            {
                MessageBoxResult result = MessageBox.Show("Are you sure you want to delete the selected Cost Centers?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result != MessageBoxResult.Yes)
                {
                    return;
                }

                //Create an IncrementalDiscoveryData "bucket" for capturing all the deletes that will be processed at the same time
                IncrementalDiscoveryData idd = new IncrementalDiscoveryData();

                foreach (NavigationModelNodeBase node in nodes)
                {
                    EnterpriseManagementObject emoCostCenter = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid(node["$Id$"].ToString()), ObjectQueryOptions.Default);
                    idd.Remove(emoCostCenter);
                }

                idd.Commit(emg);
                RequestViewRefresh();
            }
        }
Esempio n. 27
0
 public static TreeViewItem Create(Guid NetworkAdapter_Guid, EnterpriseManagementGroup _emg)
 {
     try
     {
         emg = _emg;
         mpNetworkAssetLibrary = emg.ManagementPacks.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version());
         relNetworkAdapterHasChildNetworkAdapter = emg.EntityTypes.GetRelationshipClass("SMCenter.NetworkAdapterHasChildNetworkAdapter", mpNetworkAssetLibrary);
         TreeViewItem TVI = new TreeViewItem();
         if (NetworkAdapter_Guid != Guid.Empty)
         {
             TVI = CreateTree(NetworkAdapter_Guid);
         }
         else
         {
             System.Windows.MessageBox.Show("Id Network Adapter is Empty");
         }
         return(TVI);
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show("CabelTree Create procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
         return(null);
     }
 }
Esempio n. 28
0
        public override void ExecuteCommand(IList <Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeBase> nodes, Microsoft.EnterpriseManagement.ConsoleFramework.NavigationModelNodeTask task, ICollection <string> parameters)
        {
            try
            {
                // LogFile _LogFile = new LogFile(@"C:\LogForms.txt", true);
                IDataItem dataItem = null;
                //There will only ever be one item because we are going to limit this task to single select
                foreach (NavigationModelNodeBase node in nodes)
                {
                    //Check if task was started from form
                    bool startedFromForm = FormUtilities.Instance.IsNodeWithinForm(nodes[0]);
                    //If started from form
                    if (startedFromForm)
                    {
                        dataItem = FormUtilities.Instance.GetFormDataContext(node);
                    }
                    //Else started from view
                    else
                    {
                        dataItem = node;
                    }
                }

                EnterpriseManagementGroup emg = GetSession();
                ManagementPack            mpAssetCore;
                ManagementPack            mpNetworkAssetLibrary;
                ManagementPack            mpCMLibrary;

                ManagementPackClass classWindowsComputer;
                ManagementPackClass classDeployedComputer;


                ManagementPackRelationship relComputerRunsWindowsComputer;
                mpAssetCore                    = emg.ManagementPacks.GetManagementPack("SMCenter.AssetManagement.Core", "75b45bd6835084b1", new Version());
                mpNetworkAssetLibrary          = emg.ManagementPacks.GetManagementPack("SMCenter.NetworkAssetManagement.Library", "75b45bd6835084b1", new Version());
                mpCMLibrary                    = emg.ManagementPacks.GetManagementPack("Microsoft.SystemCenter.ConfigurationManager", "31bf3856ad364e35", new Version());
                classWindowsComputer           = emg.EntityTypes.GetClass("SMCenter.WindowsComputer", mpNetworkAssetLibrary);
                classDeployedComputer          = emg.EntityTypes.GetClass("SMCenter.DeployedComputer", mpNetworkAssetLibrary);
                relComputerRunsWindowsComputer = emg.EntityTypes.GetRelationshipClass("Microsoft.SystemCenter.ConfigurationManager.DeployedComputerRunsWindowsComputer", mpCMLibrary);

                EnterpriseManagementObject WC = null;
                Guid CurrentNodeId            = (Guid)dataItem["$Id$"];
                EnterpriseManagementObject DC = emg.EntityObjects.GetObject <EnterpriseManagementObject>(CurrentNodeId, ObjectQueryOptions.Default);
                //if (WC.IsInstanceOf(classWindowsComputer))
                //{
                //    var rels = emg.EntityObjects.GetRelationshipObjectsWhereTarget<EnterpriseManagementObject>(WC.Id, relComputerRunsWindowsComputer, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                //    foreach (EnterpriseManagementRelationshipObject<EnterpriseManagementObject> rel in rels)
                //    {
                //        DC = rel.SourceObject;
                //    }
                //}
                //else
                //{
                //    //_LogFile.Write(String.Format("No DC"), false);
                //    System.Windows.MessageBox.Show(DateTime.Now + " : " + "ExecuteCommand Error : " + "Текущий объект не является Windows Computer.");
                //}

                if (DC.IsInstanceOf(classDeployedComputer))
                {
                    var rels = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(DC.Id, relComputerRunsWindowsComputer, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in rels)
                    {
                        WC = rel.TargetObject;
                    }
                }
                else
                {
                    //_LogFile.Write(String.Format("No DC"), false);
                    System.Windows.MessageBox.Show(DateTime.Now + " : " + "ExecuteCommand Error : " + "Текущий объект не является Deployed Computer.");
                }

                if (WC != null)
                {
                    EnterpriseManagementObjectDataType dataType = new EnterpriseManagementObjectDataType(classWindowsComputer);
                    IDataItem itemIdentity = dataType.CreateProxyInstance(WC);
                    Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(itemIdentity);
                }
                else
                {
                    System.Windows.MessageBox.Show(DateTime.Now + " : Нет связанных Windows Computer!", "Service Manager", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "ExecuteCommand Error : " + ex.Message);
            }
        }
Esempio n. 29
0
        public virtual void Initialize(string ServerName)
        {
            EnterpriseManagementGroup emg;
            if (_emg != null && _emg.ConnectionSettings.ServerName == ServerName)
                emg = _emg;
            else
                emg = new EnterpriseManagementGroup(ServerName);

            Initialize(emg);
        }
Esempio n. 30
0
 public virtual void Initialize(EnterpriseManagementGroup emg)
 {
     lock (_lck)
     {
         if (_emg == null || _emg.ConnectionSettings.ServerName != emg.ConnectionSettings.ServerName)
         {
             _emg = emg;
             if (!_emg.IsConnected)
                 _emg.Reconnect();
         }
     }
 }
        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();
        }
 protected bool Initialize(EnterpriseManagementGroup emg, AuthenticationType authType, EventHandler<AuthorizationCodeRequiredEventArgs> codeRequiredHandler, Guid clientId = default(Guid), string clientSecret = null)
 {
     base.Initialize(emg);
     return InitializeClient(authType, codeRequiredHandler, clientId, clientSecret);
 }
Esempio n. 36
0
 public static EnterpriseManagementRelationshipObject <EnterpriseManagementObject> GetSingleRelationship(EnterpriseManagementGroup emg, ManagementPackRelationship classRelationship, Guid Id, bool IdObjectIsSource)
 {
     try
     {
         EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relObject = null;
         if (IdObjectIsSource)
         {
             var items = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
             foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items)
             {
                 relObject = rel;
             }
         }
         else
         {
             var items = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
             foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items)
             {
                 relObject = rel;
             }
         }
         return(relObject);
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show("_Rel procedure error : " + ex.Message, "Service Manager");
         return(null);
     }
 }
Esempio n. 37
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();
            }
        }
        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);
            }
        }