Example #1
0
        private VirtualResource CreateExpandedResource(Collection <ExpandedResourceMetadata> expandedData, int index)
        {
            // First clone this Load Tester resource, then clear it's metadata set.
            VirtualResource resource = this.Clone <LoadTester>();

            resource.VirtualResourceMetadataSet.Clear();

            resource.Name = "{0} [{1}]".FormatWith(resource.Name, index);

            // For each entry in the expanded set, get the metadata item from "this" by the id
            // in the expanded set item, clone it, then update the thread count to the value
            // in the expanded set item, then add the new metadata item to the resource.  Do
            // this for all items in the expanded data.  Then return the resource.
            foreach (var item in expandedData)
            {
                var metadata = VirtualResourceMetadataSet.First(x => x.VirtualResourceMetadataId == item.Id).Clone();

                // Update the execution plan with the correct number of threads and update it with
                // the property thread ramp up information.
                var plan = LegacySerializer.DeserializeDataContract <LoadTesterExecutionPlan>(metadata.ExecutionPlan);
                plan.ThreadCount = item.ThreadCount;

                plan.RampUpSettings = new Collection <RampUpSetting>();
                foreach (var setting in item.RampUpSettings)
                {
                    plan.RampUpSettings.Add(setting);
                }
                metadata.ExecutionPlan = LegacySerializer.SerializeDataContract(plan).ToString();
                resource.VirtualResourceMetadataSet.Add(metadata);
            }

            return(resource);
        }
Example #2
0
 public ScenarioSelectionItem(EnterpriseScenario scenario)
 {
     ScenarioId       = scenario.EnterpriseScenarioId;
     Name             = scenario.Name;
     EstimatedRunTime = scenario.EstimatedRuntime;
     // ScenarioSettings override the default
     if (!string.IsNullOrEmpty(scenario.ScenarioSettings))
     {
         ScenarioSettings settings = LegacySerializer.DeserializeDataContract <ScenarioSettings>(scenario.ScenarioSettings);
         EstimatedRunTime = settings.EstimatedRunTime;
     }
 }
        /// <summary>
        /// Loads the session data from a local cache
        /// </summary>
        public void SessionDataLoad()
        {
            TraceFactory.Logger.Debug("Loading proxy references and subscribers");
            EventPublisher.LoadSubscriberData();

            // If there is a proxy entries cache file, load it and process it.
            if (File.Exists(_backupFile))
            {
                TraceFactory.Logger.Debug("Cache file exists, loading");
                var proxies = LegacySerializer.DeserializeDataContract <SessionProxyControllerSet>(File.ReadAllText(_backupFile));

                // If the number of entries is greater than the max, then we need to adjust
                // the max to account for all entries.
                if (proxies.Count > _proxyControllers.Maximum)
                {
                    _proxyControllers = new SessionProxyControllerSet(proxies.Count);
                }

                // Create a new entry in the proxie entries and then tell the proxy
                // entry to refresh all subscribers.
                foreach (var proxy in proxies.Values)
                {
                    try
                    {
                        proxy.Channel.Ping();
                        _proxyControllers.Add(proxy);
                        TraceFactory.Logger.Debug("Endpoint reloaded for {0}".FormatWith(proxy.SessionId));
                    }
                    catch (EndpointNotFoundException ex)
                    {
                        TraceFactory.Logger.Debug("Endpoint skipped for {0}:{1}".FormatWith(proxy.SessionId, ex.Message));
                    }
                }

                try
                {
                    File.Delete(_backupFile);
                    TraceFactory.Logger.Debug("deleted {0}".FormatWith(_backupFile));
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Error("Error deleting saved proxies file", ex);
                }
            }
            else
            {
                TraceFactory.Logger.Debug("Nothing to load...");
            }
        }
