private void Update_GridView(int selectedId)
 {
     using (EnterpriseTestContext context = new EnterpriseTestContext())
     {
         children_GridView.DataSource = ResourceWindowsCategory.SelectByParent(context, selectedId);
     }
 }
        private void removeAssociated_Button_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Deletion is final, are you sure you want to remove?", "Removal confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                children_GridView.EndEdit();
                List <string> services = getSelectedServices();
                foreach (string service in services)
                {
                    using (EnterpriseTestContext context = new EnterpriseTestContext())
                    {
                        // Get service to remove from parent
                        ResourceWindowsCategory serviceToDelete = ResourceWindowsCategory.SelectByName(context, service, tabControl_Types.SelectedTab.Text);

                        //Get Parent
                        ResourceWindowsCategory parent = ResourceWindowsCategory.SelectByName(context, listBox_Resource.Text, tabControl_Types.SelectedTab.Text);

                        //Remove Parent Child relationship
                        ResourceWindowsCategory.RemoveChild(context, parent.CategoryId, serviceToDelete.CategoryId);

                        context.SaveChanges();

                        // Update Grid
                        children_GridView.DataSource = null;
                        children_GridView.DataSource = ResourceWindowsCategory.SelectByParent(context, (int)listBox_Resource.SelectedValue);
                    }
                }
            }
        }
Пример #3
0
        public override void Initialize(object entity)
        {
            _metadata = entity as VirtualResourceMetadata;
            if (_metadata == null)
            {
                throw new EditorTypeMismatchException(entity, typeof(VirtualResourceMetadata));
            }

            string server = (_metadata.VirtualResource as PerfMonCollector).HostName;
            List <ResourceWindowsCategory> categories = null;

            using (EnterpriseTestContext context = new EnterpriseTestContext())
            {
                //Load categories from the database.
                categories = ResourceWindowsCategory.Select(context, "PerfMon").ToList();
            }

            // Get the top node. It will have a blank name.
            ResourceWindowsCategory top = categories.FirstOrDefault(c => string.IsNullOrEmpty(c.Name));

            foreach (ResourceWindowsCategory category in top.Children)
            {
                if (category.Name == PrintQueueCategory)
                {
                    LoadPrintQueueCounterNames(category.Children);
                }
                else
                {
                    BuildTree(category);
                }
            }
            LoadPrintQueues(server);

            SelectedCounter = _metadata.Metadata;

            // Data Bindings
            hostNameDisplay_Label.Text = server;
            category_TextBox.DataBindings.Add("Text", _selected, "Category");
            instance_TextBox.DataBindings.Add("Text", _selected, "Instance");
            counter_TextBox.DataBindings.Add("Text", _selected, "Counter");
            collect_CheckBox.DataBindings.Add("Checked", _selected, "CollectAtStart");
            //Interval Binding requires special formatting.
            Binding intervalBinding = new Binding("Text", _selected, "CollectionInterval");

            intervalBinding.Format += new ConvertEventHandler(IntervalBinding_Format);
            intervalBinding.Parse  += new ConvertEventHandler(IntervalBinding_Parse);
            interval_TextBox.DataBindings.Add(intervalBinding);

            SyncTreeChecked(_selected.Key);

            available_TreeView.BeforeCheck += new TreeViewCancelEventHandler(Available_TreeView_BeforeCheck);
            available_TreeView.AfterCheck  += new TreeViewEventHandler(Available_TreeView_AfterCheck);

            // Validate the data coming in
            ValidateInterval(_selected.CollectionInterval);
            ValidateSelection();
        }
Пример #4
0
        /// <summary>
        /// Initial Form Setup
        /// </summary>
        /// <param name="resource"></param>
        private void SetupForm(ResourceWindowsCategory resource)
        {
            resourceType_TextBox.Text             = resource.CategoryType;
            serverName_TextBox.Text               = resource.Name;
            services_GridView.AutoGenerateColumns = false;
            resource_GroupBox.Enabled             = false;

            updateServerGrid(ValidateServerName(resource.Name));
        }
