private void Code_ExecuteCode(object sender, EventArgs e)
        {
            try {
                LogEvent("Connecting to SCSM");
                EnterpriseManagementGroup emg = new EnterpriseManagementGroup("localhost");
                LogEvent("Retrieving activity " + this.GetValue(ActivityIdProperty).ToString());
                ManagementPackClass        ActivityClass  = emg.EntityTypes.GetClass(new Guid("42642d4f-d342-3f1b-965c-628a0f4119e2"));
                ManagementPackClass        RequestClass   = emg.EntityTypes.GetClass(new Guid("04b69835-6343-4de2-4b19-6be08c612989"));
                EnterpriseManagementObject ActivityObject = emg.EntityObjects.GetObject <EnterpriseManagementObject>(new Guid((string)this.GetValue(ActivityIdProperty)), ObjectQueryOptions.Default);
                IList <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > Objects = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(ActivityObject.Id, ObjectQueryOptions.Default);
                foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> Object in Objects)
                {
                    if (Object.RelationshipId == new Guid("2da498be-0485-b2b2-d520-6ebd1698e61b"))
                    {
                        LogEvent("Found related SR " + Object.SourceObject.Id.ToString());

                        Object.SourceObject[new Guid("9ca6666e-e25e-244c-5d2d-94268017f4b1")].Value = ActivityObject[new Guid("029dd446-c76c-ab37-a105-235da4f979dd")].Value;
                        LogEvent("Activity Field Updated");
                        Object.Commit();
                    }
                }
            } catch (Exception ex)
            {
                LogEvent(ex.Message, 1);
            }
            finally
            {
                FlushLog(Log, 0);
            }
        }
Example #2
0
        int getStartingSequenceId(IList <EnterpriseManagementObject> relatedActivities, PublishedProject project)
        {
            if (emoProjectAutomationSettings[null, "ActivityStageInsertionEnum"].Value as ManagementPackEnumeration != null)
            {
                //see if any tasks exists in the activity list.  If they do, then set the sequence value equal to the first element.
                if (relatedActivities.Any(a => a[null, "TaskGUID"] == null ? false : (Guid)a[null, "TaskGUID"].Value == project.Tasks.First().Id))
                {
                    return((int)relatedActivities.First(a => a[null, "TaskGUID"] != null && (Guid)a[null, "TaskGUID"].Value == project.Tasks.First().Id)[null, "SequenceId"].Value);
                }
                else
                {
                    EnterpriseManagementObject emoPlaceHolderActivity = relatedActivities.FirstOrDefault(a => a[null, "Stage"].Value ==
                                                                                                         emoProjectAutomationSettings[null, "ActivityStageInsertionEnum"].Value as ManagementPackEnumeration);

                    if (emoPlaceHolderActivity == null) //no stage or the wrong stage was set... default to the end of the sequence.
                    {
                        return(relatedActivities.Count);
                    }
                    else
                    {
                        return((int)emoPlaceHolderActivity[null, "SequenceId"].Value); //we want to start the task insertion at this sequence number.
                    }
                }
            }
            else
            {
                //no enumeration was set as a placeholder for a sequence of activities.  Put all task activities as the end of the sequence.
                return(relatedActivities.Count);
            }
        }
Example #3
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            GroupChooserDialog dialog = new GroupChooserDialog(this.Container);

            dialog.ShowDialog(this);
            if (dialog.DialogResult == DialogResult.OK)
            {
                if (dialog.SelectedItems != null)
                {
                    ChooserControlItem selectedItem = dialog.SelectedItem as ChooserControlItem;
                    if ((selectedItem == null) || (selectedItem.Item == null))
                    {
                    }
                    else
                    {
                        EnterpriseManagementObject item = selectedItem.Item as EnterpriseManagementObject;
                        if (!string.IsNullOrEmpty(item.DisplayName))
                        {
                            txtGroup.Text = item.DisplayName;
                            IsConfigValid = ValidatePageConfiguration();
                        }
                    }
                }
            }
        }