Example #4
0
        protected void CreateMetadataDetail(VirtualResource resource, ResourceDetailBase detail)
        {
            Dictionary <int, OfficeWorkerMetadataDetail> orderedDetails = new Dictionary <int, OfficeWorkerMetadataDetail>();

            foreach (var data in resource.VirtualResourceMetadataSet)
            {
                OfficeWorkerMetadataDetail metadata = new OfficeWorkerMetadataDetail()
                {
                    MetadataType = data.MetadataType,
                    Data         = data.Metadata,

                    Plan = data.ExecutionPlan != null
                        ? LegacySerializer.DeserializeDataContract <WorkerExecutionPlan>(data.ExecutionPlan)
                        : new WorkerExecutionPlan(),

                    Id              = data.VirtualResourceMetadataId,
                    Name            = data.Name,
                    MetadataVersion = data.MetadataVersion,
                    Enabled         = data.Enabled,
                };

                // Offset the key by 100, this is a bunch but it will guarantee (or should) that
                // if for some reason the same order number exists in two plans that they
                // won't conflict.  While the ordered list contains the key, it will keep
                // adding one until it's found an open spot.  Using 100 means we could have up
                // to 100 entries with the same order number and still resolve them.  Of course this
                // doesn't guarantee any ultimate order to the metadata, but in most cases when
                // the order value is unique, this will just ensure the items are added in numerical
                // order so that the serialized XML shows them in order as well.
                int key = metadata.Plan.Order * 100;

                while (orderedDetails.ContainsKey(key))
                {
                    key++;
                }
                orderedDetails.Add(key, metadata);
            }

            // Add the metadata to the manifest in order so that the XML shows them in order.
            foreach (int key in orderedDetails.Keys.OrderBy(x => x))
            {
                detail.MetadataDetails.Add(orderedDetails[key]);
            }
        }
Example #5
0
        private void CreateMetadataDetail(VirtualResource resource, ResourceDetailBase detail)
        {
            foreach (var data in resource.VirtualResourceMetadataSet.Where(m => m.Enabled))
            {
                LoadTesterMetadataDetail metadata = new LoadTesterMetadataDetail()
                {
                    MetadataType = data.MetadataType,
                    Data         = data.Metadata,

                    Plan = data.ExecutionPlan != null
                        ? LegacySerializer.DeserializeDataContract <LoadTesterExecutionPlan>(data.ExecutionPlan)
                        : new LoadTesterExecutionPlan(),

                    Id              = data.VirtualResourceMetadataId,
                    Name            = data.Name,
                    MetadataVersion = data.MetadataVersion,
                    Enabled         = data.Enabled,
                };
                detail.MetadataDetails.Add(metadata);
            }
        }