Пример #5
0
 /// <summary>
 /// Constructor to add services to existing resource
 /// </summary>
 /// <param name="resource"></param>
 /// <param name="associatedServices"></param>
 public ResourceWindowsConfigurationForm(ResourceWindowsCategory resource, List <string> associatedServices)
 {
     InitializeComponent();
     try
     {
         _associatedServices = associatedServices;
         SetupForm(resource);
     }
     catch
     {
         this.Close();
     }
 }
 private void insert_Button_Click(object sender, EventArgs e)
 {
     using (EnterpriseTestContext context = new EnterpriseTestContext())
     {
         foreach (PerfMonCounterData counter in _selectedCounters)
         {
             ResourceWindowsCategory.AddPerfMon(context, counter.Category, counter.InstanceName, counter.Counter, ResourceWindowsCategoryType.PerfMon);
         }
         context.SaveChanges();
     }
     MessageBox.Show(this, "Selected counters have been added to the database.", "Insert Counters", MessageBoxButtons.OK, MessageBoxIcon.Information);
     ClearSelectedItems();
 }
Пример #7
0
        private void LoadComboBoxes(EnterpriseTestContext context)
        {
            sessionName_ComboBox.DataSource    = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionName.ToString());
            sessionName_ComboBox.SelectedIndex = -1;

            sessionType_ComboBox.DataSource    = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionType.ToString());
            sessionType_ComboBox.SelectedIndex = -1;

            sessionCycle_ComboBox.DataSource    = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionCycle.ToString());
            sessionCycle_ComboBox.SelectedIndex = sessionCycle_ComboBox.FindString(Ticket.SessionCycle);

            retention_ComboBox.DataSource    = SessionLogRetentionHelper.ExpirationList;
            retention_ComboBox.SelectedIndex = retention_ComboBox.FindString(EnumUtil.GetDescription(WizardPageManager.GetDefaultLogRetention()));
        }
 private void addResource_Button_Click(object sender, EventArgs e)
 {
     using (ResourceWindowsConfigurationForm addForm = new ResourceWindowsConfigurationForm(tabControl_Types.SelectedTab.Text))
     {
         addForm.ShowDialog();
         if (addForm.DialogResult == DialogResult.OK)
         {
             ResourceWindowsCategory newServer = addForm.Resource;
             string newCategoryType            = addForm.CategoryType;
             LoadResourceTypeTabs();
             tabControl_Types.SelectedTab  = tabControl_Types.TabPages[newServer.CategoryType];
             listBox_Resource.SelectedItem = newServer.Name;
             Update_GridView((int)listBox_Resource.SelectedValue);
         }
     }
 }
        private void LoadResourceTypeTabs()
        {
            // Move all controls out of the first tab before clearing the tabs collection
            listBox_Resource.Parent   = this;
            resource_ToolStrip.Parent = this;
            groupBox_Assoc.Parent     = this;
            tabControl_Types.TabPages.Clear();

            using (EnterpriseTestContext context = new EnterpriseTestContext())
            {
                foreach (string resourceType in ResourceWindowsCategory.SelectDistinctCategoryTypes(context))
                {
                    tabControl_Types.TabPages.Add(resourceType, resourceType);
                }
            }
        }
        /// <summary>
        /// When a resource type is selected the resource list box is populated based on its value.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl_Types_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabPage selectedTab = SelectedTab;

            if (selectedTab != null)
            {
                // Add all controls into the selected tab
                listBox_Resource.Parent   = selectedTab;
                resource_ToolStrip.Parent = selectedTab;
                groupBox_Assoc.Parent     = selectedTab;

                using (EnterpriseTestContext context = new EnterpriseTestContext())
                {
                    listBox_Resource.DataSource = ResourceWindowsCategory.SelectParent(context, selectedTab.Text).ToList();
                }
            }
        }
Пример #11
0
        private void LoadComponentsListBox(string selectedHost)
        {
            ResourceWindowsCategory component = null;

            components_ListBox.Items.Add(Any);
            using (EnterpriseTestContext context = new EnterpriseTestContext())
            {
                component = ResourceWindowsCategory.Select(context, "EventLog", selectedHost).FirstOrDefault();
            }

            if (component != null)
            {
                foreach (ResourceWindowsCategory child in component.Children)
                {
                    components_ListBox.Items.Add(child.Name);
                }
            }
        }