Example #4
0
        //Ищем связанные NA. в случае нахождения модуля - проверяем связь с локацией и сохраняем Location_Id
        EnterpriseManagementRelationshipObject <EnterpriseManagementObject> Get_Relationship(Guid G)
        {
            //try
            //{
            EnterpriseManagementObject EMO = null;
            EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel = null;    //new EnterpriseManagementRelationshipObject<EnterpriseManagementObject>();
            var T_objects = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(G, relChildNetworkAdapterRefParentNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);

            foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
            {
                rel = relobj;
                EMO = relobj.SourceObject;
            }
            if (classModule != null && EMO != null)
            {
                if (EMO.IsInstanceOf(classModule))
                {
                    var G_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(EMO.Id, relConfigItemRefLocation, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                    foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> confobj in G_objects)
                    {
                        Location_Id = confobj.TargetObject.Id;
                    }
                }
            }
            return(rel);
            //}
            //catch (Exception ex)
            //{
            //    System.Windows.MessageBox.Show("Get_Relationship procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
            //    return null;
            //}
        }
 private void brd_SCSForm_MouseDown(object sender, MouseButtonEventArgs e)
 {
     try
     {
         if (this.CabelsTreeView.SelectedItem != null)
         {
             TreeViewItem SelectedTreeItem = (TreeViewItem)this.CabelsTreeView.SelectedItem;
             if (SelectedTreeItem.Header.ToString().Contains("Cable.Footage"))
             {
                 System.Windows.MessageBox.Show("Select object!", "Service Manager", MessageBoxButton.OK, MessageBoxImage.Warning);
             }
             else
             {
                 Guid G = new Guid(SelectedTreeItem.Tag.ToString());
                 EMO = emg.EntityObjects.GetObject <EnterpriseManagementObject>(G, ObjectQueryOptions.Default);
                 var newWindow = new SCSForm(EMO);
                 newWindow.Show();
             }
         }
         else
         {
             System.Windows.MessageBox.Show("Select object!", "Service Manager", MessageBoxButton.OK, MessageBoxImage.Warning);
         }
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show("brd_SCSForm_MouseDown procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
         this.Close();
     }
 }
 //Ищем связанные NA. в случае нахождения модуля - проверяем связь с локацией и сохраняем Location_Id
 EnterpriseManagementRelationshipObject <EnterpriseManagementObject> SubChild(Guid G)
 {
     try
     {
         EnterpriseManagementObject EMO = null;
         EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel = null; //new EnterpriseManagementRelationshipObject<EnterpriseManagementObject>();
         var T_objects = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(G, relNetworkAdapterHasChildNetworkAdapter, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
         foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in T_objects)
         {
             rel = relobj;
             EMO = relobj.TargetObject;
         }
         if (EMO.IsInstanceOf(classModule))
         {
             var G_objects = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(EMO.Id, relLocationContainsConfigItem, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
             foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> confobj in G_objects)
             {
                 Location_Id = confobj.SourceObject.Id;
             }
         }
         return(rel);
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show("SubChild procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
         return(null);
     }
 }
        private void CabelsTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
        {
            try
            {
                this.txtLocation.Text = "";

                TreeViewItem SelectedItem = (TreeViewItem)e.NewValue;
                if (SelectedItem != null)
                {
                    if (!(SelectedItem.Header.ToString().Contains("Cable")))
                    {
                        Guid Guid  = new Guid(SelectedItem.Tag.ToString());
                        var  items = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(Guid, relConfigItemRefLocation, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                        foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in items)
                        {
                            EnterpriseManagementObject E = relobj.TargetObject;
                            this.txtLocation.Text = E[classLocation, "Path"].Value.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("CabelsTreeView_SelectedItemChanged procedure error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }
        }
Example #8
0
 public static EnterpriseManagementObject GetObjectFromSingleRelationship(EnterpriseManagementGroup emg, ManagementPackRelationship classRelationship, Guid Id, bool IdObjectIsSource)
 {
     try
     {
         EnterpriseManagementObject emo_Object = null;
         if (IdObjectIsSource)
         {
             var items = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
             foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items)
             {
                 emo_Object = rel.TargetObject;
             }
         }
         else
         {
             var items = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(Id, classRelationship, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
             foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in items)
             {
                 emo_Object = rel.SourceObject;
             }
         }
         return(emo_Object);
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show("_Rel procedure error : " + ex.Message, "Service Manager");
         return(null);
     }
 }
        static void Main(string[] args)
        {
            Console.WriteLine("Type in the Work Item ID (e.g. 'AC1234'). Or just press enter to grab the first found Timer Activity. Tot test settings type 'settings'");
            string strID = Console.ReadLine();



            EnterpriseManagementGroup emg = new EnterpriseManagementGroup("localhost");


            ManagementPackClass mpcTimerActivity = Common.GetManagementPackClassByName("Cireson.Timer.Activity", emg);
            ManagementPackClass mpcWorkItem      = Common.GetManagementPackClassByName("System.WorkItem", emg);


            EnterpriseManagementObject emoActivity = null;
            Window defaultWindow = null;

            if (String.IsNullOrEmpty(strID))
            {
                var emoReader = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(mpcTimerActivity, ObjectQueryOptions.Default);

                if (emoReader.Count == 0)
                {
                    throw new Exception("Found zero objects of class " + mpcTimerActivity.Name);
                }
                emoActivity = emoReader.First();
            }
            else if (strID == "settings")
            {
                defaultWindow = new TimerActivitySettingsWindow();

                defaultWindow.Width  = 400;
                defaultWindow.Height = 300;
            }
            else
            {
                EnterpriseManagementObjectGenericCriteria cmogc = new EnterpriseManagementObjectGenericCriteria("Name = '" + strID + "'");
                var emoReader = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(cmogc, ObjectQueryOptions.Default);

                if (emoReader.Count == 0)
                {
                    throw new Exception("Found zero objects with id '" + strID + "'");
                }
                emoActivity = emoReader.First();
                var taUserControl = new CiresonTimerActivityUserControl(); //This manually triggers the user control dataContext changed event

                defaultWindow = new Window();


                defaultWindow.Width       = 800;
                defaultWindow.Height      = 1000;
                defaultWindow.Content     = taUserControl;
                taUserControl.DataContext = emoActivity; //This simulates when SCSM sets the datacontext as an idataitem on Window initialization.
            }



            defaultWindow.ShowDialog(); //Make it modal, because we can. Also prevents the window from closing instantly.
            //defaultWindow.Show();
        }
Example #10
0
        public static string GetDataWarehouseConnectionString(this ManagementGroup mg, bool integratedSecurity = true, string extraOptions = null)
        {
            ManagementPackClass        DWClass    = mg.EntityTypes.GetClass(SystemCenterId.DataWarehouseClassId); // GetClass(mg, "Microsoft.SystemCenter.DataWarehouse");
            EnterpriseManagementObject DWInstance = mg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(DWClass, ObjectQueryOptions.Default).FirstOrDefault();

            if (DWInstance != null)
            {
                string DWSQLServerName = DWInstance[SystemCenterId.DataWarehouseClassProperties.MainDatabaseServerNamePropertyId].Value.ToString();
                string DWDataBaseName  = DWInstance[SystemCenterId.DataWarehouseClassProperties.MainDatabaseNamePropertyId].Value.ToString();
                string result          = "Server=" + DWSQLServerName + ";Database=" + DWDataBaseName;
                if (integratedSecurity)
                {
                    result += ";Integrated Security=True";
                }
                else
                {
                    result += ";Integrated Security=False";
                }
                if (!string.IsNullOrEmpty(extraOptions))
                {
                    if (extraOptions[0] != ';')
                    {
                        extraOptions = ";" + extraOptions;
                    }
                    result += extraOptions;
                }
                return(result);
            }
            else
            {
                throw new ObjectNotFoundException("Cannot find Data Warehouse instance. Entire SCOM must be broken.");
            }
        }
Example #11
0
        private void LoadFormDataTimerTypeEnums(EnterpriseManagementObject emoActivity)
        {
            //Load our list of Timer Type enumerations
            var emg = emoActivity.ManagementGroup;

            var mpcTimerActivity = emoActivity.GetLeastDerivedNonAbstractClass().GetManagementPack();

            var enumTimerDelayTypeRootEnum = emg.EntityTypes.GetEnumeration("TimeDelayTypeEnum", mpcTimerActivity); //The room enum.
            var ilistEnumTimerTypes        = (emg.EntityTypes.GetChildEnumerations(enumTimerDelayTypeRootEnum.Id, TraversalDepth.Recursive)).OrderBy(x => x.Ordinal);

            ObservableCollection <ManagementPackEnumeration> ocEnumerations = new ObservableCollection <ManagementPackEnumeration>(ilistEnumTimerTypes);

            this.timeDurationTypeSource = ocEnumerations;

            //Set the selected value that was previously saved, if it exists.
            if (ocEnumerations.Count > 0)
            {
                //And also select the template that was previously saved on the activity.
                ManagementPackEnumeration mpeSavedEnum = GetEnumerationFromEmoProperty(emoActivity, "TimeDelayType_Enum"); //might be null
                ManagementPackEnumeration matchingEnum = null;

                if (mpeSavedEnum != null)
                {
                    matchingEnum = this.timeDurationTypeSource.Where(x => x.Name == mpeSavedEnum.Name).FirstOrDefault();
                }
                if (matchingEnum != null)
                {
                    this.selectedDurationType = matchingEnum; //And select our current value that is saved on the form.
                    //this.SelectedNotificationTemplateDescription = matchingNotificationTemplate.templateDescription;
                }
            }
        }
Example #12
0
        private DateTime?GetDateTimeFromEmoProperty(EnterpriseManagementObject emoObject, string strPropertyName)
        {
            if (emoObject[null, strPropertyName] == null || emoObject[null, strPropertyName].Value == null)
            {
                return(null);
            }

            DateTime?parsedDateTime = emoObject[null, strPropertyName].Value as DateTime?;

            if (parsedDateTime != null)
            {
                parsedDateTime = ((DateTime)parsedDateTime).ToLocalTime();
                return(parsedDateTime);
            }

            //The direct assignment failed? Try a parse.
            DateTime parsedDateTimeTemp;

            if (DateTime.TryParse(strPropertyName, out parsedDateTimeTemp))
            {
                parsedDateTime = (DateTime)parsedDateTimeTemp.ToLocalTime();
                return(parsedDateTime);
            }

            return(null);
        }
        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 from BaseManagedEntity where FullName like '%<enter your class ID here>%'
             * where the GUID you want is returned in the BaseManagedEntityID column in the result set
             */
            String strSingletonBaseManagedObjectID = "4AD8DC00-2333-93D6-5EB4-D372A42DEA7B";

            //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 emoIncidentSLASettings = 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 = "Edit Incident SLA Settings";
            WizardData data = new IncidentSLASettingsWizardData(emoIncidentSLASettings, emg);

            wizard.WizardData = data;
            wizard.AddLast(new WizardStep("Configuration", typeof(Settings), wizard.WizardData));

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

            wizardWindow.ShowDialog();
        }
Example #14
0
        void buildReleaseRecord(EnterpriseManagementObject emoReleaseRecord, EnterpriseManagementObject emoProject)
        {
            try
            {
                //get the project associated with the original change request and query project server for it.
                var projectGuid = (Guid)emoProject[null, "GUID"].Value;
                projectConnector.LoadProject(projectGuid);
                //load the first level project task data
                PublishedProject project = projectConnector.Projects.FirstOrDefault(p => p.Id == projectGuid);

                if (project == null)
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Project was not found on Project Server.  It may have been removed.\r\n\r\nProject Name: {0}\r\nProject GUID: {1}",
                                                                        emoProject.DisplayName, (emoProject[null, "GUID"].Value == null) ? string.Empty : emoProject[null, "GUID"].Value.ToString()), EventLogEntryType.Warning);
                }
                else
                {
                    projectConnector.LoadProjectTaskData(project, 1);

                    //get all activities in the release record
                    var lstReleaseRecordActivites = emg.EntityObjects.GetRelatedObjects <EnterpriseManagementObject>(emoReleaseRecord.Id,
                                                                                                                     mprRelationships.First(r => r.Name == "System.WorkItemContainsActivity"),
                                                                                                                     TraversalDepth.OneLevel,
                                                                                                                     ObjectQueryOptions.Default);

                    buildActivitiesList(lstReleaseRecordActivites, emoReleaseRecord, emoProject, project);

                    EventLog.WriteEntry(strEventLogTitle, string.Format("Succsesfully processed '{0}' activities list.  Any changes will be submiited to the database.", emoReleaseRecord.DisplayName));
                }
            }
            catch (SharePoint.Client.ServerException ex)
            {
                exceptionsList.Add(new BuildReleaseRecordException(string.Format("An error occured while building '{0}' activities.  The related Project is '{1}'.", emoReleaseRecord.DisplayName, emoProject.DisplayName), ex));
            }
        }
        public static ILicenseValidatorProxy LoadLicensingDomain(EnterpriseManagementObject appSettings)
        {
            var domainSetup = new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                DisallowApplicationBaseProbing = false,
                DisallowBindingRedirects       = true,
                DisallowCodeDownload           = true,
                DisallowPublisherPolicy        = true
            };

            var domain = AppDomain.CreateDomain(Guid.NewGuid().ToString(), null, domainSetup);



            using (var stream = GetLicenseClientResource(appSettings))
            {
                var proxy =
                    domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName,
                                                   typeof(LicenseValidatorProxy).FullName, false, BindingFlags.Default, null, new[] { stream }, null, null, null) as
                    ILicenseValidatorProxy;

                if (proxy == null)
                {
                    throw new Exception("Cannot load proxy.");
                }

                return(proxy);
            }
        }