Example #6
0
        private void importToolStripButton_Click(object sender, EventArgs e)
        {
            using (var dialog = new ExportOpenFileDialog(_directory, "Open STB Device Export File", ImportExportType.Printer))
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    var file = dialog.Base.FileName;
                    _directory = Path.GetDirectoryName(file);

                    using (AssetInventoryContext context = DbConnect.AssetInventoryContext())
                    {
                        var contracts = LegacySerializer.DeserializeDataContract <AssetContractCollection <PrinterContract> >(File.ReadAllText(file));
                        foreach (var contract in contracts)
                        {
                            var printer = ContractFactory.Create(contract, context);
                            AddPrinter(printer);
                        }
                    }
                }
            }
        }
        /// <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)
        {
            _adminWorker = entity as AdminWorker;
            if (_adminWorker == null)
            {
                throw new ControlTypeMismatchException(entity, typeof(AdminWorker));
            }

            // Load the configurations into the helper class
            foreach (var item in _adminWorker.VirtualResourceMetadataSet)
            {
                WorkerExecutionPlan plan = null;
                if (item.ExecutionPlan == null)
                {
                    plan = new WorkerExecutionPlan();
                }
                else
                {
                    plan = LegacySerializer.DeserializeDataContract <WorkerExecutionPlan>(item.ExecutionPlan);
                }

                _mainConfigurations.Add(new WorkerActivityConfiguration(item, plan));
            }

            // Load the activities into the binding list
            activity_TabControl.SelectTab(main_TabPage);
            _selectedPhase = ResourceExecutionPhase.Main;
            activity_GridView.BestFitColumns();

            // Set up data bindings
            name_TextBox.DataBindings.Add("Text", _adminWorker, "Name");
            description_TextBox.DataBindings.Add("Text", _adminWorker, "Description");

            platform_ComboBox.SetPlatform(_adminWorker.Platform, VirtualResourceType.AdminWorker);
            testcaseid_numericUpDown.Value = _adminWorker.TestCaseId;
            ConfigureEnableAllButton();
            CreateActivityDropDownMenu();

            RefreshGrid();
        }
        private void importToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                using (var dialog = new ExportOpenFileDialog(_directory, "Open Test Document Export File", ImportExportType.Document))
                {
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        var file = dialog.Base.FileName;
                        _directory = Path.GetDirectoryName(file);

                        var contracts = LegacySerializer.DeserializeDataContract <DocumentContractCollection>(File.ReadAllText(file));

                        foreach (var contract in contracts)
                        {
                            if (!_context.TestDocuments.Any(x => x.FileName.Equals(contract.FileName, StringComparison.OrdinalIgnoreCase)))
                            {
                                var document = ContractFactory.Create(_context, contract);
                                _importedDocumentData.Add(document.TestDocumentId, contract.Data);
                                AddDocument(document);
                            }
                            else
                            {
                                // Log an error for the current file, but keep going
                                TraceFactory.Logger.Debug("Document already exists: {0}".FormatWith(contract.FileName));
                            }
                        }

                        MessageBox.Show("Documents have been imported", "Import Documents", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                TraceFactory.Logger.Error(ex);
                MessageBox.Show("Error importing document: {0}. Check log file for more details.".FormatWith(ex.Message));
            }
        }
        /// <summary>
        /// Loads the subscribers list from a data file.
        /// </summary>
        public void LoadSubscriberData()
        {
            if (!File.Exists(_dumpFile))
            {
                TraceFactory.Logger.Debug("Nothing to load...");
                return;
            }

            lock (_lock)
            {
                _subscribers = LegacySerializer.DeserializeDataContract <Collection <Uri> >(File.ReadAllText(_dumpFile));
            }

            TraceFactory.Logger.Debug("Loaded {0} subscribers".FormatWith(_subscribers.Count));
            try
            {
                File.Delete(_dumpFile);
                TraceFactory.Logger.Debug("Deleted {0}".FormatWith(_dumpFile));
            }
            catch (Exception ex)
            {
                TraceFactory.Logger.Error("Error deleting saved subscriber file", ex);
            }
        }
        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);
            }
        }
Example #11
0
        private void LoadSystemSettings(string manifestFilePath)
        {
            SystemManifest systemManifest = LegacySerializer.DeserializeDataContract <SystemManifest>(GetFileContents(manifestFilePath));

            GlobalDataStore.Load(systemManifest);
        }
        /// <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();
        }