Пример #12
0
        private void add_Button_Click(object sender, EventArgs e)
        {
            // End grid edit mode
            services_GridView.EndEdit();

            // Validate resource name is not blank
            if (!ValidateResourceTypeName())
            {
                MessageBox.Show("Pleae enter valid resource name", "Invalid resource name", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            // Get checkbox services and custom service
            List <string> servicesToAdd = getSelectedServices();

            if (getCustomService() != null)
            {
                servicesToAdd.Add(getCustomService());
            }

            // Add and link services to server and resource type
            using (EnterpriseTestContext context = new EnterpriseTestContext())
            {
                // Get resource type and server name
                string categoryType        = resourceType_TextBox.Text;
                string validatedServerName = serverName_TextBox.Text;

                int serverId = ResourceWindowsCategory.AddResource(context, validatedServerName, categoryType);
                ResourceWindowsCategory serverResource = ResourceWindowsCategory.SelectById(context, serverId);

                foreach (string service in servicesToAdd)
                {
                    int tempId = ResourceWindowsCategory.AddResource(context, service, categoryType);
                    ResourceWindowsCategory tempService = ResourceWindowsCategory.SelectById(context, tempId);
                    tempService.Parents.Add(serverResource);
                }

                context.SaveChanges();
                Resource = serverResource;
                resourceType_TextBox.Text = categoryType;
                this.DialogResult         = DialogResult.OK;
                this.Close();
            }
        }
        private void LoadInstances(string categoryName, string machineName)
        {
            instance_ListBox.Items.Clear();

            if (categoryName == PrintQueueCategory)
            {
                using (AssetInventoryContext context = DbConnect.AssetInventoryContext())
                {
                    var queues = context.RemotePrintQueues.Where(n => n.PrintServer.HostName.Equals(machineName, StringComparison.OrdinalIgnoreCase)).OrderBy(n => n.Name);
                    foreach (RemotePrintQueue queue in queues)
                    {
                        instance_ListBox.Items.Add(queue.Name);
                    }
                }
            }
            else
            {
                using (EnterpriseTestContext context = new EnterpriseTestContext())
                {
                    var category = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.PerfMon.ToString()).Where(c => c.Name == categoryName).First();

                    foreach (ResourceWindowsCategory instance in category.Children)
                    {
                        instance_ListBox.Items.Add(instance.Name);
                    }
                }
            }


            //If there's only one instance, automatically select it and load the counters
            if (instance_ListBox.Items.Count == 1)
            {
                instance_ListBox.SelectedIndex = 0;
                instance_ListBox_SelectedIndexChanged(null, EventArgs.Empty);
            }
            else
            {
                instance_ListBox.SelectedIndex = -1;
                counter_ListBox.DataSource     = null;
            }

            addCounter_ToolStripButton.Enabled = false;
        }
        private void addAssociated_Button_Click(object sender, EventArgs e)
        {
            List <string> associatedServices         = new List <string>();
            List <ResourceWindowsCategory> services  = new List <ResourceWindowsCategory>();
            ResourceWindowsCategory        component = new ResourceWindowsCategory();

            using (EnterpriseTestContext context = new EnterpriseTestContext())
            {
                component = ResourceWindowsCategory.SelectById(context, (int)listBox_Resource.SelectedValue);
                services  = ResourceWindowsCategory.SelectByParent(context, (int)listBox_Resource.SelectedValue);
            }

            foreach (ResourceWindowsCategory service in services)
            {
                associatedServices.Add(service.Name);
            }

            try
            {
                if (pingServer(component.Name))
                {
                    ResourceWindowsConfigurationForm addForm = new ResourceWindowsConfigurationForm(component, associatedServices);
                    addForm.ShowDialog();
                    if (addForm.DialogResult == DialogResult.OK)
                    {
                        ResourceWindowsCategory newServer = addForm.Resource;
                        string newCategoryType            = addForm.CategoryType;
                        LoadResourceTypeTabs();
                        tabControl_Types.SelectedTab  = tabControl_Types.TabPages[newServer.CategoryType];
                        listBox_Resource.SelectedItem = newServer.Name;
                        Update_GridView((int)listBox_Resource.SelectedValue);
                    }
                }
            }
            catch
            {
                string errorMessage = "Error: No access to " + component.Name;
                MessageBox.Show(errorMessage, "Server Access Failure", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        private void LoadCounters(string machineName)
        {
            if (_loadFromMachine)
            {
                string instanceName = SelectedInstance;
                PerformanceCounterCategory      category = SelectedCategory as PerformanceCounterCategory;
                Collection <PerformanceCounter> counters = PerfMonController.GetCounters(category, instanceName);
                counter_ListBox.DataSource = counters;
            }
            else
            {
                ResourceWindowsCategory instance = null;
                using (EnterpriseTestContext context = new EnterpriseTestContext())
                {
                    instance = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.PerfMon.ToString()).Where(c => c.Name == machineName).FirstOrDefault();
                }
                counter_ListBox.DataSource = instance.Children;
            }

            counter_ListBox.DisplayMember = "Name";
            counter_ListBox.SelectedIndex = -1;
        }
        private void removeResource_Button_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Deletion is final, are you sure you want to remove?", "Removal confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                using (EnterpriseTestContext context = new EnterpriseTestContext())
                {
                    ResourceWindowsCategory resource = ResourceWindowsCategory.SelectByName(context, listBox_Resource.Text, tabControl_Types.SelectedTab.Text);
                    if (resource.Children.Count > 0)
                    {
                        MessageBox.Show("Please remove all associations before deleting '{0}'.".FormatWith(resource.Name), "Delete Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    context.ResourceWindowsCategories.DeleteObject(resource);
                    context.SaveChanges();

                    listBox_Resource.DataSource = ResourceWindowsCategory.SelectParent(context, SelectedTab.Text).ToList();
                }
            }
        }
Пример #17
0
        private void BuildTree(ResourceWindowsCategory categoryItem, TreeNode parentNode)
        {
            TreeNode thisNode = null;

            if (parentNode == null)
            {
                thisNode = available_TreeView.Nodes.Add(categoryItem.Name);
            }
            else
            {
                thisNode = parentNode.Nodes.Add(categoryItem.Name);
            }

            thisNode.Name = GenerateNodeKey(thisNode);
            if (categoryItem.Children.Count > 0)
            {
                HideCheckBox(thisNode);
            }
            foreach (ResourceWindowsCategory child in categoryItem.Children)
            {
                BuildTree(child, thisNode);
            }
        }
Пример #18
0
 private void LoadComboBoxes()
 {
     sessionName_ComboBox.DataSource  = ResourceWindowsCategory.Select(_enterpriseTestContext, ResourceWindowsCategoryType.SessionName.ToString());
     sessionType_ComboBox.DataSource  = ResourceWindowsCategory.Select(_enterpriseTestContext, ResourceWindowsCategoryType.SessionType.ToString());
     sessionCycle_ComboBox.DataSource = ResourceWindowsCategory.Select(_enterpriseTestContext, ResourceWindowsCategoryType.SessionCycle.ToString());
 }
        private void LoadComboBoxes(EnterpriseTestContext context)
        {
            sessionName_ComboBox.DataSource    = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionName.ToString());
            sessionName_ComboBox.SelectedIndex = -1;
            sessionType_ComboBox.DataSource    = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionType.ToString());
            sessionType_ComboBox.SelectedIndex = -1;
            sessionCycle_ComboBox.DataSource   = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionCycle.ToString());


            retention_ComboBox.DataSource    = SessionLogRetentionHelper.ExpirationList;
            retention_ComboBox.SelectedIndex = retention_ComboBox.FindString(EnumUtil.GetDescription(WizardPageManager.GetDefaultLogRetention()));

            Dictionary <string, int> failureItems = new Dictionary <string, int>();
            List <TimeSpan>          failTimes    = new List <TimeSpan>();

            using (AssetInventoryContext assetContext = DbConnect.AssetInventoryContext())
            {
                string powerState   = EnumUtil.GetDescription(VMPowerState.PoweredOff);
                var    availableVMs = assetContext.FrameworkClients.Where(n => n.PowerState == powerState);

                platform_ComboBox.DataSource = null;
                platform_ComboBox.Items.Clear();
                platform_ComboBox.DisplayMember = "Name";
                platform_ComboBox.ValueMember   = "FrameworkClientPlatformId";
                platform_ComboBox.DataSource    = assetContext.FrameworkClientPlatforms.Where(n => n.Active).OrderBy(n => n.FrameworkClientPlatformId).ToList();

                holdId_ComboBox.DataSource = null;
                holdId_ComboBox.Items.Clear();
                holdId_ComboBox.DataSource = availableVMs.Select(n => n.HoldId).Distinct().Where(n => n != null).ToList();
            }
            failureItems.Add("1 Failure", 1);
            failureItems.Add("2 Failures", 2);
            failureItems.Add("5 Failures", 5);
            failureItems.Add("10 Failures", 10);
            failureItems.Add("15 Failures", 15);
            failureItems.Add("20 Failures", 20);

            threshold_comboBox.DataSource    = new BindingSource(failureItems, null);
            threshold_comboBox.DisplayMember = "Key";
            threshold_comboBox.ValueMember   = "Value";

            failTimes.Add(TimeSpan.FromMinutes(15));
            failTimes.Add(TimeSpan.FromMinutes(30));
            failTimes.Add(TimeSpan.FromHours(1));
            failTimes.Add(TimeSpan.FromHours(2));
            failTimes.Add(TimeSpan.FromHours(6));
            failTimes.Add(TimeSpan.FromHours(12));
            failureTime_comboBox.DataSource = new BindingSource(failTimes, null);


            if (Ticket.SessionId != null && _scenario != null)
            {
                if (!string.IsNullOrEmpty(_scenario.ScenarioSettings))
                {
                    var scenarioSettings = LegacySerializer.DeserializeDataContract <ScenarioSettings>(_scenario.ScenarioSettings);
                    //Populate boxes from selected settings
                    dartLog_CheckBox.Checked           = scenarioSettings.NotificationSettings.CollectDartLogs;
                    email_textBox.Text                 = scenarioSettings.NotificationSettings.Emails;
                    failureTime_comboBox.SelectedIndex = failTimes.FindIndex(x => x == scenarioSettings.NotificationSettings.FailureTime);
                    threshold_comboBox.SelectedIndex   = failureItems.ToList().FindIndex(x => x.Value == scenarioSettings.NotificationSettings.FailureCount);
                    triggerList_TextBox.Lines          = scenarioSettings.NotificationSettings.TriggerList;
                    runtime_NumericUpDown.Value        = Math.Min(scenarioSettings.EstimatedRunTime, runtime_NumericUpDown.Maximum); // scenarioSettings.EstimatedRunTime;
                    logLocation_TextBox.Text           = scenarioSettings.LogLocation;
                    eventLog_CheckBox.Checked          = scenarioSettings.CollectEventLogs;
                }

                sessionName_ComboBox.Text = string.IsNullOrEmpty(Ticket.SessionName) ? _scenario.Name : Ticket.SessionName;
            }

            //TraceFactory.Logger.Debug($"initial:{_initial}");
            if (!_initial)
            {
                sessionType_ComboBox.SelectedText   = Ticket.SessionType;
                sessionCycle_ComboBox.SelectedIndex = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionCycle.ToString()).Select(x => x.Name).ToList().IndexOf(Ticket.SessionCycle);


                //TraceFactory.Logger.Debug($"email:{_ticket.EmailAddresses}");
                if (!string.IsNullOrEmpty(Ticket.EmailAddresses))
                {
                    dartLog_CheckBox.Checked           = Ticket.CollectDARTLogs;
                    email_textBox.Text                 = Ticket.EmailAddresses;
                    failureTime_comboBox.SelectedIndex = failTimes.FindIndex(x => x == Ticket.FailureTime);
                    threshold_comboBox.SelectedIndex   = failureItems.ToList().FindIndex(x => x.Value == Ticket.FailureCount);
                    triggerList_TextBox.Lines          = Ticket.TriggerList;
                    runtime_NumericUpDown.Value        = Math.Min(Ticket.DurationHours, runtime_NumericUpDown.Maximum);
                    eventLog_CheckBox.Checked          = Ticket.CollectEventLogs;
                    email_textBox.Text                 = Ticket.EmailAddresses;
                }
                if (Ticket.FailureTime != TimeSpan.MaxValue)
                {
                    failureTime_comboBox.SelectedIndex = failTimes.FindIndex(x => x == Ticket.FailureTime);
                }
                if (Ticket.FailureCount != -1)
                {
                    threshold_comboBox.SelectedIndex = failureItems.ToList().FindIndex(x => x.Value == Ticket.FailureCount);
                }
                if (!string.IsNullOrEmpty(Ticket.LogLocation))
                {
                    logLocation_TextBox.Text = Ticket.LogLocation;
                }
                if (Ticket.TriggerList != null)
                {
                    triggerList_TextBox.Lines = Ticket.TriggerList;
                }
                dartLog_CheckBox.Checked    = Ticket.CollectDARTLogs;
                eventLog_CheckBox.Checked   = Ticket.CollectEventLogs;
                runtime_NumericUpDown.Value = Math.Min(Ticket.DurationHours, runtime_NumericUpDown.Maximum);
            }
        }
