public void Update(EnterpriseTestContext context) { var temp = context.AssociatedProductVersions.Where(x => x.AssociatedProductId == ProductId && x.EnterpriseScenarioId == ScenarioId); if (temp == null || temp.Count() == 0) { AssociatedProductVersion version = new AssociatedProductVersion(); version.AssociatedProductId = ProductId; version.EnterpriseScenarioId = ScenarioId; version.Active = Active; version.Version = Version; context.AssociatedProductVersions.AddObject(version); context.SaveChanges(); } else { AssociatedProductVersion version = context.AssociatedProductVersions.Where(x => x.AssociatedProductId == ProductId && x.EnterpriseScenarioId == ScenarioId).First(); version.AssociatedProductId = ProductId; version.EnterpriseScenarioId = ScenarioId; version.Active = Active; version.Version = Version; context.SaveChanges(); } }
private void ok_Button_Click(object sender, EventArgs e) { if (ValidateEntities()) { _context.SaveChanges(); DialogResult = DialogResult.OK; Close(); } }
/// <summary> /// Handles the Click event of the ok_Button control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void ok_Button_Click(object sender, EventArgs e) { if (_bulkDeviceControl.BulkDeviceListChange) { UpdateVirtualResourceMetadataAssetUsage(); } if (_bulkPrintQueueControl.BulkPrintQueueListChange) { UpdateVirtualResourceMetadataPrintQueueUsage(); } this.DialogResult = DialogResult.OK; _context.SaveChanges(); }
private void deleteProduct_Button_Click(object sender, EventArgs e) { string vendor = vendor_TextBox.Text; string name = name_TextBox.Text; using (EnterpriseTestContext context = new EnterpriseTestContext()) { var temp = context.AssociatedProducts.Where(y => y.AssociatedProductId == _selectedProductId); if (temp.Count() == 0) { MessageBox.Show("Name and Vendor don't exist in the database to delete", "Product Delete Error", MessageBoxButtons.OK); return; } else { AssociatedProduct del = temp.First(); context.DeleteObject(del); context.SaveChanges(); LoadPage(); } if (context.AssociatedProducts.Count() == 0) { editProduct_Button.Enabled = false; } } deleteProduct_Button.Enabled = false; }
private void ok_Button_Click(object sender, EventArgs e) { if (_sessionSummary != null) { // Build string of selected tags. string tagList = BuildTagList(); // Update DataLog.SessionSummary. _sessionSummary.SessionName = sessionName_ComboBox.Text; _sessionSummary.Type = sessionType_ComboBox.Text; _sessionSummary.Cycle = sessionCycle_ComboBox.Text; _sessionSummary.Reference = reference_TextBox.Text; _sessionSummary.Tags = tagList; _sessionSummary.SessionName = sessionName_ComboBox.Text; _sessionSummary.Notes = notes_TextBox.Text; _sessionSummary.Tags = tagList; //Commit changes to the databases _dataLogContext.SaveChanges(); _enterpriseTestContext.SaveChanges(); this.DialogResult = DialogResult.OK; } else { this.DialogResult = DialogResult.Cancel; } }
private void addAssociation_Button_Click(object sender, EventArgs e) { using (EnterpriseTestContext context = new EnterpriseTestContext()) { var meta = metaData_ComboBox.SelectedItem as MetadataType; var temp = context.AssociatedProducts.Where(y => y.AssociatedProductId == _selectedProductId && y.MetadataTypes.Any(x => x.Name == meta.Name)); //var otherTemp = temp.First().Value.Where(x => x.AssociatedProductId == _selectedProductId).First(); if (temp.Count() > 0) { MessageBox.Show("Plugin Association already exists for this metadata", "Product Association Error", MessageBoxButtons.OK); return; } else { var metadata = context.MetadataTypes.Where(y => y.Name == meta.Name).First(); var prod = context.AssociatedProducts.Where(y => y.AssociatedProductId == _selectedProductId).First(); prod.MetadataTypes.Add(metadata); context.SaveChanges(); } } LoadPage(); }
/// <summary> /// Commits this instance. /// </summary> public void Commit() { Cursor = Cursors.WaitCursor; foreach (var entity in _deletedItems) { _context.Users.DeleteObject(entity); } foreach (var item in _users) { switch (item.EntityState) { case EntityState.Added: { _context.Users.AddObject(item); break; } } } _context.SaveChanges(); _deletedItems.Clear(); Cursor = Cursors.Default; }
/// <summary> /// Commits this instance. /// </summary> public void Commit() { Cursor = Cursors.WaitCursor; foreach (var entity in _deletedItems) { _context.MetadataTypes.DeleteObject(entity); } foreach (var item in _pluginTypes) { switch (item.EntityState) { case EntityState.Added: { _context.MetadataTypes.AddObject(item); break; } case EntityState.Modified: { _context.MetadataTypes.ApplyCurrentValues(item); break; } } } _context.SaveChanges(); _deletedItems.Clear(); Cursor = Cursors.Default; }
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); } } } }
private void editProduct_Button_Click(object sender, EventArgs e) { string vendor = vendor_TextBox.Text; string name = name_TextBox.Text; if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(vendor)) { MessageBox.Show("Name and Vendor Fields can not be blank", "Edit Product Error", MessageBoxButtons.OK); return; } using (EnterpriseTestContext context = new EnterpriseTestContext()) { var temp = context.AssociatedProducts.Where(y => y.AssociatedProductId == _selectedProductId); if (temp.Count() == 0) { MessageBox.Show("Name and Vendor don't exist in the database to edit", "Product Add Error", MessageBoxButtons.OK); return; } else { AssociatedProduct edit = temp.First(); edit.Name = name; edit.Vendor = vendor; context.SaveChanges(); LoadPage(); } } }
private void ok_Button_Click(object sender, EventArgs e) { //Only save changes if this form created the data context. if (_localContext) { _dataContext.SaveChanges(); } this.DialogResult = DialogResult.OK; }
/// <summary> /// Performs final validation before allowing the user to navigate away from the page. /// </summary> /// <returns> /// True if this page was successfully validated. /// </returns> public virtual bool Complete() { Guid scenarioId = Ticket.ScenarioIds.FirstOrDefault(); if (!ValidateInput(scenarioId)) { return(false); } // STE-only if (GlobalSettings.IsDistributedSystem) { PopulateSelectedVMs(); } using (EnterpriseTestContext context = new EnterpriseTestContext()) { // Perform a data integrity check on the scenario if (PerformDataIntegrityCheck(context, scenarioId) == false) { Cancel?.Invoke(this, EventArgs.Empty); return(false); } PopulateNotificationSettings(); SetAssociatedProducts(); // Populate ticket data from the UI Ticket.CollectEventLogs = eventLog_CheckBox.Checked; Ticket.SessionName = string.IsNullOrEmpty(sessionName_ComboBox.Text) ? selectedScenario_TextBox.Text : sessionName_ComboBox.Text; Ticket.SessionType = sessionType_ComboBox.Text; Ticket.SessionCycle = sessionCycle_ComboBox.Text; Ticket.Reference = WizardPageManager.GetReferenceData(reference_TextBox); Ticket.SessionNotes = notes_TextBox.Text; Ticket.DurationHours = (int)runtime_NumericUpDown.Value; SessionLogRetention selected = EnumUtil.GetByDescription <SessionLogRetention>((string)retention_ComboBox.SelectedItem); Ticket.ExpirationDate = selected.GetExpirationDate(DateTime.Now); Ticket.LogLocation = logLocation_TextBox.Text; Ticket.RemoveUnresponsiveDevices = deviceOffline_CheckBox.Checked; // Save session name and selected VMs SaveSessionName(context, scenarioId); context.SaveChanges(); } // Save selected scenario to settings so it can be selected next time Properties.Settings.Default.LastExecutedScenario = scenarioId; Properties.Settings.Default.Save(); // Initiate the session with the dispatcher TraceFactory.Logger.Debug("Calling Initiate() on {0}".FormatWith(Ticket.SessionId)); SessionClient.Instance.InitiateSession(Ticket); return(true); }
/// <summary> /// Imports this instance of MetadataTypeInstallerContract into the EnterpriseTest database. /// </summary> /// <param name="context">The EnterpriseTest data context.</param> public void Import(EnterpriseTestContext context) { var metadataType = context.MetadataTypes.FirstOrDefault(x => x.Name.Equals(Name)); foreach (var installer in Packages.SelectMany(x => x.Settings).Select(x => x.Installer)) { var installerFileName = Path.GetFileName(installer.FilePath); if (!context.SoftwareInstallers.Select(x => x.FilePath).Any(x => x.EndsWith(installerFileName))) { // Add the installer to the database as it doesn't already exist var saveToPath = Path.GetDirectoryName(GlobalSettings.Items[Setting.ExternalSoftware]); var newInstaller = installer.CreateEntity(saveToPath); context.SoftwareInstallers.AddObject(newInstaller); context.SaveChanges(); var directory = Path.GetDirectoryName(newInstaller.FilePath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } // Save the actual installer file to the new location. File.WriteAllBytes(newInstaller.FilePath, Convert.FromBase64String(installer.RawData)); } } foreach (var package in Packages) { var newPackage = package.CreateEntity(metadataType); context.SoftwareInstallerPackages.AddObject(newPackage); foreach (var setting in package.Settings) { var newSetting = setting.CreateEntity(); newSetting.InstallerId = setting.Installer.InstallerId; newSetting.PackageId = newPackage.PackageId; context.SoftwareInstallerSettings.AddObject(newSetting); } } context.SaveChanges(); }
private void removeAssociation_Button_Click(object sender, EventArgs e) { using (EnterpriseTestContext context = new EnterpriseTestContext()) { //var meta = metaData_ComboBox.SelectedItem as MetadataType; var metadata = context.MetadataTypes.Where(y => y.Name == _selectedMetadata).First(); var prod = context.AssociatedProducts.Where(y => y.AssociatedProductId == _selectedProductId).First(); prod.MetadataTypes.Remove(metadata); context.SaveChanges(); } LoadPage(); }
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(); }
/// <summary> /// Saves the changes. /// </summary> private void SaveChanges() { using (new BusyCursor()) { foreach (UserGroup group in _groups) { if (group.EntityState == EntityState.Added || group.EntityState == EntityState.Detached) { _context.UserGroups.AddObject(group); } } _context.SaveChanges(); } }
/// <summary> /// Performs final validation before allowing the user to navigate away from the page. /// </summary> /// <returns> /// True if this page was successfully validated. /// </returns> public bool Complete() { if (!ValidateInput()) { return(false); } // We're gonna need a data context several times in the following lines using (EnterpriseTestContext context = new EnterpriseTestContext()) { List <EnterpriseScenario> scenarios = EnterpriseScenario.Select(context, Ticket.ScenarioIds).ToList(); // Perform a data integrity check on the scenarios if (PerformDataIntegrityCheck(scenarios) == false) { return(false); } //PopulateNotificationSettings() TODO: What about the email list? The ticket has an email list. Can we repurpose it for batch operations? // Populate ticket data from the UI Ticket.ScenarioIds = GetSelectedScenarioIds(); Ticket.CollectEventLogs = false; Ticket.SessionName = sessionName_ComboBox.Text; Ticket.SessionType = sessionType_ComboBox.Text; Ticket.SessionCycle = sessionCycle_ComboBox.Text; Ticket.Reference = WizardPageManager.GetReferenceData(reference_TextBox); Ticket.SessionNotes = notes_TextBox.Text; Ticket.DurationHours = (int)runtime_NumericUpDown.Value; SessionLogRetention logRetention = EnumUtil.GetByDescription <SessionLogRetention>((string)retention_ComboBox.SelectedItem); Ticket.ExpirationDate = logRetention.GetExpirationDate(DateTime.Now); Ticket.LogLocation = GlobalSettings.WcfHosts[WcfService.DataLog]; SetAssociatedProducts(context, scenarios); // Doesn't make sense to save session name for batch operation. context.SaveChanges(); } // Initiate the session with the dispatcher TraceFactory.Logger.Debug($"Calling Initiate() on {Ticket.SessionId}"); SessionClient.Instance.InitiateSession(Ticket); return(true); }
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 InsertSystemSetting(string subType, string settingName, string settingValue, string description) { using (EnterpriseTestContext context = new EnterpriseTestContext()) { if (!context.SystemSettings.Any(s => s.Name.Equals(settingName, StringComparison.InvariantCultureIgnoreCase))) { SystemSetting newSetting = new SystemSetting() { Type = SettingType.SystemSetting.ToString(), SubType = subType, Name = settingName, Value = settingValue, Description = description }; context.AddToSystemSettings(newSetting); context.SaveChanges(); } } }
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(); } } }
private bool SaveChanges() { foreach (SoftwareInstallerPackage package in _packages) { if (package.EntityState == EntityState.Added || package.EntityState == EntityState.Detached) { _dataContext.SoftwareInstallerPackages.AddObject(package); } } try { _dataContext.SaveChanges(); return(true); } catch (UpdateException ex) { TraceFactory.Logger.Error(ex); MessageBox.Show("Only one instance of an installer can be added to an installer package.", "Update Installer Package", MessageBoxButtons.OK, MessageBoxIcon.Error); } //If we end up here, the save failed. return(false); }
private void addProduct_button_Click(object sender, EventArgs e) { string vendor = vendor_TextBox.Text; string name = name_TextBox.Text; if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(vendor)) { MessageBox.Show("Name and Vendor Fields can not be blank", "Product Add Error", MessageBoxButtons.OK); return; } using (EnterpriseTestContext context = new EnterpriseTestContext()) { var temp = context.AssociatedProducts.Where(y => y.Name == name && y.Vendor == vendor); if (temp.Count() > 0) { MessageBox.Show("Name and Vendor already exists in the database", "Product Add Error", MessageBoxButtons.OK); return; } else { Guid id = SequentialGuid.NewGuid(); AssociatedProduct newProd = new AssociatedProduct(); newProd.AssociatedProductId = id; newProd.Name = name; newProd.Vendor = vendor; context.AssociatedProducts.AddObject(newProd); context.SaveChanges(); LoadPage(); } } }
private void ImportScenarios(string fileName, Guid folderId) { int totalActivities = 0; List <Database.EnterpriseScenario> exportedScenarios; using (FileStream fs = File.OpenRead(fileName)) { StreamReader sReader = new StreamReader(fs); var scenarioString = sReader.ReadToEnd(); exportedScenarios = (List <Database.EnterpriseScenario>)JsonConvert.DeserializeObject(scenarioString, typeof(List <Database.EnterpriseScenario>)); } using (EnterpriseTestContext context = new EnterpriseTestContext(_currentDatabase)) { foreach (var sourceScenario in exportedScenarios) { EnterpriseScenario targetScenario = new EnterpriseScenario { Name = sourceScenario.Name, EnterpriseScenarioId = SequentialGuid.NewGuid(), FolderId = folderId, Company = sourceScenario.Company, Deleted = false, Description = sourceScenario.Description, Owner = UserManager.CurrentUserName, ScenarioSettings = sourceScenario.ScenarioSettings, Vertical = sourceScenario.Vertical }; //if (context.EnterpriseScenarios.FirstOrDefault(x => // x.EnterpriseScenarioId == sourceScenario.EnterpriseScenarioId) != null) //{ // targetScenario.EnterpriseScenarioId = SequentialGuid.NewGuid(); //} foreach (var sourceScenarioVirtualResource in sourceScenario.VirtualResources) { SolutionTester targetVirtualResource = new SolutionTester("SolutionTester") { Description = sourceScenarioVirtualResource.Description, Enabled = true, EnterpriseScenarioId = targetScenario.EnterpriseScenarioId, Name = sourceScenarioVirtualResource.Name, InstanceCount = sourceScenarioVirtualResource.InstanceCount, Platform = sourceScenarioVirtualResource.Platform, ResourceType = sourceScenarioVirtualResource.ResourceType, ResourcesPerVM = sourceScenarioVirtualResource.ResourcePerVM, TestCaseId = sourceScenarioVirtualResource.TestCaseId, VirtualResourceId = SequentialGuid.NewGuid(), DurationTime = sourceScenarioVirtualResource.DurationTime, MaxActivityDelay = sourceScenarioVirtualResource.MaxActivityDelay, MinActivityDelay = sourceScenarioVirtualResource.MinActivityDelay, RandomizeActivities = sourceScenarioVirtualResource.RandomizeActivities, RandomizeActivityDelay = sourceScenarioVirtualResource.RandomizeActivityDelay, ExecutionMode = EnumUtil.Parse <ExecutionMode>(sourceScenarioVirtualResource.RunMode), MaxStartupDelay = sourceScenarioVirtualResource.MaxStartupDelay, MinStartupDelay = sourceScenarioVirtualResource.MinStartupDelay, RandomizeStartupDelay = sourceScenarioVirtualResource.RandomizeStartupDelay, RepeatCount = sourceScenarioVirtualResource.RepeatCount, AccountType = SolutionTesterCredentialType.DefaultDesktop, UseCredential = false }; //if (context.VirtualResources.FirstOrDefault(x => // x.VirtualResourceId == sourceScenarioVirtualResource.VirtualResourceId) != null) //{ // targetVirtualResource.VirtualResourceId = SequentialGuid.NewGuid(); //} foreach (var virtualResourceMetadata in sourceScenarioVirtualResource.VirtualResourceMetadata) { VirtualResourceMetadata targetVirtualResourceMetadata = new VirtualResourceMetadata(virtualResourceMetadata.ResourceType, virtualResourceMetadata.MetadataType) { VirtualResourceId = targetVirtualResource.VirtualResourceId, Deleted = false, Enabled = true, ExecutionPlan = virtualResourceMetadata.ExecutionPlan, Metadata = virtualResourceMetadata.Metadata, MetadataVersion = virtualResourceMetadata.MetadataVersion, MetadataType = virtualResourceMetadata.MetadataType, Name = virtualResourceMetadata.Name, ResourceType = virtualResourceMetadata.ResourceType, VirtualResourceMetadataId = SequentialGuid.NewGuid(), }; //if (context.VirtualResourceMetadataSet.FirstOrDefault(x => // x.VirtualResourceMetadataId == // targetVirtualResourceMetadata.VirtualResourceMetadataId) != null) //{ // targetVirtualResourceMetadata.VirtualResourceMetadataId = SequentialGuid.NewGuid(); //} targetVirtualResourceMetadata.AssetUsage = VirtualResourceMetadataAssetUsage .CreateVirtualResourceMetadataAssetUsage( targetVirtualResourceMetadata.VirtualResourceMetadataId, Serializer.Serialize(_edtAssetSelectionControl.AssetSelectionData).ToString()); targetVirtualResource.VirtualResourceMetadataSet.Add(targetVirtualResourceMetadata); totalActivities++; } targetScenario.VirtualResources.Add(targetVirtualResource); } context.EnterpriseScenarios.AddObject(targetScenario); } try { MessageBox.Show( $"Found {totalActivities} activities to import. This might take few minutes to complete. Please be patient. Press OK to proceed.", ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information); context.SaveChanges(); MessageBox.Show($"{exportedScenarios.Count} scenarios successfully imported.", ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information); } catch (SqlException sqlException) { MessageBox.Show($"Error occurred while importing the scenario. {ScalableTest.Extension.JoinAllErrorMessages(sqlException)}", ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error); } catch (UpdateException updateException) { MessageBox.Show($"Error occurred while importing the scenario. {ScalableTest.Extension.JoinAllErrorMessages(updateException)}", ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception e) { MessageBox.Show($"An unknown error occurred while importing scenario. {ScalableTest.Extension.JoinAllErrorMessages(e)}", ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error); } } }
private void ok_Button_Click(object sender, EventArgs e) { _context.SaveChanges(); this.DialogResult = DialogResult.OK; }
/// <summary> /// Commits all changes to this controller's managed <see cref="EnterpriseTestContext" />. /// </summary> public void CommitChanges() { _context?.SaveChanges(); }
private void ProcessFinish() { if (_completionControl.SelectedFolderId == Guid.Parse("00000000-0000-0000-0000-000000000000")) { MessageBox.Show("Please Select a destination folder", "Import Scenario", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } StringBuilder importMessage = new StringBuilder("The Scenario '"); importMessage.Append(_scenarioContract.Name); importMessage.AppendLine("' was successfully imported."); try { using (new BusyCursor()) { if (!_masterCompositeControl.Validate()) { return; } if (_compositeContract != null) { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { bool changesMade = false; HashSet <Guid> pQueues = new HashSet <Guid>(); foreach (var printer in _compositeContract.Printers) { if (!context.Assets.Any(x => x.AssetId.Equals(printer.AssetId))) { context.Assets.Add(ContractFactory.Create(printer, context)); changesMade = true; } } var items = _compositeContract.Scenario.ActivityPrintQueueUsage; XmlDocument doc = new XmlDocument(); foreach (var item in items) { doc.LoadXml(item.XmlSelectionData); XmlNode node = doc.DocumentElement.FirstChild.FirstChild.FirstChild; if (!string.IsNullOrEmpty(node.InnerText) && IsGuid(node.InnerText)) { if (!pQueues.Contains(Guid.Parse(node.InnerText)) && node.FirstChild.FirstChild.Name == "_printQueueId") { pQueues.Add(Guid.Parse(node.InnerText)); } } } var containsQueues = context.RemotePrintQueues.Where(x => pQueues.Contains(x.RemotePrintQueueId)).Select(x => x.Name); if (pQueues.Count() != containsQueues.Count() || containsQueues.Count() == 0) { importMessage.AppendLine("Warning: Some Print Queues May Not Have Imported."); importMessage.AppendLine("Please use Bulk Edit Tool to resolve."); } if (changesMade) { context.SaveChanges(); } } } using (EnterpriseTestContext context = new EnterpriseTestContext()) { var importMaps = new List <ContractFactory.ImportMap>(); if (_finalScenarioEntity == null) { _finalScenarioEntity = ContractFactory.Create(_scenarioContract, out importMaps); } var emptyPlatforms = ( from r in _finalScenarioEntity.VirtualResources where (string.IsNullOrEmpty(r.Platform) || r.Platform.Equals("LOCAL")) && !r.ResourceType.Equals("SolutionTester") select r ); if (emptyPlatforms != null && emptyPlatforms.Count() > 0) { using (AssignPlatformDialog dialog = new AssignPlatformDialog(emptyPlatforms)) { dialog.ShowDialog(); return; } } _finalScenarioEntity.Owner = UserManager.CurrentUserName; foreach (var group in _scenarioContract.UserGroups) { var entity = context.UserGroups.FirstOrDefault(x => x.GroupName.Equals(group)); if (entity != null) { _finalScenarioEntity.UserGroups.Add(entity); } } _finalScenarioEntity.FolderId = _completionControl.SelectedFolderId; context.AddToEnterpriseScenarios(_finalScenarioEntity); CreateFolders(_scenarioContract, _finalScenarioEntity, context, importMaps); context.SaveChanges(); ScenarioImported = true; } if (_importMetadataMessages.Length > 0) { importMessage.AppendLine(_importMetadataMessages.ToString()); } MessageBox.Show(importMessage.ToString(), "Import Scenario", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); TraceFactory.Logger.Error(ex); } }
private bool ImportConfigurationFiles() { try { SystemTrace.Instance.Debug("Checking for import files"); string[] importFiles = Directory.GetFiles("Import", "*.stbs"); if (importFiles.Count() > 0) { // Import any exported scenario files that were included in the installation using (EnterpriseTestContext context = new EnterpriseTestContext()) { UpdateStatus("Importing Scenarios"); ContractFactory.OnStatusChanged += ContractFactory_OnStatusChanged; string folderName = $"V{_ticket.CurrentVersion} Imports"; ConfigurationTreeFolder folder = context.ConfigurationTreeFolders.FirstOrDefault(x => x.Name.Equals(folderName)); if (folder == null) { folder = new ConfigurationTreeFolder(SequentialGuid.NewGuid(), folderName, ConfigurationObjectType.ScenarioFolder.ToString(), null); context.AddToConfigurationTreeFolders(folder); context.SaveChanges(); } //Ensure the path exists for import files in the shared folder location StringBuilder importDestination = new StringBuilder(_fileSharePath); importDestination.Append("\\Import\\V"); importDestination.Append(_ticket.CurrentVersion); Directory.CreateDirectory(importDestination.ToString()); importDestination.Append("\\"); int destinationPathIndex = importDestination.Length; foreach (string fileName in importFiles) { SystemTrace.Instance.Debug($"Importing {fileName}"); EnterpriseScenario enterpriseScenario = null; try { XElement fileData = XElement.Parse(File.ReadAllText(fileName)); // If this is a composite contract file it may contain printer and document // information in addition to the base scenario data. if (fileData.Name.LocalName == "Composite") { var compositeContract = Serializer.Deserialize <EnterpriseScenarioCompositeContract>(fileData); if (!ImportExportUtil.ProcessCompositeContractFile(compositeContract)) { SystemTrace.Instance.Error($"Failed to process composite contract: {fileName}."); } enterpriseScenario = ContractFactory.Create(compositeContract.Scenario); } else { var scenarioContract = Serializer.Deserialize <EnterpriseScenarioContract>(fileData); enterpriseScenario = ContractFactory.Create(scenarioContract); } enterpriseScenario.FolderId = folder.ConfigurationTreeFolderId; SystemTrace.Instance.Debug($"Adding Scenario '{enterpriseScenario.Name}'"); context.AddToEnterpriseScenarios(enterpriseScenario); // Copy the import file to the shared folder location importDestination.Append(Path.GetFileName(fileName)); try { File.Copy(fileName, importDestination.ToString(), true); } catch (Exception ex) { SystemTrace.Instance.Error($"Failed to copy '{fileName}' to '{importDestination.ToString()}'.", ex); } importDestination.Remove(destinationPathIndex, importDestination.Length - destinationPathIndex); } catch (Exception ex) { // Log an error for the current file, but keep going SystemTrace.Instance.Error($"Failed to import: {fileName}", ex); } } context.SaveChanges(); ContractFactory.OnStatusChanged -= ContractFactory_OnStatusChanged; UpdateStatus("Scenario Import Complete"); } } } catch (Exception ex) { SendError(ex); return(false); } return(true); }
private bool InsertPluginTypes() { UpdateStatus("Enabling new plugins for this installation"); try { using (EnterpriseTestContext context = new EnterpriseTestContext()) { List <MetadataType> currentPlugins = context.MetadataTypes.ToList(); string[] lines = File.ReadAllLines("PluginList.txt"); SendProgressStart(lines.Count()); for (int i = 0; i < lines.Count(); i++) { if (!string.IsNullOrEmpty(lines[i]) && !lines[i].StartsWith("//") && !lines[i].StartsWith("*")) { string[] items = lines[i].Split(','); if (items.Length < 1) { SystemTrace.Instance.Error("Need at least 1 plugin name per line"); } else { string name = items[0].Trim(); // default the title to the name if not specified string title = (items.Length > 1 && !string.IsNullOrEmpty(items[1]) ? items[1].Trim() : name); // default the group to blank if not specified string group = (items.Length > 2 && !string.IsNullOrEmpty(items[2]) ? items[2].Trim() : string.Empty); // default the icon to null if not specified byte[] icon = (items.Length > 3 && !string.IsNullOrEmpty(items[3]) ? Convert.FromBase64String(items[3].Trim()) : null); MetadataType type = new MetadataType() { Name = name, Title = title, Group = group, AssemblyName = "Plugin.{0}.dll".FormatWith(name), Icon = icon }; // Only add plugins if they are new if (!currentPlugins.Any(x => x.Name.Equals(name))) { if (!context.MetadataTypes.Any(x => x.Name.Equals(type.Name))) { foreach (var resourceType in context.ResourceTypes) { SystemTrace.Instance.Debug("Enabling {0}".FormatWith(type.Name)); type.ResourceTypes.Add(resourceType); } SendProgressUpdate(i + 1); if (!context.MetadataTypes.Any(x => x.Name.Equals(type.Name))) { context.AddToMetadataTypes(type); } } } } } } context.SaveChanges(); SendProgressEnd(); } } catch (Exception ex) { SendError(ex); return(false); } return(true); }