Example #13
0
        /// <summary>
        /// Configures User Groups in Activity Directory for each user count..
        /// </summary>
        /// <param name="credential">The credential.</param>
        /// <param name="addToGroups">Whether to add the user to the AD groups specified in the manifest.</param>
        protected void ConfigureUserGroups(OfficeWorkerCredential credential, bool addToGroups = true)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            string userName = credential.UserName;

            // Check to be sure there are user groups to configure
            string securityGroupXml = SystemManifest.Resources.GetByUsername(userName).SecurityGroups;

            if (string.IsNullOrEmpty(securityGroupXml))
            {
                // There are no active directory groups to process, so return
                return;
            }

            // Get the groups to be processed and the appropriate logging label
            Collection <ActiveDirectoryGroup> groups = null;
            string label = string.Empty;

            if (addToGroups)
            {
                groups = LegacySerializer.DeserializeDataContract <Collection <ActiveDirectoryGroup> >(securityGroupXml);
                label  = "Adding";
            }
            else
            {
                groups = new Collection <ActiveDirectoryGroup>();
                label  = "Removing";
            }

            PrincipalContext context = new PrincipalContext(ContextType.Domain);

            // Compare what the list of groups are to the master list from Active Directory
            // for every entry found in active directory add it to the list to be processed.
            // If there is a group listed to be assigned but it doesn't exist anymore in active
            // directory, log that error.
            var groupsToAssign = new List <GroupPrincipal>();

            if (addToGroups)
            {
                foreach (var group in groups)
                {
                    GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, group.Name);
                    if (groupPrincipal != null)
                    {
                        TraceFactory.Logger.Debug("Group {0} will be assigned to {1}".FormatWith(groupPrincipal.Name, credential.UserName));
                        groupsToAssign.Add(groupPrincipal);
                    }
                    else
                    {
                        TraceFactory.Logger.Error("The group {0} does not exist in the Active Directory server".FormatWith(group.Name));
                    }
                }
            }

            // Find any groups the user is a member of that must be removed.  Ignore Domain Users, since that group cannot be unjoined.
            UserPrincipal userPrincipal      = UserPrincipal.FindByIdentity(context, userName);
            var           existingUserGroups = userPrincipal.GetAuthorizationGroups().OfType <GroupPrincipal>();
            var           groupsToRemove     = existingUserGroups.Except(groupsToAssign).Where(n => n.Name != "Domain Users");

            Action action = () =>
            {
                ActiveDirectoryController.RemoveUserFromGroups(userPrincipal, groupsToRemove);
                ActiveDirectoryController.AddUserToGroups(userPrincipal, groupsToAssign);
            };

            try
            {
                Retry.WhileThrowing(action, 10, TimeSpan.FromSeconds(5), new List <Type> {
                    typeof(DirectoryServicesCOMException)
                });
            }
            catch (UnauthorizedAccessException)
            {
                TraceFactory.Logger.Debug("User {0} is not authorized to assign group membership. {1} will not be assigned."
                                          .FormatWith(Environment.UserName, credential.UserName));
            }
        }
        /// <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)
        {
            _loadTester = entity as LoadTester;
            if (_loadTester == null)
            {
                throw new ControlTypeMismatchException(entity, typeof(LoadTester));
            }

            // Load the configurations into the helper class
            LoadTesterConfiguration config = null;

            foreach (var item in _loadTester.VirtualResourceMetadataSet)
            {
                config          = new LoadTesterConfiguration();
                config.Metadata = item;

                if (item.ExecutionPlan == null)
                {
                    config.ExecutionPlan = new LoadTesterExecutionPlan();
                }
                else
                {
                    config.ExecutionPlan = LegacySerializer.DeserializeDataContract <LoadTesterExecutionPlan>(item.ExecutionPlan);
                }

                _configurations.Add(config);
            }

            // Load the activities into the binding list
            activity_GridView.DataSource = _configurations;
            activity_GridView.BestFitColumns();

            if (!GlobalSettings.IsDistributedSystem)
            {
                virtualMachinePlatform_ComboBox.Visible = false;
                platform_Label.Visible = false;
                _loadTester.Platform   = "LOCAL";
            }
            else
            {
                virtualMachinePlatform_ComboBox.SetPlatform(_loadTester.Platform, WorkerType);
            }

            name_TextBox.DataBindings.Add("Text", _loadTester, "Name");
            description_TextBox.DataBindings.Add("Text", _loadTester, "Description");

            // Set up execution thread count for the current plan
            maxThreadsPerVM_NumericUpDown.ValueChanged -= maxThreadsPerVM_NumericUpDown_ValueChanged;
            maxThreadsPerVM_NumericUpDown.Maximum       = 500;
            maxThreadsPerVM_NumericUpDown.Minimum       = 1;
            maxThreadsPerVM_NumericUpDown.Value         = _loadTester.ThreadsPerVM;
            maxThreadsPerVM_NumericUpDown.ValueChanged += maxThreadsPerVM_NumericUpDown_ValueChanged;

            CreateActivityDropDownMenu();

            if (_configurations.Count > 0)
            {
                // Select the first item in the list and then setup the databindings for that list.
                activity_GridView.Rows[0].IsSelected = true;
                var configuration = activity_GridView.Rows[0].DataBoundItem as LoadTesterConfiguration;
                SetupExecutionPlanBindings(configuration);
            }
        }
        private void importButton_Click(object sender, EventArgs e)
        {
            var file = string.Empty;

            using (var dialog = new ExportOpenFileDialog(_directory, "Open Software Installer Export File", ImportExportType.Installer))
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    file       = dialog.Base.FileName;
                    _directory = Path.GetDirectoryName(file);
                }
            }

            if (string.IsNullOrEmpty(file))
            {
                return;
            }

            var contract = LegacySerializer.DeserializeDataContract <MetadataTypeInstallerContract>(File.ReadAllText(file));

            using (var context = new EnterpriseTestContext())
            {
                var metadataType = context.MetadataTypes.FirstOrDefault(x => x.Name.Equals(contract.Name));

                if (metadataType == null)
                {
                    MessageBox.Show("The plugin activity ({0}) dependent on this software installer does not exist in this system.".FormatWith(contract.Name));
                    return;
                }

                try
                {
                    Cursor = Cursors.WaitCursor;

                    var currentPackages = context.SoftwareInstallerPackages
                                          .Where(x => x.MetadataTypes.Any(y => y.Name.Equals(contract.Name)))
                                          .Select(x => x.Description);

                    if (currentPackages != null && currentPackages.Count() > 0)
                    {
                        var           packageNames = string.Join(Environment.NewLine, currentPackages.ToArray());
                        StringBuilder builder      = new StringBuilder();
                        builder.Append("The following packages are already associated with the {0} plugin.".FormatWith(contract.Name));
                        builder.AppendLine(" Do you want to continue with the import?");
                        builder.AppendLine();
                        builder.AppendLine(packageNames);

                        var result = MessageBox.Show(builder.ToString(), "Installers Already Exist for {0}".FormatWith(contract.Name), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result == DialogResult.No)
                        {
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Cursor = Cursors.Default;
                }

                try
                {
                    Cursor = Cursors.WaitCursor;
                    contract.Import(context);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                finally
                {
                    Cursor = Cursors.Default;
                }
            }

            LoadGrids();

            MessageBox.Show("The software installer was successfully imported", "Import Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Example #16
0
        private void LoadScenarios(string testScenario)
        {
            _scenarioList    = new ObservableCollection <ScenarioQueueItem>();
            _groupCollection = new ObservableCollection <string>()
            {
                "None"
            };
            //find out if the scenario has multiple values
            var testScenarios = testScenario.Split(',').Select(x => x.RemoveWhiteSpace());

            using (EnterpriseTestContext context = new EnterpriseTestContext(_currentDatabase))
            {
                var scenarios = context.EnterpriseScenarios.Where(x => testScenarios.Contains(x.Company));

                foreach (var enterpriseScenario in scenarios)
                {
                    string distribution, groupName;
                    if (string.IsNullOrEmpty(enterpriseScenario.ScenarioSettings))
                    {
                        continue;
                    }
                    var settings = LegacySerializer.DeserializeDataContract <ScenarioSettings>(enterpriseScenario.ScenarioSettings);
                    try
                    {
                        if (!settings.ScenarioCustomDictionary.TryGetValue("Distribution", out distribution))
                        {
                            distribution = "1";
                        }
                    }
                    catch
                    {
                        distribution = "1";
                    }

                    try
                    {
                        if (!settings.ScenarioCustomDictionary.TryGetValue("Group", out groupName))
                        {
                            groupName = "None";
                        }
                    }
                    catch
                    {
                        groupName = "None";
                    }

                    if (groupName.Contains(","))
                    {
                        var groups = groupName.Split(',');
                        foreach (var group in groups)
                        {
                            if (!_groupCollection.Contains(group))
                            {
                                _groupCollection.Add(group);
                            }
                        }
                    }
                    else
                    {
                        if (!_groupCollection.Contains(groupName))
                        {
                            _groupCollection.Add(groupName);
                        }
                    }


                    var description = enterpriseScenario.Description;

                    _scenarioList.Add(new ScenarioQueueItem
                    {
                        ScenarioId   = enterpriseScenario.EnterpriseScenarioId,
                        ScenarioName = enterpriseScenario.Name,
                        Description  = description,
                        Distribution = Convert.ToInt32(distribution),
                        GroupName    = groupName
                    });
                }
            }

            ScenarioDataGrid.DataContext = _scenarioList;
            GroupComboBox.DataContext    = _groupCollection;
            ScenarioCountTextBlock.Text  = _scenarioList.Count(x => x.Active).ToString("D2");
            TextBoxTotalScenario.Text    = _scenarioList.Where(x => x.Active).Sum(x => x.Distribution).ToString("D2");
        }