Пример #20
0
 private void BuildTree(ResourceWindowsCategory categoryItem)
 {
     BuildTree(categoryItem, null);
 }
        /// <summary>
        /// Initializes this instance with the specified object.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <exception cref="ControlTypeMismatchException">
        /// Thrown when an object of incorrect type is passed to this instance.
        ///   </exception>
        public override void Initialize(object entity)
        {
            _scenario = entity as EnterpriseScenario;

            if (_scenario == null)
            {
                throw new ControlTypeMismatchException(entity, typeof(EnterpriseScenario));
            }

            _owner = _scenario.Owner;

            // Set data source for the grid view and resize the columns
            resource_GridView.DataSource = _scenario.VirtualResources;
            resource_GridView.BestFitColumns();

            // Set data sources for combo boxes
            using (EnterpriseTestContext context = new EnterpriseTestContext())
            {
                string scenarioTags = GlobalSettings.Items[Setting.ScenarioTags];
                vertical_ComboBox.Items.AddRange(scenarioTags.Split(','));
                category_ComboBox.DataSource = EnterpriseScenario.SelectDistinctCompany(context).ToList();

                if (UserManager.CurrentUser.HasPrivilege(UserRole.Manager) || (!string.IsNullOrEmpty(_scenario.Owner) && _scenario.Owner.Equals(UserManager.CurrentUserName)))
                {
                    owner_ComboBox.Items.Add("Unknown");
                    foreach (var name in context.Users.Select(x => x.UserName))
                    {
                        owner_ComboBox.Items.Add(name);
                    }
                    owner_ComboBox.SelectedItem           = _scenario.Owner;
                    editorGroups_CheckedListBox.BackColor = Color.FromKnownColor(KnownColor.Window);
                }
                else
                {
                    owner_ComboBox.Items.Add(_scenario.Owner);
                    editorGroups_CheckedListBox.SelectionMode = SelectionMode.None;
                    editorGroups_CheckedListBox.BackColor     = Color.FromKnownColor(KnownColor.Control);
                }

                LoadGroups(context);

                foreach (var group in context.UserGroups)
                {
                    _availableGroups.Add(group);
                }

                sessionCycle_ComboBox.DataSource    = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionCycle.ToString());
                sessionCycle_ComboBox.SelectedIndex = -1;

                if (!string.IsNullOrEmpty(_scenario.ScenarioSettings))
                {
                    _settings = LegacySerializer.DeserializeDataContract <ScenarioSettings>(_scenario.ScenarioSettings);
                    sessionCycle_ComboBox.SelectedIndex = ResourceWindowsCategory.Select(context, ResourceWindowsCategoryType.SessionCycle.ToString()).Select(x => x.Name).ToList().IndexOf(_settings.TargetCycle);
                }

                List <string> metadatas = new List <string>();
                foreach (VirtualResource vr in _scenario.VirtualResources.Where(n => n.Enabled))
                {
                    foreach (var vrms in vr.VirtualResourceMetadataSet.Where(n => n.Enabled))
                    {
                        metadatas.Add(vrms.MetadataType);
                    }
                }
                _associatedProducts = context.AssociatedProducts.Where(n => n.MetadataTypes.Any(m => metadatas.Contains(m.Name))).ToList();
                var productIds = _associatedProducts.Select(x => x.AssociatedProductId);
                _productVersions = AssociatedProductVersion.SelectVersions(context, productIds, _scenario.EnterpriseScenarioId).ToList();

                _scenarioProducts = from productInfo in _associatedProducts
                                    join versionInfo in _productVersions
                                    on productInfo.AssociatedProductId equals versionInfo.AssociatedProductId
                                    select new ScenarioProduct
                {
                    ProductId  = productInfo.AssociatedProductId,
                    Version    = versionInfo.Version,
                    ScenarioId = _scenario.EnterpriseScenarioId,
                    Name       = productInfo.Name,
                    Vendor     = productInfo.Vendor,
                    Active     = versionInfo.Active
                };

                var scenarioProducts = _scenarioProducts.ToList();
                if (scenarioProducts.Count != 0)
                {
                    scenarioProductBindingSource.Clear();

                    scenarioProductBindingSource.DataSource = scenarioProducts.Distinct(new ScenarioProductEqualityComparer());
                    scenarioProductBindingSource.ResetBindings(true);
                }
            }

            // Set up data bindings
            name_TextBox.DataBindings.Add("Text", _scenario, "Name");
            description_TextBox.DataBindings.Add("Text", _scenario, "Description");
            category_ComboBox.DataBindings.Add("Text", _scenario, "Company");
            vertical_ComboBox.DataBindings.Add("Text", _scenario, "Vertical");
            //owner_ComboBox.DataBindings.Add("Text", _scenario, "Owner");

            CreateResourceDropDownMenu();

            //_associateProductHandler.CopyToUI(_associateProductHandler.CopyFromScenario(_scenario), this.associatedProducts_DataGrid);
            List <TimeSpan>          failTimes    = new List <TimeSpan>();
            Dictionary <string, int> failureItems = new Dictionary <string, int>();

            failureItems.Add("1 Failure", 1);
            failureItems.Add("2 Failures", 2);
            failureItems.Add("5 Failures", 5);
            failureItems.Add("10 Failures", 10);
            failureItems.Add("15 Failures", 15);
            failureItems.Add("20 Failures", 20);

            failTimes.Add(TimeSpan.FromMinutes(15));
            failTimes.Add(TimeSpan.FromMinutes(30));
            failTimes.Add(TimeSpan.FromHours(1));
            failTimes.Add(TimeSpan.FromHours(2));
            failTimes.Add(TimeSpan.FromHours(6));
            failTimes.Add(TimeSpan.FromHours(12));

            failureTime_comboBox.DataSource  = new BindingSource(failTimes, null);
            threshold_comboBox.DataSource    = new BindingSource(failureItems, null);
            threshold_comboBox.DisplayMember = "Key";
            threshold_comboBox.ValueMember   = "Value";

            //if a new scenario, get empty, otherwise gather saved info from enterprise test.
            if (!string.IsNullOrEmpty(_scenario.ScenarioSettings))
            {
                _settings = LegacySerializer.DeserializeDataContract <ScenarioSettings>(_scenario.ScenarioSettings);
                //Populate boxes from selected settings
                dartLog_CheckBox.Checked = _settings.NotificationSettings.CollectDartLogs;
                email_textBox.Text       = _settings.NotificationSettings.Emails;

                failureTime_comboBox.SelectedIndex = failTimes.FindIndex(x => x == _settings.NotificationSettings.FailureTime);
                threshold_comboBox.SelectedIndex   = failureItems.ToList().FindIndex(x => x.Value == _settings.NotificationSettings.FailureCount);

                triggerList_TextBox.Lines = _settings.NotificationSettings.TriggerList;
                //runtime_NumericUpDown.Value =  _settings.EstimatedRunTime;

                runtime_NumericUpDown.Value = Math.Min(_settings.EstimatedRunTime, runtime_NumericUpDown.Maximum);
                logLocation_TextBox.Text    = _settings.LogLocation;
                eventLog_CheckBox.Checked   = _settings.CollectEventLogs;
                _scenarioCustomDictionary   = _settings.ScenarioCustomDictionary;

                if (_scenarioCustomDictionary != null && _scenarioCustomDictionary.Count != 0)
                {
                    customDictionary_listBox.DataSource    = new BindingSource(_scenarioCustomDictionary, null);
                    customDictionary_listBox.DisplayMember = "Key";
                    customDictionary_listBox.ValueMember   = "Value";
                }
            }
            else
            {
                //Populate combo boxes
                try
                {
                    dartLog_CheckBox.Checked = _settings.NotificationSettings.CollectDartLogs;
                }
                catch
                {
                    dartLog_CheckBox.Checked = false;
                }

                email_textBox.Text = "";

                //Log settings
                logLocation_TextBox.Text  = "";
                eventLog_CheckBox.Checked = false;

                runtime_NumericUpDown.Value = Math.Min(_scenario.EstimatedRuntime, runtime_NumericUpDown.Maximum);
            }
            if (string.IsNullOrEmpty(logLocation_TextBox.Text))
            {
                logLocation_TextBox.Text = GlobalSettings.WcfHosts[WcfService.DataLog];
            }
            AddEventHandlers();
        }
        private void LoadCategories(string machineName)
        {
            if (_loadFromMachine)
            {
                try
                {
                    if (!string.IsNullOrEmpty(userName_textBox.Text))
                    {
                        NetworkCredential networkCredential = new NetworkCredential(userName_textBox.Text, password_textBox.Text, string.IsNullOrEmpty(domain_textBox.Text) ? "." : domain_textBox.Text);
                        UserImpersonator.Execute(() => LoadCategoriesImpl(machineName), networkCredential);
                    }
                    else
                    {
                        LoadCategoriesImpl(machineName);
                    }
                }
                catch (Win32Exception w32Exception)
                {
                    TraceFactory.Logger.Error(w32Exception);
                    MessageBox.Show("Could not access counters.  Please ensure the following services are running on remote machine: " + Environment.NewLine +
                                    "1. Performance Logs & Alerts" + Environment.NewLine +
                                    "2. Remote Registry. " + w32Exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);

                    server_ListBox.SelectedIndex = -1;
                    return;
                }
                catch (UnauthorizedAccessException unauthException)
                {
                    TraceFactory.Logger.Error(unauthException);
                    MessageBox.Show("Unable to access host, please check the user credentials provided.");
                    server_ListBox.SelectedIndex = -1;
                    return;
                }
                catch (ArgumentException argException)
                {
                    TraceFactory.Logger.Error(argException);
                    MessageBox.Show("Could not access counters.  Please ensure the following services are running on remote machine: " + Environment.NewLine +
                                    "1. Performance Logs & Alerts" + Environment.NewLine +
                                    "2. Remote Registry. ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    server_ListBox.SelectedIndex = -1;
                    return;
                }
            }
            else
            {
                //Load categories from the database.
                using (EnterpriseTestContext context = new EnterpriseTestContext())
                {
                    category_ListBox.Items.Clear();
                    var categoryTop = ResourceWindowsCategory.Select(context, "PerfMon").FirstOrDefault(c => string.IsNullOrEmpty(c.Name));

                    foreach (var counter in categoryTop.Children)
                    {
                        category_ListBox.Items.Add(counter.Name);
                    }

                    category_ListBox.SelectedIndex         = -1;
                    category_ListBox.SelectedIndexChanged += category_ListBox_SelectedIndexChanged;
                }
            }
        }