private void BuildManagement_Load(object sender, EventArgs e) { using (AssetInventoryContext context = new AssetInventoryContext()) { serverFilter_ToolStripComboBox.ComboBox.DataSource = FrameworkServerType.SelectAll(context); } }
private static List <MobileDevice> GetMobileDevices() { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { return(context.Assets.Include(n => n.Reservations).OfType <MobileDevice>().ToList()); } }
/// <summary> /// Updates the status of all printers in asset inventory. /// </summary> public void UpdatePrinterStatus() { using (AssetInventoryContext context = new AssetInventoryContext(_connectionString)) { List <Printer> printers = context.Assets.OfType <Printer>().ToList(); LogDebug($"Updating status of {printers.Count} printers."); foreach (Printer printer in printers) { if (!string.IsNullOrEmpty(printer.Address1)) { if (IPAddress.TryParse(printer.Address1, out IPAddress printerIpAddress)) { if (!printerIpAddress.IsIPv6LinkLocal) { printer.Online = PingDevice(printerIpAddress, TimeSpan.FromSeconds(5)); } } } } context.SaveChanges(); LogDebug("Finished updating printer status."); } }
/// <summary> /// Initializes this form instance. /// </summary> private void Initialize() { InitializeComponent(); UserInterfaceStyler.Configure(this, FormStyle.FixedDialog); ShowIcon = true; _context = DbConnect.AssetInventoryContext(); // Set up Validation fieldValidator.RequireValue(textBox_AssetId, label_AssetId); fieldValidator.RequireValue(textBox_Product, label_Product); fieldValidator.RequireValue(textBox_Address, label_Address); fieldValidator.RequireValue(textBox_VmName, label_VmName); fieldValidator.RequireCustom(label_Capabilites, () => _capabilityControls.Any(n => n.Checked), "At least one capability must be selected."); fieldValidator.SetIconAlignment(textBox_AssetId, ErrorIconAlignment.MiddleLeft); fieldValidator.SetIconAlignment(textBox_Product, ErrorIconAlignment.MiddleLeft); fieldValidator.SetIconAlignment(textBox_Address, ErrorIconAlignment.MiddleLeft); fieldValidator.SetIconAlignment(textBox_VmName, ErrorIconAlignment.MiddleLeft); fieldValidator.SetIconAlignment(label_Capabilites, ErrorIconAlignment.MiddleLeft); _capabilityControls = new List <CheckBox>() { checkBox_Scan, checkBox_ControlPanel, checkBox_Mobile }; }
protected override void StartService(CommandLineArguments args) { if (args == null) { throw new ArgumentNullException("args"); } FrameworkServiceHelper.LoadSettings(args, autoRefresh: true); using (EnterpriseTestContext dataContext = new EnterpriseTestContext()) { GlobalSettings.IsDistributedSystem = dataContext.VirtualResources.Any(r => r.ResourceType == "OfficeWorker"); } string dispatcherHostName = "localhost"; if (GlobalSettings.IsDistributedSystem) { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { var dispatcher = context.FrameworkServers.FirstOrDefault(x => x.Active && x.ServerTypes.Any(n => n.Name == "BTF")); if (dispatcher == null) { TraceFactory.Logger.Error("Could not find any dispatchers reserved for BTF Execution."); return; } } } SessionClient.Instance.Initialize(dispatcherHostName); SessionClient.Instance.SessionStartupTransitionReceived += Instance_SessionStartupTransitionReceived; SessionClient.Instance.SessionStateReceived += Instance_SessionStateReceived; _server = WebApp.Start <Startup>(url: _baseAddress); _executionTimer.Start(); }
/// <summary> /// Initializes a new instance of the <see cref="VirtualMachinePlatformConfigForm"/> class. /// </summary> public VirtualMachinePlatformConfigForm() { InitializeComponent(); UserInterfaceStyler.Configure(this, FormStyle.SizeableDialog); _assetInventoryContext = DbConnect.AssetInventoryContext(); _enterpriseTestContext = DbConnect.EnterpriseTestContext(); }
/// <summary> /// Gets a collection of printer products for the specified family from Asset Inventory. /// </summary> /// <param name="printerFamily">The printer family.</param> /// <returns>A collection of printer products.</returns> public IEnumerable <string> GetPrinterProducts(string printerFamily) { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { return(context.PrinterProducts.Where(n => n.Family == printerFamily).Select(n => n.Name).Distinct().ToList()); } }
/// <summary> /// Populates the dropdown with Printer family and displays the it's Printer names. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrinterProductsForm_Load(object sender, EventArgs e) { productName_dataGridView.AutoGenerateColumns = false; productFamily_ComboBox.Refresh(); List <string> familyItems; using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { familyItems = context.PrinterProducts.Select(n => n.Family).Distinct().ToList(); } if (!familyItems.Any()) { MessageBox.Show("There are no Product Categories available in the database.\nPlease add the Product Category and try again.", "Product Category Loading Failure", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } foreach (var item in familyItems) { productFamily_ComboBox.Items.Add(item); _products.Add(item, new SortableBindingList <StringValue>()); foreach (var productName in _context.PrinterProducts.Where(n => n.Family == item).Select(n => n.Name).Distinct()) { _products[item].Add(new StringValue(productName)); } } if (productFamily_ComboBox.Items.Count > 0) { productFamily_ComboBox.SelectedIndex = 0; } }
private DomainAccountReservationSet GetReservedAccounts(bool mockReserve = false) { DomainAccountReservationSet result = new DomainAccountReservationSet(Ticket.SessionId); using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { if (mockReserve) { //Build a mock reservation foreach (var poolType in Quantities.DomainAccountQuantity.Keys) { DomainAccountPool pool = DomainAccountService.SelectPool(context, poolType); result.Add(poolType, pool, 0, Quantities.DomainAccountQuantity[poolType]); } } else { foreach (DomainAccountReservation reservation in DomainAccountService.SelectReservationsBySession(context, Ticket.SessionId)) { DomainAccountPool pool = DomainAccountService.SelectPool(context, reservation.DomainAccountKey); result.Add(reservation.DomainAccountKey, pool, reservation.StartIndex, reservation.Count); } } } return(result); }
private void remove_Button_Click(object sender, EventArgs e) { var row = GetFirstSelectedRow(); if (row != null) { Printer printer = row.DataBoundItem as Printer; DialogResult dialogResult = MessageBox.Show ( "Removing Printer {0}. Do you want to continue?".FormatWith(printer.AssetId), "Delete Printer", MessageBoxButtons.YesNo, MessageBoxIcon.Question ); if (dialogResult == DialogResult.Yes) { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { Asset asset = context.Assets.FirstOrDefault(n => n.AssetId == printer.AssetId); context.Assets.Remove(asset); context.SaveChanges(); } RefreshItems(); } } }
private static List <Camera> GetCameras() { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { return(context.Assets.Include(n => n.Reservations).OfType <Camera>().ToList()); } }
/// <summary> /// Creates asset reservations for the specified time period. /// Attempts to reserve devices for the entire period, but will create a partial reservation /// if the device is not available for the entire time. /// </summary> /// <param name="assetIds">The assets to reserve.</param> /// <param name="sessionId">The session ID to reserve for.</param> /// <param name="reservationKey">The reservation key indicating which existing reservations may be used.</param> /// <param name="requestedStart">The requested start.</param> /// <param name="requestedEnd">The requested end.</param> /// <returns>A collection of <see cref="AssetReservationResult" /> describing the reservations that could be made.</returns> /// <exception cref="ArgumentNullException"><paramref name="assetIds" /> is null.</exception> public IEnumerable <AssetReservationResult> ReserveAssets(IEnumerable <string> assetIds, string sessionId, string reservationKey, DateTime requestedStart, DateTime requestedEnd) { if (assetIds == null) { throw new ArgumentNullException(nameof(assetIds)); } List <AssetReservationResult> results = new List <AssetReservationResult>(); using (AssetInventoryContext context = new AssetInventoryContext(_connectionString)) { //Include associated Assets, like Cameras List <string> assetIdsFinal = assetIds.ToList(); assetIdsFinal.AddRange(GetAssociatedCameras(context, assetIds)); LogInfo($"Reserving {assetIdsFinal.Count()} assets for session {sessionId}."); // Get all the data from the database at once, but then loop through the requested IDs to see if there are any missing List <Asset> assets = context.Assets.Include(n => n.Pool).Include(n => n.Reservations).Where(n => assetIdsFinal.Contains(n.AssetId)).ToList(); foreach (string assetId in assetIdsFinal) { Asset asset = assets.FirstOrDefault(n => n.AssetId == assetId); if (asset != null) { CreateReservations(asset, sessionId, reservationKey, requestedStart, requestedEnd); AssetReservationResult result = GetReservationResult(asset, sessionId, requestedStart, requestedEnd); results.Add(result); } else { // Asset was not found in database LogWarn($"Asset {assetId} was not found in Asset Inventory database."); results.Add(new AssetReservationResult(assetId, AssetAvailability.Unknown)); } } // Update ReservationHistory where configured to do so foreach (Asset asset in assets.Where(n => n.Pool.TrackReservations == true)) { foreach (AssetReservation reservation in asset.Reservations.Where(n => context.Entry(n).State == EntityState.Added)) { context.ReservationHistory.Add(new ReservationHistory(reservation)); } } // Commit the reservations to the database try { context.SaveChanges(); } catch (DbUpdateException ex) when(ex.InnerException?.InnerException?.Message?.Contains(_duplicateReservationConstraint) == true) { // This may happen due to concurrency conflicts, e.g. somebody else creates a reservation // after we have retrieved the existing reservations from the database but before we attempt to save them back. throw new ResourceReservationException("Failed to create reservation due to a conflict with an existing reservation.", ex); } } return(results); }
/// <summary> /// Selects a summary of sessions and their Virtual Machine usage /// </summary> /// <returns></returns> public static dynamic SelectVirtualMachineSessionUsageSummary() { List <FrameworkClient> virtualMachines = null; List <SessionInfo> sessionSummarySet = null; using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { virtualMachines = context.FrameworkClients.ToList(); } //Get the list of sessions that are currently consuming VMs IEnumerable <string> sessionIds = virtualMachines.Select(s => s.SessionId).Distinct(); using (DataLogContext context = DbConnect.DataLogContext()) { sessionSummarySet = context.Sessions.Where(s => sessionIds.Contains(s.SessionId)).ToList(); } var now = DateTime.Now; var workingSet = ( from v in virtualMachines from s in sessionSummarySet.Where(s => s.SessionId == v.SessionId) orderby v.SortOrder select new { SessionId = s.SessionId, ScenarioName = s.SessionName, Owner = s.Owner, Status = s.Status, Dispatcher = s.Dispatcher, StartDate = s.StartDateTime?.LocalDateTime, EndDate = s.ProjectedEndDateTime?.LocalDateTime, TimeRunning = (s.StartDateTime == null ? "Unknown" : "{0:%d} Days {0:%h} Hours".FormatWith(now - s.StartDateTime)), XP = (v.FrameworkClientHostName != null && v.FrameworkClientHostName.StartsWith("X", StringComparison.OrdinalIgnoreCase)) ? 1 : 0, W7 = (v.FrameworkClientHostName != null && v.FrameworkClientHostName.StartsWith("W7", StringComparison.OrdinalIgnoreCase)) ? 1 : 0, W8 = (v.FrameworkClientHostName != null && v.FrameworkClientHostName.StartsWith("W8", StringComparison.OrdinalIgnoreCase)) ? 1 : 0, } ).ToList(); // summarize the results by grouping and counting dynamic result = (from f in workingSet group f by f.SessionId into s select new { SessionId = s.Key, ScenarioName = s.First().ScenarioName, Owner = s.First().Owner, Status = s.First().Status, Dispatcher = s.First().Dispatcher, StartDate = s.First().StartDate, EndDate = s.First().EndDate, TimeRunning = s.First().TimeRunning, XPCount = s.Sum(x => x.XP), WSevCount = s.Sum(x => x.W7), W8Count = s.Sum(x => x.W8), }).ToList(); return(result); }
private void serverFilter_ToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) { var selectedServer = serverFilter_ToolStripComboBox.ComboBox.SelectedItem as FrameworkServerType; dispatchers_DataGridView.DataSource = null; if (_context == null) { _context = new AssetInventoryContext(); } if (selectedServer.Name == "Dispatcher") { var dispatchers = FrameworkServer.Select(_context, ServerType.Dispatcher, GlobalSettings.Environment).ToList(); dispatchers_DataGridView.DataSource = dispatchers; } else if (selectedServer.Name == "Print") { var printServers = FrameworkServer.Select(_context, ServerType.Print, GlobalSettings.Environment).ToList(); dispatchers_DataGridView.DataSource = printServers; } else if (selectedServer.Name == "Citrix") { var citrixServers = FrameworkServer.Select(_context, ServerType.Citrix, GlobalSettings.Environment).ToList(); dispatchers_DataGridView.DataSource = citrixServers; } }
/// <summary> /// Adds Asset info to the specified <see cref="SystemManifest"/>. /// </summary> /// <param name="manifest">The <see cref="SystemManifest"/>.</param> public void AssignManifestInfo(SystemManifest manifest) { manifest.AllAssets.Clear(); manifest.ActivityAssets.Clear(); List <AssetInfo> assetInfoList = new List <AssetInfo>(); var assetIds = _activityAssets.Values.SelectMany(n => n).Distinct().ToList(); using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { assetInfoList.AddRange(context.Assets.Where(n => assetIds.Contains(n.AssetId)).ToAssetInfoCollection()); assetInfoList.AddRange(context.BadgeBoxes.Where(n => assetIds.Contains(n.PrinterId)).ToBadgeBoxInfoCollection()); } foreach (AssetInfo asset in assetInfoList) { manifest.AllAssets.Add(asset); TraceFactory.Logger.Debug("asset: " + asset.AssetId + " Desc: " + asset.Description); } foreach (var activityAsset in _activityAssets) { manifest.ActivityAssets.Add(activityAsset.Key, activityAsset.Value); } }
/// <summary> /// Retrieves the simulators listed in table Assets and if available what their reservations are. /// </summary> private void GetMasterList() { _masterList = new SimReservedList(); using (AssetInventoryContext aie = DbConnect.AssetInventoryContext()) { var matches = (from ds in aie.Assets.OfType <DeviceSimulator>() join ar in aie.AssetReservations on ds.AssetId equals ar.AssetId into mgtGroup from item in mgtGroup.DefaultIfEmpty() select new { ds.AssetId, ds.Product, ds.Address, ds.VirtualMachine, SessionId = item.SessionId == null ? "" : item.SessionId, ReservedFor = item.ReservedFor == null ? "" : item.ReservedFor }); foreach (var m in matches) { SimReserved ent = new SimReserved(); ent.AssetId = m.AssetId; ent.Product = m.Product; ent.HostAddress = m.Address; ent.VirtualMachine = m.VirtualMachine; ent.SessionId = m.SessionId; ent.ReservedFor = m.ReservedFor; _masterList.Add(ent); } } }
protected override void LoadUserPools() { userPool_ComboBox.DisplayMember = "Description"; DomainAccountPool selectedPool = null; List <DomainAccountPool> userPools = null; using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { userPools = context.DomainAccountPools.OrderBy(x => x.Description).ToList(); } if (userPools.Count > 0) { bool testerHasUserPool = !string.IsNullOrEmpty(_tester.UserPool); if (testerHasUserPool) { //If tester has a User Pool setting, select it if it's in the list if (userPools.Any(x => x.DomainAccountKey.Equals(_tester.UserPool))) { selectedPool = userPools.First(x => x.DomainAccountKey.Equals(_tester.UserPool)); } } else { selectedPool = userPools.First(); } } userPool_ComboBox.DataSource = userPools; userPool_ComboBox.SelectedItem = selectedPool; }
/// <summary> /// Helper to create the camera detail info. /// </summary> /// <param name="asset"></param> /// <param name="camera"></param> /// <returns></returns> private static CameraDetail CreateCameraDetail(AssetReservationResult asset, Camera camera) { using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { FrameworkServer server = context.FrameworkServers.Include(n => n.ServerSettings).FirstOrDefault(n => n.HostName == camera.CameraServer); Dictionary <string, string> serverSettings = server?.ServerSettings.ToDictionary(n => n.Name, n => n.Value, StringComparer.OrdinalIgnoreCase); if (serverSettings == null) { // If there are no ServerSettings for the specified camera server, return as much data as we have. // Even if it's incomplete, we don't want to fail here, we want it to fail later in the process when // the framework attempts to contact the camera server during the Validate stage. Log a warning. TraceFactory.Logger.Warn($"Server settings for Camera Server '{camera.CameraServer}' not found in configuration."); } return(new CameraDetail(asset.AssetId, asset.AvailabilityStart, asset.AvailabilityEnd) { Address = serverSettings?["ServerAPIUrl"] ?? string.Empty, CameraId = camera.AssetId, PrinterId = camera.PrinterId, CameraServer = camera.CameraServer, ServerUser = serverSettings?["ServerAPIUserName"] ?? string.Empty, ServerPassword = serverSettings?["ServerAPIPassword"] ?? string.Empty, Availability = asset.Availability }); } }
/// <summary> /// Retrieves a collection of output monitor destinations of the specified type. /// </summary> /// <param name="monitorType">The type of output monitor destinations to retrieve.</param> /// <returns>A collection of output monitor destinations.</returns> public IEnumerable <string> GetOutputMonitorDestinations(string monitorType) { STFMonitorType stfMonitorType = (STFMonitorType)Enum.Parse(typeof(STFMonitorType), monitorType); Collection <string> result = new Collection <string>(); using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { foreach (MonitorConfig monitorConfig in context.MonitorConfigs.Where(m => m.MonitorType == monitorType)) { if (monitorConfig.Configuration.StartsWith("<OutputMonitorConfig")) { OutputMonitorConfig outputConfig = LegacySerializer.DeserializeXml <OutputMonitorConfig>(monitorConfig.Configuration); if (stfMonitorType.Equals(STFMonitorType.OutputEmail) || stfMonitorType.Equals(STFMonitorType.DigitalSendNotification)) { result.Add(outputConfig.MonitorLocation); } else { result.Add($@"\\{monitorConfig.ServerHostName}\{outputConfig.MonitorLocation}"); } } } } return(result); }
public static IEnumerable <AssetDetail> CreateAssetDetails(IEnumerable <AssetReservationResult> testAssets) { List <AssetDetail> assetDetails = new List <AssetDetail>(); List <string> assetIds = testAssets.Select(n => n.AssetId).ToList(); using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { List <Asset> assets = context.Assets.Where(n => assetIds.Contains(n.AssetId)).ToList(); foreach (Asset asset in assets) { AssetReservationResult testAsset = testAssets.First(n => n.AssetId == asset.AssetId); AssetDetail assetDetail = CreateAssetDetail(asset, testAsset); assetDetail.Description = asset.ToAssetInfo().Description; assetDetails.Add(assetDetail); } List <BadgeBox> badgeBoxes = context.BadgeBoxes.Where(n => assetIds.Contains(n.PrinterId)).ToList(); foreach (BadgeBox badgeBox in badgeBoxes) { assetDetails.Add(CreateBadgeBoxDetail(badgeBox)); } } return(assetDetails); }
private static void DeleteApplications(AssetInventoryContext entities, Dictionary <String, SortableBindingList <StringValue> > applicationNames) { if (entities == null) { throw new ArgumentNullException("entities"); } if (applicationNames == null) { throw new ArgumentNullException("applicationNames"); } foreach (CitrixPublishedApp app in entities.CitrixPublishedApps) { SortableBindingList <StringValue> appList = null; // Remove each entry in the system that is found in the target applicationNames by hostname // but where the application names is not included in the target set of application names // for that host. if (applicationNames.TryGetValue(app.CitrixServer, out appList) && !appList.Any(n => n.Value.EqualsIgnoreCase(app.ApplicationName))) { entities.CitrixPublishedApps.Remove(app); } } entities.SaveChanges(); }
/// <summary> /// Sends notifications for all expiring licenses. /// </summary> /// <param name="expirationNotifier">The <see cref="ExpirationNotifier" />.</param> public void SendExpirationNotifications(ExpirationNotifier expirationNotifier) { using (AssetInventoryContext context = new AssetInventoryContext(_connectionString)) { List <License> expiringLicenses = context.Licenses.Include(n => n.Owners) .Where(n => n.RequestSentDate == null && DbFunctions.AddDays(DateTime.Now, n.ExpirationNoticeDays) > n.ExpirationDate) .ToList(); LogDebug($"Found {expiringLicenses.Count} expiring licenses."); IEnumerable <Guid> serverIds = expiringLicenses.Select(n => n.FrameworkServerId).Distinct(); Dictionary <Guid, FrameworkServer> servers = context.FrameworkServers .Where(n => serverIds.Contains(n.FrameworkServerId)) .ToDictionary(n => n.FrameworkServerId, n => n); foreach (License license in expiringLicenses) { servers.TryGetValue(license.FrameworkServerId, out FrameworkServer server); bool sentRenewalRequest = false; if (license.SolutionVersion.Equals("latest", StringComparison.InvariantCultureIgnoreCase)) { //If not set to "latest" the licence renewal will be done manually SendNewLicenseRequest(license, server); sentRenewalRequest = true; } SendExpirationNotification(expirationNotifier, license, server, sentRenewalRequest); license.RequestSentDate = DateTime.Now; context.SaveChanges(); } LogDebug("Finished processing license notifications."); } }
/// <summary> /// Creates a Printer object from a PrinterContract. /// </summary> /// <param name="contract"></param> /// <returns></returns> public static Printer Create(PrinterContract contract, AssetInventoryContext context) { var pool = context.AssetPools.FirstOrDefault(n => n.Name == contract.PoolName); Printer printer = new Printer() { AssetId = contract.AssetId, AssetType = contract.AssetType, Pool = pool, Product = contract.Product, Model = contract.Model, Address1 = contract.Address1, Address2 = contract.Address2, Description = contract.Description, Location = contract.Location, PortNumber = contract.PortNumber, SnmpEnabled = contract.SnmpEnabled, Owner = contract.Owner, PrinterType = contract.PrinterType, SerialNumber = contract.SerialNumber, ModelNumber = contract.ModelNumber, EngineType = contract.EngineType, FirmwareType = contract.FirmwareType, }; return(printer); }
/// <summary> /// Reloads all the MonitorConfig items for each monitor running on the current service host. /// </summary> public void RefreshConfig() { TraceFactory.Logger.Debug("Request received to refresh config."); List <MonitorConfig> currentConfiguration = null; using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { currentConfiguration = context.MonitorConfigs.Where(n => n.ServerHostName == Environment.MachineName).ToList(); } lock (_monitors) { RemoveStaleMonitors(new HashSet <Guid>(currentConfiguration.Select(c => c.MonitorConfigId))); } foreach (MonitorConfig config in currentConfiguration) { StfMonitor monitor = _monitors.Where(m => m.MonitorId == config.MonitorConfigId).FirstOrDefault(); if (monitor != null) { // Found existing monitor monitor.RefreshConfig(config); } else { //Monitor exists in the database config, but is not running on the current service host. CreateMonitor(config); } } TraceFactory.Logger.Debug("Config refreshed."); }
/// <summary> /// Creates a new instance of the <see cref="ManifestServerAgent"/> class. /// </summary> /// <param name="scenarioId"></param> public ManifestServerAgent(Guid scenarioId) { using (EnterpriseTestContext context = new EnterpriseTestContext()) { // Retrieve server usage data for all enabled activities in the specified session var activities = (from serverusage in context.VirtualResourceMetadataServerUsages let data = serverusage.ServerSelectionData let metadata = serverusage.VirtualResourceMetadata let resource = metadata.VirtualResource where resource.EnterpriseScenarioId == scenarioId && resource.Enabled == true && metadata.Enabled == true && data != null select new { Id = metadata.VirtualResourceMetadataId, Servers = data }).ToList(); foreach (var activity in activities) { ServerSelectionData serverSelectionData = GetSelectionData(activity.Servers); _activityServers.Add(activity.Id, GetServerIds(serverSelectionData)); } } var serverIds = _activityServers.Values.SelectMany(n => n).Distinct().ToList(); using (AssetInventoryContext assetContext = DbConnect.AssetInventoryContext()) { _servers.AddRange(assetContext.FrameworkServers.Where(n => serverIds.Contains(n.FrameworkServerId)).ToServerInfoCollection()); } }
private static PrintDriverPackage GetDatabaseDriverPackage(AssetInventoryContext context, PrintDeviceDriverCollection drivers, string basePath, bool overwrite) { // Check to see if this entry already exists. var dbDriverPackage = context.PrintDriverPackages.Include("PrintDrivers").FirstOrDefault(n => n.Name == drivers.Version); if (dbDriverPackage != null) { if (overwrite) { // Delete the files. string packagePath = Path.GetDirectoryName(dbDriverPackage.InfX86.TrimEnd('\\')); string deletePath = Path.Combine(basePath, packagePath); if (Directory.Exists(deletePath)) { Directory.Delete(deletePath, recursive: true); } // Remove database entries. while (dbDriverPackage.PrintDrivers.Count != 0) { context.PrintDrivers.Remove(dbDriverPackage.PrintDrivers.First()); } context.PrintDriverPackages.Remove(dbDriverPackage); } else { throw new IOException("Print Driver Package version already exists: " + drivers.Version); } } return(dbDriverPackage); }
/// <summary> /// Handles the Load event of the VirtualMachinePlatformConfigForm control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void VirtualMachineGroupConfigForm_Load(object sender, EventArgs e) { groups_DataGridView.AutoGenerateColumns = false; machines_DataGridView.AutoGenerateColumns = false; Cursor = Cursors.WaitCursor; platformFilter_ToolStripComboBox.Items.Add("All Platforms"); using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { foreach (var item in context.FrameworkClientPlatforms.Where(x => x.Active == true)) { platformFilter_ToolStripComboBox.Items.Add(item); } } platformFilter_ToolStripComboBox.SelectedIndex = 0; // Spin off a thread to load each piece of data, then have then sync up through a // semaphore and come back together in the loadPlatformWorker_RunWorkerCompleted() call // where a bit more initialization will occur BackgroundWorker loadMachinesWorker = new BackgroundWorker(); loadMachinesWorker.DoWork += new DoWorkEventHandler(LoadMachines_DoWork); loadMachinesWorker.RunWorkerAsync(); BackgroundWorker loadGroupsWorker = new BackgroundWorker(); loadGroupsWorker.DoWork += new DoWorkEventHandler(LoadGroups_DoWork); loadGroupsWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(LoadGroups_RunWorkerCompleted); loadGroupsWorker.RunWorkerAsync(); }
private static AssetIdCollection GetAssetIds(AssetSelectionData selectionData) { AssetIdCollection result = new AssetIdCollection(); using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { foreach (string assetId in selectionData.SelectedAssets) { result.Add(assetId); //Check to see if the asset has badge boxes BadgeBox badgeBox = context.BadgeBoxes.FirstOrDefault(n => n.PrinterId == assetId); if (badgeBox != null) { TraceFactory.Logger.Debug($"Asset: {assetId} has associated BadgeBox: {badgeBox.BadgeBoxId}"); result.Add(badgeBox.BadgeBoxId); } //Check to see if the asset has cameras Core.AssetInventory.Camera camera = context.Assets.OfType <Core.AssetInventory.Camera>().FirstOrDefault(c => c.PrinterId == assetId); if (camera != null) { TraceFactory.Logger.Debug($"Asset: {assetId} has associated Camera: {camera.AssetId}"); result.Add(camera.AssetId); } } } return(result); }
private static void UpdateInventory() { int count = 0; TraceFactory.Logger.Debug("Synchronizing VM inventory with vSphere server."); using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { using (var vSphereController = GetVSphereController()) { foreach (VSphereVirtualMachine serverVM in vSphereController.GetVirtualMachines()) { FrameworkClient inventoryVM = Select(context, serverVM.HostName); if (inventoryVM != null) { VMUsageState currentState = EnumUtil.GetByDescription <VMUsageState>(inventoryVM.UsageState); if (currentState != VMUsageState.Unavailable && currentState != VMUsageState.DoNotSchedule && string.IsNullOrEmpty(inventoryVM.SessionId)) { inventoryVM.PowerState = EnumUtil.GetDescription(GetPowerState(serverVM)); inventoryVM.UsageState = EnumUtil.GetDescription(GetUsageState(serverVM)); inventoryVM.LastUpdated = DateTime.Now; } count++; } } } context.SaveChanges(); } TraceFactory.Logger.Debug("Syncronization complete. VM Count: {0}".FormatWith(count)); }
public void LoadPrinters(AssetContractCollection <PrinterContract> printers) { _printers = printers; bool changesMade = false; using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { foreach (var printer in _printers) { if (!context.Assets.Any(x => x.Pool.Name.Equals(printer.PoolName))) { if (context.AssetPools.Count() > 0) { printer.PoolName = context.AssetPools.First().Name; if (!context.Assets.Any(x => x.AssetId.Equals(printer.AssetId))) { context.Assets.Add(ContractFactory.Create(printer, context)); changesMade = true; } } } } if (changesMade) { context.SaveChanges(); } } resolveDataGridView.DataSource = _printers; CheckItemsResolved(); }