Example #16
0
 public override void ExecuteCommand(IList <NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection <string> parameters)
 {
     try
     {
         EnterpriseManagementGroup emg = ConsoleContext.GetConsoleEMG();
         // (Cireson.ProjectAutomation.Library) (Microsoft.SystemCenter.Connector.ProjectServer.Settings) (5a49b80c-4c34-d189-ca94-a591580f1995)
         ManagementPackClass        mpcSettings = emg.EntityTypes.GetClass(new Guid("5a49b80c-4c34-d189-ca94-a591580f1995"));                           //get the settings class.
         EnterpriseManagementObject emoSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(mpcSettings.Id, ObjectQueryOptions.Default); //get the settings class instance.
         //somewhere here we will have a container for our class data to feed the consoleWizard obj.
         AdminSettingsData admData       = new AdminSettingsData(emoSettings);
         WizardStory       consoleWizard = new WizardStory();
         consoleWizard.WizardData = admData;
         consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strGroomingSettings"), typeof(AdminSettingsGroomingForm), admData));
         consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strStatusSettings"), typeof(AdminSettingsStatusForm), admData));
         consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strProjectTasksSettings"), typeof(AdminSettingsProjectTasksForm), admData));
         consoleWizard.AddLast(new WizardStep(ServiceManagerLocalization.GetStringFromManagementPack("strProjectLicensingSettings"), typeof(AdminSettingsLicensingForm), admData));
         PropertySheetDialog propertyDialog = new PropertySheetDialog(consoleWizard);
         propertyDialog.Width  = 800;
         propertyDialog.Height = 700;
         propertyDialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
         propertyDialog.Title         = ServiceManagerLocalization.GetStringFromManagementPack("strSettings");
         propertyDialog.ShowInTaskbar = true;
         propertyDialog.Icon          = BitmapFrame.Create(System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Microsoft.EnterpriseManagement.ServiceManager.ProjectServer.ConsoleTasks;component/Icons/Image.Cireson.16x16.ico", UriKind.RelativeOrAbsolute)).Stream);
         propertyDialog.ShowDialog();
     }
     catch (Exception ex)
     {
         ConsoleContextHelper.Instance.ShowErrorDialog(ex, string.Empty, ConsoleJobExceptionSeverity.Error);
     }
 }
Example #17
0
        public X1(EnterpriseManagementGroup emg, Guid settingsGuid, string productName)
        {
            _emg         = emg;
            _productName = productName;

            _emoSettings = _emg.EntityObjects.GetObject <EnterpriseManagementObject>(settingsGuid, ObjectQueryOptions.Default);
        }
Example #18
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();

                Guid CurrentNodeId             = (Guid)dataItem["$Id$"];
                EnterpriseManagementObject EMO = emg.EntityObjects.GetObject <EnterpriseManagementObject>(CurrentNodeId, ObjectQueryOptions.Default);
                var newWindow = new SCSForm(EMO);
                newWindow.Show();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "ExecuteCommand Error : " + ex.Message);
            }
        }
Example #19
0
        //Get property for passed emoUser
        public string GetProperty(
            ref EnterpriseManagementGroup emg,
            EnterpriseManagementObject emoIncident,
            ref ManagementPackClass mpcADUser,
            string sProperty
            )
        {
            try
            {
                //Assigned to user relationship Guid
                Guid rel = new Guid("15e577a3-6bf9-6713-4eac-ba5a5b7c4722");

                EnterpriseManagementObject emoAssignedToUser = null;

                foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> obj in
                         emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(emoIncident.Id, TraversalDepth.OneLevel, ObjectQueryOptions.Default))
                {
                    if (obj.RelationshipId == rel)
                    {
                        emoAssignedToUser = obj.TargetObject;
                    }
                }
                return("" + emoAssignedToUser[mpcADUser, sProperty].Value);
            }
            catch
            {
                return("no-one");
            }
        }
Example #20
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DBEngineChooserDialog dialog = new DBEngineChooserDialog(Container);

            dialog.ShowDialog(this);
            if (dialog.DialogResult == DialogResult.OK)
            {
                if (dialog.SelectedItems != null)
                {
                    ChooserControlItem selectedItem = dialog.SelectedItem as ChooserControlItem;
                    if ((selectedItem == null) || (selectedItem.Item == null))
                    {
                    }
                    else
                    {
                        EnterpriseManagementObject item = selectedItem.Item as EnterpriseManagementObject;
                        if (!string.IsNullOrEmpty(item.FullName))
                        {
                            if (item.DisplayName.ToLower() == "MSSQLServer".ToLower() || item.DisplayName.ToLower() == "SQLEXPRESS".ToLower())
                            {
                                txtInstanceName.Text = item.Path;
                            }
                            else
                            {
                                txtInstanceName.Text = item.Path + "\\" + item.DisplayName;
                            }

                            using (ManageQueryOleDBSDKHelper helper = new ManageQueryOleDBSDKHelper(ManagementGroup))
                            {
                                switch (item.GetClasses()[0].Name)
                                {
                                case "Microsoft.SQLServer.DBEngine":
                                    Databases = helper.GetRelatedObjects(item.Id, "Microsoft.SQLServer.Library", "Microsoft.SQLServer.Database");
                                    break;

                                case "Microsoft.SQLServer.2014.DBEngine":
                                    Databases = helper.GetRelatedObjects(item.Id, "Microsoft.SQLServer.2014.Discovery", "Microsoft.SQLServer.2014.Database");
                                    break;

                                case "Microsoft.SQLServer.2016.DBEngine":
                                    Databases = helper.GetRelatedObjects(item.Id, "Microsoft.SQLServer.2016.Discovery", "Microsoft.SQLServer.2016.Database");
                                    break;

                                default:
                                    break;
                                }

                                cmbDatabase.DataSource    = new BindingSource(Databases, null);
                                cmbDatabase.DisplayMember = "DisplayName";
                                cmbDatabase.ValueMember   = "Id";

                                ManagementPackClass winClass = helper.GetManagementPackClass("Microsoft.Windows.Library", "Microsoft.Windows.Computer");

                                principalName = helper.GetObjectsByName(item.Path, winClass).FirstOrDefault().DisplayName;
                            }
                        }
                    }
                }
            }
        }
        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();
        }
Example #22
0
        public WorkItem DownloadWIfromSM(string Id)
        {
            EnterpriseManagementObject wiInSM = null;
            WorkItem wi = new WorkItem();

            EnterpriseManagementObjectCriteria criteria = new EnterpriseManagementObjectCriteria(String.Format("Name='{0}'", Id), wiClass);

            IObjectReader <EnterpriseManagementObject> reader = mg.EntityObjects.
                                                                GetObjectReader <EnterpriseManagementObject>(criteria, ObjectQueryOptions.Default);

            if (reader.Count == 1)
            {    // Found WI
                wiInSM = reader.GetRange(0, 1)[0];
            }
            else
            {
                Console.WriteLine("Can't find Work Item {0}", Id);
                Environment.Exit(2);
            }

            wi.Id                 = Convert.ToString(wiInSM[wiClass, "Id"].Value);
            wi.Title              = Convert.ToString(wiInSM[wiClass, "Title"].Value);
            wi.Description        = Convert.ToString(wiInSM[wiClass, "Description"].Value);
            wi.ContactMethod      = Convert.ToString(wiInSM[wiClass, "ContactMethod"].Value);
            wi.DisplayName        = Convert.ToString(wiInSM[wiClass, "DisplayName"].Value);
            wi.ScheduledStartDate = Convert.ToDateTime(wiInSM[wiClass, "ScheduledStartDate"].Value).ToLocalTime();
            wi.ScheduledEndDate   = Convert.ToDateTime(wiInSM[wiClass, "ScheduledEndDate"].Value).ToLocalTime();
            wi.ActualStartDate    = Convert.ToDateTime(wiInSM[wiClass, "ActualStartDate"].Value).ToLocalTime();
            wi.ActualEndDate      = Convert.ToDateTime(wiInSM[wiClass, "ActualEndDate"].Value).ToLocalTime();
            //            wi.LastModified     = Convert.ToDateTime(wiInSM[null, "LastModified"].Value).ToLocalTime();  // doesnt' work - this one is from System.Entity

            return(wi);
        }
 public void SubmitTaskAsync(Guid taskId, EnterpriseManagementObject mo, Dictionary <string, string> taskParameters, OnTaskStatusChangeDelegate statusChangeCallback)
 {
     Dbg.Log($"Entering {MethodBase.GetCurrentMethod().Name}");
     try
     {
         if (!MPTasks.ContainsKey(taskId))
         {
             GetTaskObjects(taskId);
         }
         if (MPTasks.ContainsKey(taskId))
         {
             Microsoft.EnterpriseManagement.Runtime.TaskConfiguration taskParams = new Microsoft.EnterpriseManagement.Runtime.TaskConfiguration();
             if (taskParameters != null)
             {
                 foreach (KeyValuePair <string, string> paramPair in taskParameters)
                 {
                     taskParams.Overrides.Add(new Pair <ManagementPackOverrideableParameter, string>(MPTasks[taskId].OverrideableParameters[paramPair.Key], paramPair.Value));
                 }
             }
             UpdateTaskStatus("Starting a new task...");
             Guid batchId = ManagementGroup.TaskRuntime.SubmitTask(mo, MPTasks[taskId].ManagementPackTask, taskParams, new Microsoft.EnterpriseManagement.Runtime.TaskStatusChangeCallback(OnTaskStatusChange));
             MPTasks[taskId].TaskCallbacks.Add(batchId, statusChangeCallback);
             UpdateTaskStatus("Waiting on task completion...");
         }
     }
     catch (Exception e)
     {
         MessageBox.Show($"Failed to start task.\r\nError message: {e.Message}.", "Task Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Example #24
0
        private void OnSubmitted(object sender, FormCommandExecutedEventArgs e)
        {
            try
            {
                CurrentDataItem = this.DataContext as IDataItem;


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

                var racks = emg.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(CurrentEMO.Id, relConfigItemRefRack, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in racks)
                {
                    int res;
                    if (!(int.TryParse(this.TemplateRackItem.Unit, out res)) && this.TemplateRackItem.Unit != null)
                    {
                        System.Windows.MessageBox.Show(DateTime.Now + " : " + "Значение Unit должно быть числовым!");
                        return;
                    }
                    if (this.TemplateRackItem.Unit != null)
                    {
                        relobj[relConfigItemRefRack, "UnitIndex"].Value = this.TemplateRackItem.Unit;
                        relobj.Commit();
                    }
                }
            }
            catch (Exception exc)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "Error in OnSubmitted() " + exc.Message);
            }
        }
Example #25
0
        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if (this.DataContext != null && this.DataContext is IDataItem)
                {
                    CurrentDataItem = this.DataContext as IDataItem;
                    if (!((bool)CurrentDataItem["$IsNew$"]))
                    {
                        CurrentEMO = emg.EntityObjects.GetObject <EnterpriseManagementObject>((Guid)CurrentDataItem["$Id$"], ObjectQueryOptions.Default);

                        var racks = emg.EntityObjects.GetRelationshipObjectsWhereSource <EnterpriseManagementObject>(CurrentEMO.Id, relConfigItemRefRack, DerivedClassTraversalDepth.None, TraversalDepth.OneLevel, ObjectQueryOptions.Default);
                        foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> relobj in racks)
                        {
                            if (relobj[relConfigItemRefRack, "UnitIndex"].Value != null)
                            {
                                //System.Windows.MessageBox.Show("Unit " + relobj[relRackContainsConfigItem, "UnitIndex"].Value.ToString());
                                this.TemplateRackItem.Unit = relobj[relConfigItemRefRack, "UnitIndex"].Value.ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                System.Windows.MessageBox.Show(DateTime.Now + " : " + "Error in DataContextChanged() " + exc.Message);
            }
        }
 private IChooserControlItem CreateChooserControlItem(EnterpriseManagementObject DBEngine)
 {
     if (!localImageCache.ContainsKey(DBEngine.Id))
     {
         localImageCache.Add(DBEngine.Id, DBEngineImage);
     }
     return(new ChooserControlItem(DBEngine.Id.ToString(), DBEngine, this.DBEngineImage));
 }
Example #27
0
        private string GetProductKey()
        {
            EnterpriseManagementObject emoLicenceSettings =
                _emg.EntityObjects.GetObject <EnterpriseManagementObject>(
                    new Guid("a0dc046a-66eb-a926-23b7-9e060fdf6fe9"), ObjectQueryOptions.Default);

            return(emoLicenceSettings[null, "ProductKey"].Value as string);
        }
Example #28
0
 private IChooserControlItem CreateChooserControlItem(EnterpriseManagementObject current)
 {
     if (!localImageCache.ContainsKey(current.Id))
     {
         localImageCache.Add(current.Id, GroupsImage);
     }
     return(new ChooserControlItem(current.Id.ToString(), current, GroupsImage));
 }
Example #29
0
        void setupEnterpriseManagementObjects()
        {
            mpManagementPacks = emg.ManagementPacks.GetManagementPacks(
                new List <Guid>()
            {
                new Guid("171d60e8-a0df-e4b2-f032-a5af5c8ebe39"),    //Cireson Project Server Automation Library (Cireson.ProjectAutomation.Library) (171d60e8-a0df-e4b2-f032-a5af5c8ebe39)
                new Guid("6c2bb84d-3c1f-4006-c551-6ef50179e2e3"),    //System Work Item Change Request Library (System.WorkItem.ChangeRequest.Library) (6c2bb84d-3c1f-4006-c551-6ef50179e2e3)
                new Guid("50ba92b8-f5c7-fa12-4893-0a55df43d7ce"),    //System WorkItem Release Record Library (System.WorkItem.ReleaseRecord.Library) (50ba92b8-f5c7-fa12-4893-0a55df43d7ce)
                new Guid("545131f0-58de-1914-3a82-4fcac9100a33")     //Windows Core Library (Microsoft.Windows.Library) (545131f0-58de-1914-3a82-4fcac9100a33)
            });

            mpcClasses = emg.EntityTypes.GetClasses(
                new List <Guid>()
            {
                new Guid("5a49b80c-4c34-d189-ca94-a591580f1995"),    // (Cireson.ProjectAutomation.Library) (Microsoft.SystemCenter.Connector.ProjectServer.Settings) (5a49b80c-4c34-d189-ca94-a591580f1995)
                new Guid("e786e1c7-b1fe-5b8b-ef8f-9e2dc346c44f"),    //Dependent Activity (System.WorkItem.Activity.Library) (System.WorkItem.Activity.DependentActivity) (e786e1c7-b1fe-5b8b-ef8f-9e2dc346c44f)
                new Guid("d02dc3b6-d709-46f8-cb72-452fa5e082b8"),    //Release Record (System.WorkItem.ReleaseRecord.Library) (System.WorkItem.ReleaseRecord) (d02dc3b6-d709-46f8-cb72-452fa5e082b8)
                //new Guid("d581d2d6-b6cd-b558-7ac7-db233a7c82ec"), //Project Server Connector (Cireson.ProjectAutomation.Library) (Microsoft.SystemCenter.Connector.ProjectServer) (d581d2d6-b6cd-b558-7ac7-db233a7c82ec)
                new Guid("d2cf790e-437d-5cc4-6276-abe484c89fe6"),    //Cireson Project Task Activity (Cireson.ProjectAutomation.Library) (Cireson.ProjectAutomation.ProjectTask.Activity) (d2cf790e-437d-5cc4-6276-abe484c89fe6)
                //new Guid("42642d4f-d342-3f1b-965c-628a0f4119e2"), //Activity (System.WorkItem.Activity.Library) (System.WorkItem.Activity) (42642d4f-d342-3f1b-965c-628a0f4119e2)
                new Guid("dabf07ea-6047-b6d7-f8d3-e88ac1d260e9"),    //Cireson Project (Cireson.ProjectAutomation.Library) (Cireson.ProjectAutomation.Project) (dabf07ea-6047-b6d7-f8d3-e88ac1d260e9)
                new Guid("3567434d-015f-8dcc-f188-0a407f3a2168")     //Active Directory User or Group (Microsoft.Windows.Library) (Microsoft.AD.UserBase) (3567434d-015f-8dcc-f188-0a407f3a2168)
            });

            mprRelationships = emg.EntityTypes.GetRelationshipClasses(
                new List <Guid>()
            {
                new Guid("473c9e8a-2d84-2286-36b7-17e01c9455dd"),    //Depends on Work Item (System.WorkItem.Activity.Library) (System.DependentActivityDependsOnWorkItem) (473c9e8a-2d84-2286-36b7-17e01c9455dd)
                new Guid("2da498be-0485-b2b2-d520-6ebd1698e61b"),    //Contains Activity (System.WorkItem.Activity.Library) (System.WorkItemContainsActivity) (2da498be-0485-b2b2-d520-6ebd1698e61b)
                new Guid("6f0cb41b-9f7b-f720-9c50-6d54bd56e498"),    //(Cireson) WorkItem Has Project (Cireson.ProjectAutomation.Library) (Cireson.ProjectAutomation.WorkItemHasProject) (6f0cb41b-9f7b-f720-9c50-6d54bd56e498)
                new Guid("da3123d1-2b52-a281-6f42-33d0c1f06ab4"),    //Has Parent Work Item (System.WorkItem.Library) (System.WorkItemHasParentWorkItem) (da3123d1-2b52-a281-6f42-33d0c1f06ab4)
                new Guid("15e577a3-6bf9-6713-4eac-ba5a5b7c4722"),    //Assigned To User (System.WorkItem.Library) (System.WorkItemAssignedToUser) (15e577a3-6bf9-6713-4eac-ba5a5b7c4722)
                new Guid("d96c8b59-8554-6e77-0aa7-f51448868b43"),    //Is Related to Configuration Item (System.WorkItem.Library) (System.WorkItemRelatesToConfigItem) (d96c8b59-8554-6e77-0aa7-f51448868b43)
                new Guid("cd1890b5-fd99-b732-14a3-8bb7bcd0320f")     //Project Has Task (Cireson.ProjectAutomation.Library) (Cireson.ProjectAutomation.ProjectHasTask) (cd1890b5-fd99-b732-14a3-8bb7bcd0320f)
            });


            //ManagementPackTypeProjection mptpProjectTaskActivityRelatesToProject = emg.EntityTypes.GetTypeProjection("Cireson.ProjectAutomation.ProjectTaskActivityRelatesToProject.ProjectionType",
            //    mpManagementPacks.First(mp => mp.Name == "Cireson.ProjectAutomation.Library"));

            //get the settings class instance.  We'll need this later when we query Project for tasks
            emoProjectAutomationSettings = emg.EntityObjects.GetObject <EnterpriseManagementObject>(
                mpcClasses.First(mpc => mpc.Name == "Microsoft.SystemCenter.Connector.ProjectServer.Settings").Id, ObjectQueryOptions.Default);

            //get needed enumerations
            activityStatusEnums = emg.EntityTypes.GetChildEnumerations(new Guid("57db4880-000e-20bb-2f9d-fe4e8aca3cf6"), TraversalDepth.Recursive);
            releaseStatusEnums  = emg.EntityTypes.GetChildEnumerations(new Guid("8909ce55-a87f-2d7e-eb64-aba670596696"), TraversalDepth.Recursive);
            //find the activity set as a placeholder in settings
            //ManagementPackEnumeration mpeInsertionStage = emoProjectAutomationSettings[null, "ActivityStageInsertionEnum"].Value as ManagementPackEnumeration;

            //get the connector instance
            emoConnector = emg.EntityObjects.GetObject <EnterpriseManagementObject>(
                (Guid)emoProjectAutomationSettings[null, "ConnectorId"].Value, ObjectQueryOptions.Default);

            //get the task activity prefix
            sTaskActivityPrefix = emoProjectAutomationSettings[null, "TaskActivityPrefix"].Value as string;
        }
        private static MemoryStream GetLicenseClientResource(EnterpriseManagementObject appSettings)
        {
            var mp = appSettings.GetLeastDerivedNonAbstractClass().GetManagementPack();

            var assemblyResource =
                mp.GetResources <ManagementPackResource>()
                .FirstOrDefault(r => r.FileName == "LicenseManagement.Client.dll");

            return(appSettings.ManagementGroup.Resources.GetResourceData(assemblyResource) as MemoryStream);
        }
        public async Task ProcessActivity(EnterpriseManagementObject activityObj)
        {
            try
            {
                if (activityObj[ActivityClass, "JobId"].Value != null)
                {
                    var jobId = (Guid)activityObj[ActivityClass, "JobId"].Value;

                    var jt = _aaClient.GetJobAsync(jobId);
                    var ot = _aaClient.GetJobOutput(jobId);

                    var j = await jt;
                    activityObj[ActivityClass, "JobStatus"].Value = j.Properties.Status;
                    activityObj[ActivityClass, "JobException"].Value = j.Properties.Exception;

                    var s = j.Properties.Status.ToLower();
                    if (s == "completed")
                        activityObj[ActivityClass, "Status"].Value = ActivityCompletedEnum;
                    else if (s == "stopped" || s == "failed")
                        activityObj[ActivityClass, "Status"].Value = ActivityFailedEnum;

                    activityObj[ActivityClass, "JobOutput"].Value = await ot;
                    activityObj.Overwrite();
                }
            }
            catch (Exception error)
            {
                activityObj[ActivityClass, "JobException"].Value = error.Message;
                activityObj.Overwrite();
            }
        }
        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();
        }