public DtoProvisionResponse ConfirmProvisionRequest(DtoConfirmProvisionRequest request) { var computerService = new ServiceComputer(); var computer = computerService.GetByGuid(request.Guid); if (computer == null) { return new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Error } } ; if (computer.ProvisionStatus == EnumProvisionStatus.Status.Reset) { return new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Reset } } ; computer.ProvisionStatus = EnumProvisionStatus.Status.Provisioned; computerService.UpdateComputer(computer); var response = new DtoProvisionResponse(); var clientComServers = new GetClientComServers().Run(request.Guid); if (clientComServers != null) { response.ComServers = clientComServers; } response.ProvisionStatus = EnumProvisionStatus.Status.Provisioned; return(response); }
public ProvisionCompleteTasks() { _groupService = new ServiceGroup(); _computerService = new ServiceComputer(); _groupMembershipService = new ServiceGroupMembership(); _groupMemberships = new List <EntityGroupMembership>(); }
public DtoApiBoolResponse AddToFirstRunGroup() { var clientGuid = RequestContext.Principal.Identity.Name; var client = new ServiceComputer().GetByGuid(clientGuid); if (client == null) { return new DtoApiBoolResponse() { Value = false } } ; var membership = new EntityGroupMembership(); membership.ComputerId = client.Id; membership.GroupId = -2; new ServiceGroupMembership().AddMembership(new List <EntityGroupMembership>() { membership }); return(new DtoApiBoolResponse() { Value = true }); }
public ComputerController() { _computerServices = new ServiceComputer(); _auditLogService = new ServiceAuditLog(); _userId = Convert.ToInt32(((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type == "user_id") .Select(c => c.Value).SingleOrDefault()); }
public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) { var computerGuid = request.Headers["computerGuid"]; var comServer = request.Headers["comServer"]; var certBase64 = request.Headers["certificate"]; byte[] bytes = Convert.FromBase64String(certBase64); X509Certificate2 x509certificate = new X509Certificate2(bytes); var computer = new ServiceComputer().GetByGuid(computerGuid); if (computer == null) { return(false); } if (!new ServiceCertificate().ValidateCert(x509certificate)) { return(false); } var deviceCertEntity = new ServiceCertificate().GetCertificate(computer.CertificateId); var deviceCert = new X509Certificate2(deviceCertEntity.PfxBlob, new EncryptionServices().DecryptText(deviceCertEntity.Password), X509KeyStorageFlags.Exportable); if (!deviceCert.Equals(x509certificate)) { return(false); } return(true); }
public LdapSync() { _groupMemberships = new List <EntityGroupMembership>(); _groupService = new ServiceGroup(); _computerService = new ServiceComputer(); _groupMembershipService = new ServiceGroupMembership(); }
public DtoSocketServerVerify VerifyServer() { var computerGuid = Context.Headers["computerGuid"]; var computer = new ServiceComputer().GetByGuid(computerGuid); if (computer == null) { return(null); } var deviceCertEntity = new ServiceCertificate().GetCertificate(computer.CertificateId); var deviceCert = new X509Certificate2(deviceCertEntity.PfxBlob, new EncryptionServices().DecryptText(deviceCertEntity.Password), X509KeyStorageFlags.Exportable); //Calculate UNIX time DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = DateTime.UtcNow - epochStart; string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString(); string nonce = Guid.NewGuid().ToString("N"); string signatureRawData = requestTimeStamp + nonce; var csp = (RSACryptoServiceProvider)deviceCert.PrivateKey; SHA1Managed sha1 = new SHA1Managed(); UnicodeEncoding encoding = new UnicodeEncoding(); byte[] data = encoding.GetBytes(signatureRawData); byte[] hash = sha1.ComputeHash(data); var signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); var serverVerification = new DtoSocketServerVerify(); serverVerification.nOnce = nonce; serverVerification.Timestamp = requestTimeStamp; serverVerification.signature = Convert.ToBase64String(signature); return(serverVerification); }
//Constructor For Starting Multicast For Group public Multicast(int groupId, int userId) { _computers = new List <EntityComputer>(); _multicastSession = new EntityActiveMulticastSession(); _isOnDemand = false; _group = new ServiceGroup().GetGroup(groupId); _userId = userId; _computerServices = new ServiceComputer(); }
//Constructor For Starting Multicast For On Demand public Multicast(int imageProfileId, string clientCount, string sessionName, int userId, int comServerId) { _multicastSession = new EntityActiveMulticastSession(); _isOnDemand = true; _imageProfile = new ServiceImageProfile().ReadProfile(imageProfileId); _clientCount = clientCount; _group = new EntityGroup { ImageProfileId = _imageProfile.Id }; _userId = userId; _multicastSession.ImageProfileId = _imageProfile.Id; _computerServices = new ServiceComputer(); _comServerId = comServerId; _multicastSession.Name = sessionName; }
public bool Run(DtoInventoryCollection collection, string clientIdentifier) { var client = new ServiceComputer().GetByGuid(clientIdentifier); if (client == null) { return(false); } new ServiceBiosInventory().AddOrUpdate(collection.Bios, client.Id); new ServiceComputerSystemInventory().AddOrUpdate(collection.ComputerSystem, client.Id); new ServiceOsInventory().AddOrUpdate(collection.Os, client.Id); new ServiceProcessorInventory().AddOrUpdate(collection.Processor, client.Id); new ServicePrinterInventory().AddOrUpdate(collection.Printers, client.Id); new ServiceHardDriveInventory().AddOrUpdate(collection.HardDrives, client.Id); new ServiceNicInventory().AddOrUpdate(collection.NetworkAdapters, client.Id); new ServiceWuInventory().Add(collection.WindowsUpdates); new ServiceComputerUpdates().AddOrUpdate(collection.WindowsUpdates, client.Id); new ServiceSoftwareInventory().Add(collection.Software); new ServiceComputerSoftware().AddOrUpdate(collection.Software, client.Id); new ServiceCertificateInventory().Add(collection.Certificates); new ServiceComputerCertificate().AddOrUpdate(collection.Certificates, client.Id); new ServiceAntivirusInventory().AddOrUpdate(collection.AntiVirus, client.Id); new ServiceLogicalVolumeInventory().AddOrUpdate(collection.LogicalVolume, client.Id); new ServiceBitlockerInventory().AddOrUpdate(collection.Bitlocker, client.Id); new ServiceFirewallInventory().AddOrUpdate(collection.Firewall, client.Id); client.LastInventoryTime = DateTime.Now; if (!string.IsNullOrEmpty(collection.ClientVersion)) { client.ClientVersion = collection.ClientVersion; } if (!string.IsNullOrEmpty(collection.PushUrl)) { client.PushUrl = collection.PushUrl; } if (!string.IsNullOrEmpty(collection.HardwareUUID)) { client.UUID = collection.HardwareUUID; } new ServiceComputer().UpdateComputer(client); new ServiceImagingClientId().AddOrUpdate(client.Id); return(true); }
public DtoApiBoolResponse RemoveFromFirstRunGroup() { var clientGuid = RequestContext.Principal.Identity.Name; var client = new ServiceComputer().GetByGuid(clientGuid); if (client == null) { return new DtoApiBoolResponse() { Value = false } } ; new ServiceGroup().DeleteMembership(client.Id, -2); return(new DtoApiBoolResponse() { Value = true }); }
public DtoApiBoolResponse RemoveDownloadConnection(DtoDownloadConRequest conRequest) { var client = new ServiceComputer().GetByGuid(conRequest.ComputerGuid); if (client == null) { return new DtoApiBoolResponse() { Value = false } } ; var result = new ServiceCurrentDownload().DeleteByClientId(client.Id, conRequest.ComServer); return(new DtoApiBoolResponse() { Value = result }); } }
public DtoActionResult Approve(int id) { var result = _approvalRequestService.ApproveRequest(id); if (result.Success) { var computer = new ServiceComputer().GetComputer(id); if (computer == null) { return(result); } var auditLog = new EntityAuditLog(); auditLog.ObjectType = "ApprovalRequest"; auditLog.ObjectId = result.Id; auditLog.ObjectName = computer.Name; auditLog.ObjectJson = JsonConvert.SerializeObject(computer); auditLog.UserId = _userId; auditLog.AuditType = EnumAuditEntry.AuditType.ApproveProvision; _auditLogService.AddAuditLog(auditLog); } return(result); }
private void AutoArchiveComputers() { Logger.Debug("Computer Archive Started"); var serviceComputer = new ServiceComputer(); var archiveDays = ServiceSetting.GetSettingValue(SettingStrings.ComputerAutoArchiveDays); int intArchiveDays; if (!int.TryParse(archiveDays, out intArchiveDays)) { return; } if (intArchiveDays <= 0) { return; } Logger.Debug($"Archiving Computers Older Than {intArchiveDays} Days"); var activeComputers = _uow.ComputerRepository.Get(x => x.ProvisionStatus == EnumProvisionStatus.Status.Provisioned); if (activeComputers.Count == 0) { return; } var dateCutOff = DateTime.Now - TimeSpan.FromDays(intArchiveDays); foreach (var computer in activeComputers) { if (computer.LastCheckinTime <= dateCutOff && computer.LastCheckinTime > _localCutoff) { serviceComputer.ArchiveComputer(computer.Id); } } }
private async Task <bool> isValidRequest(string computerGuid, string deviceCert) { var computerEntity = new ServiceComputer().GetByGuid(computerGuid); if (computerEntity == null) { Logger.Debug($"ID: {logId} - Computer with identifier {computerGuid} was not found"); return(false); } var computerCert = new ServiceCertificate().GetCertX509Public(computerEntity.CertificateId); if (computerCert == null) { Logger.Debug($"ID: {logId} - Computer device certificate was null"); return(false); } var authorizationCert = new X509Certificate2(Convert.FromBase64String(deviceCert)); if (!computerCert.Equals(authorizationCert)) { Logger.Debug($"ID: {logId} - Certificate mismatch b/w what was sent and current device certificate"); return(false); } if (new ServiceCertificate().ValidateCert(authorizationCert)) { return(true); } else { Logger.Debug($"ID: {logId} - Certificate failed validation"); return(false); } }
private void Wakeup(IEnumerable <EntityComputer> computers) { var relayTasks = GenerateWakeupTask(computers); var intercomKey = ServiceSetting.GetSettingValue(SettingStrings.IntercomKeyEncrypted); var decryptedKey = new EncryptionServices().DecryptText(intercomKey); var checkinInterval = ServiceSetting.GetSettingValue(SettingStrings.CheckinInterval); var dateCutoff = DateTime.Now - TimeSpan.FromMinutes(Convert.ToInt32(checkinInterval)); foreach (var relayTask in relayTasks) { if (relayTask.Macs.Count == 0) { continue; } var destinationRelay = _uow.WolRelayRepository.GetFirstOrDefault(x => x.Gateway.Equals(relayTask.Gateway)); if (destinationRelay == null) { Logger.Debug("No WOL Relays Defined For Gateway: " + relayTask.Gateway + " Looking For Available Computers To Serve As Relay"); //find up to 10 computers on that network that have checked in recently var potentialRelays = _uow.ComputerRepository.GetPotentialWOLRelays(relayTask.Gateway, dateCutoff); if (potentialRelays == null) { Logger.Debug("No Computers Were Found To Act As A Relay For: " + relayTask.Gateway + " Skipping Computers For This Network"); continue; } if (potentialRelays.Count == 0) { Logger.Debug("No Computers Were Found To Act As A Relay For: " + relayTask.Gateway + " Skipping Computers For This Network"); continue; } var listActiveComputers = new List <EntityComputer>(); foreach (var computer in potentialRelays) { var isPoweredOn = new ServiceComputer().GetStatus(computer.Id); if (isPoweredOn) { listActiveComputers.Add(computer); } } if (listActiveComputers.Count == 0) { Logger.Debug("No Computers Were Found To Act As A Relay For: " + relayTask.Gateway + " Skipping Computers For This Network"); continue; } //send the woltask to two computers int counter = 0; foreach (var computer in listActiveComputers) { counter++; if (counter == 3) { break; } if (computer.CertificateId == -1) { continue; } if (string.IsNullOrEmpty(computer.PushUrl)) { continue; } var deviceCertEntity = _uow.CertificateRepository.GetById(computer.CertificateId); var deviceCert = new X509Certificate2(deviceCertEntity.PfxBlob, new EncryptionServices().DecryptText(deviceCertEntity.Password), X509KeyStorageFlags.Exportable); new APICall().ClientApi.SendWolTask(computer.PushUrl, deviceCert, relayTask); } } else { //send relay task to destination relay var comServer = _uow.ClientComServerRepository.GetById(destinationRelay.ComServerId); new APICall().ClientComServerApi.WakeupComputers(comServer.Url, "", decryptedKey, relayTask); } } }
protected override System.Threading.Tasks.Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { logId = logId = Guid.NewGuid().ToString("n").Substring(0, 8); // CATCH THE REQUEST BEFORE SENDING TO THE ROUTING HANDLER Logger.Debug($"ID: {logId} - Received decryption request for {request.Headers.GetValues("client").FirstOrDefault()} "); Logger.Debug($"ID: {logId} - Request URI {request.RequestUri} "); var clientIdentifier = request.Headers.GetValues("identifier").FirstOrDefault(); var encryptedCert = request.Headers.GetValues("device_cert").FirstOrDefault(); byte[] keyBytes = null; var computerEntity = new ServiceComputer().GetByGuid(clientIdentifier); if (computerEntity == null) { Logger.Debug($"ID: {logId} - Computer With Identity {clientIdentifier} Could Not Be Found."); } else { var symmKey = new EncryptionServices().DecryptText(computerEntity.SymmKeyEncrypted); keyBytes = Convert.FromBase64String(symmKey); var body = request.Content.ReadAsByteArrayAsync().Result; if (body != null) { if (body.Length != 0) { var decryptedContent = new ServiceSymmetricEncryption().DecryptAsync(keyBytes, body); if (decryptedContent.Status != TaskStatus.Faulted) { Logger.Debug($"ID: {logId} - Successfully decrypted message body"); request.Content = new StringContent(decryptedContent.Result, Encoding.UTF8, "application/json"); Logger.Debug($"ID: {logId} - Message content: " + decryptedContent.Result); } else { Logger.Debug($"ID: {logId} - Could not decrypt message body"); } } } var decryptedCert = new ServiceSymmetricEncryption().DecryptAsync(keyBytes, Convert.FromBase64String(encryptedCert)); request.Headers.Remove("device_cert"); if (decryptedCert.Status != TaskStatus.Faulted) { request.Headers.Add("device_cert", decryptedCert.Result); Logger.Debug($"ID: {logId} - Successfully decrypted device certificate"); Logger.Debug($"ID: {logId} - Checking certificate authorization"); } else { Logger.Debug($"ID: {logId} - Could not decrypt device certificate"); } } // SETUP A CALLBACK FOR CATCHING THE RESPONSE - AFTER ROUTING HANDLER, AND AFTER CONTROLLER ACTIVITY return(base.SendAsync(request, cancellationToken).ContinueWith( task => { // RETURN THE ORIGINAL RESULT var response = task.Result; //Don't encrypt body if trying to download file if (!request.RequestUri.ToString().EndsWith("GetFile/")) { var body = ResponseHandler(task, keyBytes, computerEntity); if (body != null) { response.Content = body; } } return response; }, cancellationToken)); }
public DtoProxyReservation GetProxyReservation(string mac) { var bootClientReservation = new DtoProxyReservation(); var computer = _uow.ComputerRepository.Get(x => x.ImagingMac.ToUpper().Equals(mac.ToUpper())).FirstOrDefault(); if (computer == null) { bootClientReservation.BootFile = "NotFound"; return(bootClientReservation); } var computerGroupMemberships = new ServiceComputer().GetAllGroupMemberships(computer.Id); var computerGroups = _uow.ComputerRepository.GetAllComputerGroups(computer.Id).OrderBy(x => x.ImagingPriority).ThenBy(x => x.Name).ToList(); if (computerGroups.Count == 0) { bootClientReservation.BootFile = "NotEnabled"; return(bootClientReservation); } var bootFile = ""; foreach (var group in computerGroups) { if (!string.IsNullOrEmpty(group.ProxyBootloader)) { bootFile = group.ProxyBootloader; break; } } if (string.IsNullOrEmpty(bootFile)) { bootClientReservation.BootFile = "NotEnabled"; return(bootClientReservation); } var comServers = new Workflows.GetCompTftpServers().Run(computer.Id); foreach (var com in comServers) { bootClientReservation.NextServer = com.TftpInterfaceIp; } switch (bootFile) { case "bios_pxelinux": bootClientReservation.BootFile = @"proxy/bios/pxelinux.0"; break; case "bios_ipxe": bootClientReservation.BootFile = @"proxy/bios/undionly.kpxe"; break; case "bios_x86_winpe": bootClientReservation.BootFile = @"proxy/bios/pxeboot.n12"; bootClientReservation.BcdFile = @"/boot/BCDx86"; break; case "bios_x64_winpe": bootClientReservation.BootFile = @"proxy/bios/pxeboot.n12"; bootClientReservation.BcdFile = @"/boot/BCDx64"; break; case "efi_x86_syslinux": bootClientReservation.BootFile = @"proxy/efi32/syslinux.efi"; break; case "efi_x86_ipxe": bootClientReservation.BootFile = @"proxy/efi32/ipxe.efi"; break; case "efi_x86_winpe": bootClientReservation.BootFile = @"proxy/efi32/bootmgfw.efi"; bootClientReservation.BcdFile = @"/boot/BCDx86"; break; case "efi_x64_syslinux": bootClientReservation.BootFile = @"proxy/efi64/syslinux.efi"; break; case "efi_x64_ipxe": bootClientReservation.BootFile = @"proxy/efi64/ipxe.efi"; break; case "efi_x64_winpe": bootClientReservation.BootFile = @"proxy/efi64/bootmgfw.efi"; bootClientReservation.BcdFile = @"/boot/BCDx64"; break; case "efi_x64_grub": bootClientReservation.BootFile = @"proxy/efi64/bootx64.efi"; break; } return(bootClientReservation); }
public string Execute(string multicastPort = "") { var preScripts = "\""; var beforeFileScripts = "\""; var afterFileScripts = "\""; foreach (var script in _imageProfileServices.GetImageProfileScripts(_imageProfile.Id)) { if (script.RunWhen == EnumProfileScript.RunWhen.BeforeImaging) { preScripts += script.ScriptModuleId + " "; } else if (script.RunWhen == EnumProfileScript.RunWhen.BeforeFileCopy) { beforeFileScripts += script.ScriptModuleId + " "; } else if (script.RunWhen == EnumProfileScript.RunWhen.AfterFileCopy) { afterFileScripts += script.ScriptModuleId + " "; } } beforeFileScripts += "\""; afterFileScripts += "\""; preScripts += "\""; var sysprepTags = "\""; foreach (var sysprepTag in _imageProfileServices.GetImageProfileSysprep(_imageProfile.Id)) { sysprepTags += sysprepTag.SysprepModuleId + " "; } sysprepTags = sysprepTags.Trim(); sysprepTags += "\""; var areFilesToCopy = _imageProfileServices.GetImageProfileFileCopy(_imageProfile.Id).Any(); //On demand computer may be null if not registered if (_computer != null) { AppendString("computer_name=" + _computer.Name.Split(':').First()); //AppendString("computer_id=" + _computer.Id); } AppendString("image_name=" + _imageProfile.Image.Name); AppendString("profile_id=" + _imageProfile.Id); AppendString("pre_scripts=" + preScripts); AppendString("before_file_scripts=" + beforeFileScripts); AppendString("after_file_scripts=" + afterFileScripts); AppendString("file_copy=" + areFilesToCopy); AppendString("sysprep_tags=" + sysprepTags); if (Convert.ToBoolean(_imageProfile.WebCancel)) { AppendString("web_cancel=true"); } AppendString("task_completed_action=" + "\"" + _imageProfile.TaskCompletedAction + "\""); if (ServiceSetting.GetSettingValue(SettingStrings.ImageDirectSmb).Equals("True")) { AppendString("direct_smb=true"); } if (_direction.Contains("upload")) { AppendString("image_type=" + _imageProfile.Image.Type); if (Convert.ToBoolean(_imageProfile.RemoveGPT)) { AppendString("remove_gpt_structures=true"); } if (Convert.ToBoolean(_imageProfile.SkipShrinkVolumes)) { AppendString("skip_shrink_volumes=true"); } if (Convert.ToBoolean(_imageProfile.SkipShrinkLvm)) { AppendString("skip_shrink_lvm=true"); } AppendString("compression_algorithm=" + _imageProfile.Compression); AppendString("compression_level=-" + _imageProfile.CompressionLevel); if (Convert.ToBoolean(_imageProfile.UploadSchemaOnly)) { AppendString("upload_schema_only=true"); } if (Convert.ToBoolean(_imageProfile.SimpleUploadSchema)) { AppendString("simple_upload_schema=true"); } if (!string.IsNullOrEmpty(_imageProfile.CustomUploadSchema)) { AppendString("custom_upload_schema=true"); SetCustomSchemaUpload(); } if (Convert.ToBoolean(_imageProfile.SkipBitlockerCheck)) { AppendString("skip_bitlocker_check=true"); } if (Convert.ToBoolean(_imageProfile.SkipHibernationCheck)) { AppendString("skip_hibernation_check=true"); } } else // push or multicast { //check for null in case of on demand if (_computer != null) { var computerAttributes = new ServiceComputer().GetCustomAttributes(_computer.Id); var serviceAttribute = new ServiceCustomAttribute(); foreach (var attribute in computerAttributes) { var compAttrib = serviceAttribute.GetCustomAttribute(attribute.CustomAttributeId); if (!string.IsNullOrEmpty(attribute.Value)) { if (compAttrib.ClientImagingAvailable) { AppendString(compAttrib.Name + "=" + "\"" + attribute.Value + "\""); } } } } if (Convert.ToBoolean(_imageProfile.ChangeName)) { AppendString("change_computer_name=true"); } if (Convert.ToBoolean(_imageProfile.SkipExpandVolumes)) { AppendString("skip_expand_volumes=true"); } if (Convert.ToBoolean(_imageProfile.FixBcd)) { AppendString("fix_bcd=true"); } if (Convert.ToBoolean(_imageProfile.RandomizeGuids)) { AppendString("randomize_guids=true"); } if (Convert.ToBoolean(_imageProfile.ForceStandardLegacy)) { AppendString("force_legacy_layout=true"); } if (Convert.ToBoolean(_imageProfile.ForceStandardEfi)) { AppendString("force_efi_layout=true"); } if (Convert.ToBoolean(_imageProfile.SkipNvramUpdate)) { AppendString("skip_nvram=true"); } if (Convert.ToBoolean(_imageProfile.FixBootloader)) { AppendString("fix_bootloader=true"); } if (Convert.ToBoolean(_imageProfile.ForceDynamicPartitions)) { AppendString("force_dynamic_partitions=true"); } AppendString(SetPartitionMethod()); if (!string.IsNullOrEmpty(_imageProfile.CustomSchema)) { AppendString("custom_deploy_schema=true"); SetCustomSchemaDeploy(); } if (_direction.Contains("multicast")) { var comServer = new ServiceClientComServer().GetServer(_comServerId); if (comServer.DecompressImageOn == "client") { AppendString("decompress_multicast_on_client=true"); } if (string.IsNullOrEmpty(_imageProfile.ReceiverArguments)) { AppendString("client_receiver_args=" + "\"" + comServer.MulticastReceiverArguments + "\""); } else { AppendString("client_receiver_args=" + "\"" + _imageProfile.ReceiverArguments + "\""); } AppendString("multicast_port=" + multicastPort); AppendString("multicast_server_ip=" + comServer.MulticastInterfaceIp); } } return(_activeTaskArguments.ToString()); }
public DtoProvisionResponse ProvisionClient(DtoProvisionRequest request) { Logger.Debug($"Received Provision Request For {request.Name}"); var provisionResponse = new DtoProvisionResponse(); var computerService = new ServiceComputer(); var currentIp = IpServices.GetIPAddress(); //Check if any computers with this installation id already exist Logger.Debug($"Installation ID: {request.InstallationId}"); var existingComputer = computerService.GetByInstallationId(request.InstallationId); if (existingComputer != null) { Logger.Debug($"A Computer With This Installation Id Already Exists: {request.InstallationId}"); var originalName = existingComputer.Name; Logger.Debug($"Existing Name {originalName} Request Name {request.Name}"); existingComputer.Name = request.Name; existingComputer.Guid = Guid.NewGuid().ToString(); existingComputer.AdGuid = request.AdGuid; existingComputer.ProvisionedTime = DateTime.Now; existingComputer.InstallationId = request.InstallationId; existingComputer.LastIp = currentIp; //even though id is a match, an existing computer may be using the request name var doesExist = computerService.GetByName(request.Name); if (doesExist != null) { if (doesExist.Id != existingComputer.Id) { //id's don't match, a different computer with this name already exists //Check if we should reset matching installation id's. Should not be used unless computers have the same install id, due to improper imaging var forceInstallIdReset = ConfigurationManager.AppSettings["ForceInstallationIdReset"]; if (forceInstallIdReset.ToLower().Equals("true")) { Logger.Debug("Installation ID Reset Has Been Enforced From Web.config"); return(new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.FullReset }); } if (existingComputer.ProvisionStatus == EnumProvisionStatus.Status.Reset) { Logger.Debug("Reset Approved. Archiving Existing Computer And Changing Name Of This Request."); var result = new ServiceComputer().ArchiveComputerKeepGroups(doesExist.Id); } else if (doesExist.ProvisionStatus == EnumProvisionStatus.Status.Provisioned) { var requireResetRequests = ServiceSetting.GetSettingValue(SettingStrings.RequireResetRequests); if (requireResetRequests == "1") { //computer has not yet been reset and reset approval is required, return pending reset Logger.Debug($"Computer Has Not Had Reset Approved {originalName}"); var resetRequest = new EntityResetRequest(); resetRequest.ComputerName = originalName; resetRequest.InstallationId = request.InstallationId; resetRequest.IpAddress = currentIp; var requestResult = new ServiceResetRequest().CreateRequest(resetRequest); if (!requestResult.Success) { provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; } provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.PendingReset; return(provisionResponse); } else { Logger.Debug("Reset Approvals Are Not Required, Archiving Existing Computer."); var result = new ServiceComputer().ArchiveComputerKeepGroups(doesExist.Id); } } else if (doesExist.ProvisionStatus == EnumProvisionStatus.Status.PreProvisioned) { Logger.Debug("Restoring Computer With This ID, Removing The Existing Not Provisioned Computer With This Name"); //current id matches computer, but a new computer has preprovisioned with this name, allow provison to occur //delete the doesExist entity, allowing the archived computer to be restored var result = new ServiceComputer().DeleteComputer(doesExist.Id); //requires a new instance or delete will fail Logger.Debug("Remove Existing Result: " + JsonConvert.SerializeObject(result)); } else if (doesExist.ProvisionStatus == EnumProvisionStatus.Status.ProvisionApproved || doesExist.ProvisionStatus == EnumProvisionStatus.Status.Reset) { Logger.Debug("Restoring Computer With This ID, Archiving The Existing Not Provisioned Computer With This Name"); //current id matches computer, but a new computer has preprovisioned with this name, allow provison to occur //delete the doesExist entity, allowing the archived computer to be restored var result = new ServiceComputer().ArchiveComputerKeepGroups(doesExist.Id); //requires a new instance or delete will fail Logger.Debug("Archive Existing Result: " + JsonConvert.SerializeObject(result)); } } } var cert = GenerateDeviceCert(request.SymmKey, existingComputer); Logger.Debug($"Provisioning Computer {request.Name}"); var addResult = computerService.UpdateComputer(existingComputer); if (!addResult.Success) { new ServiceCertificate().DeleteCertificate(existingComputer.CertificateId); provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; return(provisionResponse); } provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.PendingConfirmation; provisionResponse.Certificate = Convert.ToBase64String(cert); provisionResponse.ComputerIdentifier = existingComputer.Guid; return(provisionResponse); } var computerEntity = new EntityComputer(); computerEntity.LastIp = currentIp; //By this point we know it's a new installation id, continue on with other checks //Check if this computer name is already in use var nameExistsEntity = computerService.GetByName(request.Name); if (nameExistsEntity != null) { Logger.Debug($"A Computer With This Name Exists, Continuing Checks {request.Name}"); var tmpEntity = JsonConvert.SerializeObject(nameExistsEntity); //done this way to release the entity and not make changes on updates computerEntity = JsonConvert.DeserializeObject <EntityComputer>(tmpEntity); //if the computer is not approved or preprovisioned check if reset request is required if (nameExistsEntity.ProvisionStatus != EnumProvisionStatus.Status.PreProvisioned && nameExistsEntity.ProvisionStatus != EnumProvisionStatus.Status.ProvisionApproved && nameExistsEntity.ProvisionStatus != EnumProvisionStatus.Status.Reset) { var requireResetRequests = ServiceSetting.GetSettingValue(SettingStrings.RequireResetRequests); if (requireResetRequests == "1") { //computer has not yet been reset and reset approval is required, return pending reset Logger.Debug($"Computer Has Not Had Reset Approved {request.Name}"); var resetRequest = new EntityResetRequest(); resetRequest.ComputerName = request.Name; resetRequest.InstallationId = request.InstallationId; resetRequest.IpAddress = currentIp; var requestResult = new ServiceResetRequest().CreateRequest(resetRequest); if (!requestResult.Success) { provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; } provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.PendingReset; return(provisionResponse); } else { //computer has not yet been reset and no approval is required, start the reset process Logger.Debug($"Reset Approval Not Required. Starting Reset Process. {request.Name}"); computerEntity.ProvisionStatus = EnumProvisionStatus.Status.Reset; var updateResult = computerService.UpdateComputer(computerEntity); if (!updateResult.Success) { provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; } new ServiceCertificate().DeleteCertificate(computerEntity.CertificateId); provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Reset; return(provisionResponse); } } } //Check if new provisions require pre provisioning and / or approvals var preProvisionRequired = ServiceSetting.GetSettingValue(SettingStrings.RequirePreProvision); var provisionApprovalRequired = ServiceSetting.GetSettingValue(SettingStrings.RequireProvisionApproval); var preProvisionApprovalRequired = ServiceSetting.GetSettingValue(SettingStrings.PreProvisionRequiresApproval); if (preProvisionRequired == "1") { Logger.Debug($"Pre-Provision Is Required {request.Name}"); if (computerEntity.ProvisionStatus != EnumProvisionStatus.Status.Reset && computerEntity.ProvisionStatus != EnumProvisionStatus.Status.PreProvisioned && computerEntity.ProvisionStatus != EnumProvisionStatus.Status.ProvisionApproved) { Logger.Debug($"Setting Status To Pending Pre-Provision {request.Name}"); provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.PendingPreProvision; return(provisionResponse); } else { Logger.Debug($"PreProvision Check Passed {request.Name}"); } if (preProvisionApprovalRequired == "1" && computerEntity.ProvisionStatus == EnumProvisionStatus.Status.PreProvisioned) { Logger.Debug($"PreProvision Check Passed. PreProvision Approval Is Required. Setting Status To Pending Provision Approval {request.Name}"); //submit provision approval request var approvalRequest = new EntityApprovalRequest(); approvalRequest.ComputerName = request.Name; approvalRequest.InstallationId = request.InstallationId; approvalRequest.IpAddress = currentIp; var requestResult = new ServiceApprovalRequest().CreateRequest(approvalRequest); if (!requestResult.Success) { provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; } provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.PendingProvisionApproval; return(provisionResponse); } } else if (provisionApprovalRequired == "1" && computerEntity.ProvisionStatus != EnumProvisionStatus.Status.ProvisionApproved) { Logger.Debug($"Provision Approval Is Required. Setting Status To Pending Provision Approval {request.Name}"); //submit provision approval request var approvalRequest = new EntityApprovalRequest(); approvalRequest.ComputerName = request.Name; approvalRequest.InstallationId = request.InstallationId; approvalRequest.IpAddress = currentIp; var requestResult = new ServiceApprovalRequest().CreateRequest(approvalRequest); if (!requestResult.Success) { provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; } provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.PendingProvisionApproval; return(provisionResponse); } //all pre checks complete and successful, move forward with provision //Provisioning computer computerEntity.Name = request.Name; computerEntity.Guid = Guid.NewGuid().ToString(); computerEntity.AdGuid = request.AdGuid; computerEntity.ProvisionedTime = DateTime.Now; computerEntity.InstallationId = request.InstallationId; computerEntity.LastIp = currentIp; byte[] encryptedCert; string computerIdentifier; if (computerEntity.Id == 0) // this will never be true when preprovision is required { //this computer does not at exist at all, add it Logger.Debug($"Computer Is New, Provisioning Computer {request.Name}"); encryptedCert = GenerateDeviceCert(request.SymmKey, computerEntity); var addResult = computerService.AddComputer(computerEntity); computerIdentifier = computerEntity.Guid; if (!addResult.Success) { new ServiceCertificate().DeleteCertificate(computerEntity.CertificateId); provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; return(provisionResponse); } } else { //computer exists in some way //overwriting an existing computer, should we overwrite or archive and create a new one //if serial number, memory, processor name, and computer model are the same, assume it's the same computer Logger.Debug($"Checking If Computer With Matching Hardware Info Already Exists {request.Name}"); var existingHardware = computerService.GetProvisionHardware(computerEntity.Id); var macsVerified = true; if (existingHardware != null) { foreach (var requestMac in request.Macs) { Logger.Debug(requestMac); if (!existingHardware.Macs.Contains(requestMac)) { macsVerified = false; break; } } } Logger.Debug("Macs Verified: " + macsVerified); Logger.Debug("Existing Hardware: " + JsonConvert.SerializeObject(existingHardware)); Logger.Debug("Request Hardware: " + JsonConvert.SerializeObject(request)); if (existingHardware != null) { if (existingHardware.Memory == request.Memory && existingHardware.Model.Equals(request.Model) && existingHardware.Processor.Equals(request.Processor) && existingHardware.SerialNumber.Equals(request.SerialNumber) && macsVerified) { Logger.Debug($"Hardware Match Found, Linking To Existing Computer {request.Name}"); //same computer, update it encryptedCert = GenerateDeviceCert(request.SymmKey, computerEntity); var updateResult = computerService.UpdateComputer(computerEntity); computerIdentifier = computerEntity.Guid; if (!updateResult.Success) { provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; return(provisionResponse); } } else { //different computer, archive and add new Logger.Debug($"No Hardware Match Found, Archiving Existing Computer{request.Name}"); var newComputer = new EntityComputer(); newComputer.Name = computerEntity.Name; newComputer.Guid = Guid.NewGuid().ToString(); newComputer.AdGuid = computerEntity.AdGuid; newComputer.ProvisionedTime = computerEntity.ProvisionedTime; newComputer.InstallationId = computerEntity.InstallationId; newComputer.LastIp = computerEntity.LastIp; encryptedCert = GenerateDeviceCert(request.SymmKey, newComputer); Logger.Debug("Archiving Computer"); new ServiceComputer().ArchiveComputerKeepGroups(computerEntity.Id); Logger.Debug("Adding New Computer"); var addResult = computerService.AddComputer(newComputer); computerIdentifier = newComputer.Guid; if (!addResult.Success) { new ServiceCertificate().DeleteCertificate(newComputer.CertificateId); provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; return(provisionResponse); } } } else { //cannot determine if it's the same computer, when provisioning a new computer with preprovsion or provisional approval required, we should end up here Logger.Debug($"Could Not Determine Hardware Match {request.Name}"); if (computerEntity.ProvisionStatus == EnumProvisionStatus.Status.PreProvisioned || computerEntity.ProvisionStatus == EnumProvisionStatus.Status.ProvisionApproved) { Logger.Debug($"Computer Is PreProvisioned Or Approved. Provisioning Computer. {request.Name}"); //if status is pre-provisioned or approved, assume it's a new computer and finish provision encryptedCert = GenerateDeviceCert(request.SymmKey, computerEntity); var updateResult = computerService.UpdateComputer(computerEntity); computerIdentifier = computerEntity.Guid; if (!updateResult.Success) { provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; return(provisionResponse); } } else { //not sure why we ended up here, no choice but to archive existing and create new //must create a new entity Logger.Debug($"Archiving Existing. Provisioning Computer. {request.Name}"); var newComputer = new EntityComputer(); newComputer.Name = computerEntity.Name; newComputer.Guid = Guid.NewGuid().ToString(); newComputer.AdGuid = computerEntity.AdGuid; newComputer.ProvisionedTime = computerEntity.ProvisionedTime; newComputer.InstallationId = computerEntity.InstallationId; newComputer.LastIp = computerEntity.LastIp; encryptedCert = GenerateDeviceCert(request.SymmKey, newComputer); new ServiceComputer().ArchiveComputerKeepGroups(computerEntity.Id); var addResult = computerService.AddComputer(newComputer); computerIdentifier = newComputer.Guid; if (!addResult.Success) { new ServiceCertificate().DeleteCertificate(newComputer.CertificateId); provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.Error; return(provisionResponse); } } } } provisionResponse.ProvisionStatus = EnumProvisionStatus.Status.PendingConfirmation; provisionResponse.Certificate = Convert.ToBase64String(encryptedCert); provisionResponse.ComputerIdentifier = computerIdentifier; return(provisionResponse); }
public List <EntityClientComServer> Run(int computerId) { var uow = new UnitOfWork(); var defaultCluster = uow.ComServerClusterRepository.GetFirstOrDefault(x => x.IsDefault); var computerGroupMemberships = new ServiceComputer().GetAllGroupMemberships(computerId); var computerGroups = uow.ComputerRepository.GetAllComputerGroups(computerId).OrderBy(x => x.ImagingPriority).ThenBy(x => x.Name).ToList(); List <int> tftpServerIds = new List <int>(); if (computerGroups.Count() == 0) { //use default var clusterTftpServers = uow.ComServerClusterServerRepository.GetTftpClusterServers(defaultCluster.Id); if (clusterTftpServers != null) { if (clusterTftpServers.Count > 0) { tftpServerIds = clusterTftpServers.Select(x => x.ComServerId).ToList(); } else { return(null); //default cluster has no tftp servers } } } else { foreach (var group in computerGroups) { //check if assigned cluster has any tftp servers, if not, go to next group if (group.ClusterId == -1) { group.ClusterId = defaultCluster.Id; } var clusterTftpServers = uow.ComServerClusterServerRepository.GetTftpClusterServers(group.ClusterId); if (clusterTftpServers != null) { if (clusterTftpServers.Count > 0) { tftpServerIds = clusterTftpServers.Select(x => x.ComServerId).ToList(); break; } } } if (tftpServerIds.Count == 0) { //no groups with a tftp server found for this computer, use default cluster //use default var clusterTftpServers = uow.ComServerClusterServerRepository.GetTftpClusterServers(defaultCluster.Id); if (clusterTftpServers != null) { if (clusterTftpServers.Count > 0) { tftpServerIds = clusterTftpServers.Select(x => x.ComServerId).ToList(); } else { return(null); //default cluster has no tftp servers } } } } var listComServers = new List <EntityClientComServer>(); foreach (var comServerId in tftpServerIds) { var comServer = uow.ClientComServerRepository.GetById(comServerId); listComServers.Add(comServer); } return(listComServers); }
public DtoProvisionResponse RenewSymmKey(DtoRenewKeyRequest request) { var response = new DtoProvisionResponse(); var computerService = new ServiceComputer(); var computer = computerService.GetByGuid(request.Guid); if (computer == null) { return new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Error } } ; if (computer.ProvisionStatus == EnumProvisionStatus.Status.Reset) { return new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Reset } } ; computer.ProvisionStatus = EnumProvisionStatus.Status.Provisioned; computer.SymmKeyEncrypted = new EncryptionServices().EncryptText(request.SymmKey); //computer may have been renamed, update the name var originalName = computer.Name; request.Name = request.Name.ToUpper(); if (!request.Name.Equals(computer.Name)) { computer.Name = request.Name; Logger.Debug("SymmKey Update Requires Computer Name Update"); Logger.Debug("Old Name: " + originalName); Logger.Debug("New Name: " + request.Name); var doesExist = computerService.GetByName(request.Name); //a computer already exists with this name, what next if (doesExist != null) { if (doesExist.ProvisionStatus == EnumProvisionStatus.Status.Provisioned) { Logger.Debug("An Active Computer With This Name Already Exists. Cannot Renew SymmKey"); return(new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Error }); } else if (doesExist.ProvisionStatus == EnumProvisionStatus.Status.PreProvisioned) { Logger.Debug("Updating Name, Removing PreProvisioned Computer"); //new computer has preprovisioned with this name, allow provison to occur //delete the doesExist entity, allowing the archived computer to be restored new ServiceComputer().DeleteComputer(doesExist.Id); //requires a new instance or delete will fail } else if (doesExist.ProvisionStatus == EnumProvisionStatus.Status.ProvisionApproved || doesExist.ProvisionStatus == EnumProvisionStatus.Status.Reset) { Logger.Debug("Updating Name, Archiving Existing Computer"); //new computer has preprovisioned with this name, allow provison to occur //delete the doesExist entity, allowing the archived computer to be restored new ServiceComputer().ArchiveComputerKeepGroups(doesExist.Id); //requires a new instance or delete will fail } else { return(new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Error }); } } } var result = computerService.UpdateComputer(computer); if (result == null) { Logger.Debug("Could Not Renew SymmKey. Computer Name May Have Been Updated With An Existing Computer"); return(new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Error }); } if (!result.Success) { Logger.Debug("Could Not Renew SymmKey. Computer Name May Have Been Updated With An Existing Computer"); return(new DtoProvisionResponse() { ProvisionStatus = EnumProvisionStatus.Status.Error }); } var clientComServers = new GetClientComServers().Run(request.Guid); if (clientComServers != null) { response.ComServers = clientComServers; } response.ProvisionStatus = EnumProvisionStatus.Status.Provisioned; return(response); } } }
public DtoDownloadConnectionResult CreateDownloadConnection(DtoDownloadConRequest conRequest) { var result = new DtoDownloadConnectionResult(); var guid = ConfigurationManager.AppSettings["ComServerUniqueId"]; var thisComServer = new ServiceClientComServer().GetServerByGuid(guid); if (thisComServer == null) { Logger.Error($"Com Server With Guid {guid} Not Found"); result.ErrorMessage = $"Com Server With Guid {guid} Not Found"; return(result); } if (!int.TryParse(thisComServer.EmMaxClients.ToString(), out var maxClientConnections)) { result.ErrorMessage = "Could Not Determine The MaxClientConnections For The Com Server: " + conRequest.ComServer; return(result); } if (maxClientConnections == 0) // zero is unlimited { result.Success = true; result.QueueIsFull = false; return(result); } var client = new ServiceComputer().GetByGuid(conRequest.ComputerGuid); if (client == null) { result.ErrorMessage = "Could Not Find Computer With Guid: " + RequestContext.Principal.Identity.Name; return(result); } var serviceCurrentDownloads = new ServiceCurrentDownload(); var currentConnections = serviceCurrentDownloads.TotalCount(conRequest.ComServer); var activeClient = serviceCurrentDownloads.GetByClientId(client.Id, conRequest.ComServer); if (activeClient == null && (currentConnections >= maxClientConnections)) { var activeCountAfterExpire = serviceCurrentDownloads.ExpireOldConnections(); if (activeCountAfterExpire >= maxClientConnections) { result.Success = true; result.QueueIsFull = true; return(result); } } //add new download connection for this client if (activeClient == null) { var currentDownload = new EntityCurrentDownload(); currentDownload.ComputerId = client.Id; currentDownload.ComServer = conRequest.ComServer; serviceCurrentDownloads.Add(currentDownload); result.Success = true; result.QueueIsFull = false; } //update time for existing download connection else { activeClient.LastRequestTimeLocal = DateTime.Now; serviceCurrentDownloads.Update(activeClient); result.Success = true; result.QueueIsFull = false; } return(result); }
public bool Execute(EntityComputer computer) { _computer = computer; _listOfMacs = new List <string>(); if (!string.IsNullOrEmpty(_computer.ImagingMac)) { _listOfMacs.Add(StringManipulationServices.MacToPxeMac(_computer.ImagingMac)); } else { var computerMacs = new UnitOfWork().NicInventoryRepository.Get(x => x.ComputerId == computer.Id && x.Type.Equals("Ethernet")).Select(x => x.Mac).ToList(); foreach (var mac in computerMacs) { _listOfMacs.Add(StringManipulationServices.MacToPxeMac(mac)); } } _computerServices = new ServiceComputer(); var guid = ConfigurationManager.AppSettings["ComServerUniqueId"]; _thisComServer = new ServiceClientComServer().GetServerByGuid(guid); if (_thisComServer == null) { Logger.Error($"Com Server With Guid {guid} Not Found"); return(false); } if (string.IsNullOrEmpty(_thisComServer.TftpPath)) { Logger.Error($"Com Server With Guid {guid} Does Not Have A Valid Tftp Path"); return(false); } if (ServiceSetting.GetSettingValue(SettingStrings.ProxyDhcpEnabled) == "Yes") { DeleteProxyFile("bios"); DeleteProxyFile("bios", ".ipxe"); DeleteProxyFile("efi32"); DeleteProxyFile("efi32", ".ipxe"); DeleteProxyFile("efi64"); DeleteProxyFile("efi64", ".ipxe"); DeleteProxyFile("efi64", ".cfg"); } else { var mode = ServiceSetting.GetSettingValue(SettingStrings.PxeBootloader); if (mode.Contains("ipxe")) { DeleteStandardFile(".ipxe"); } else if (mode.Contains("grub")) { DeleteStandardFile(".cfg"); } else { DeleteStandardFile(); } } return(true); }
public List <EntityClientComServer> Run(int computerId, bool includePassive = false) { var uow = new UnitOfWork(); var defaultCluster = uow.ComServerClusterRepository.GetFirstOrDefault(x => x.IsDefault); var computerGroupMemberships = new ServiceComputer().GetAllGroupMemberships(computerId); var computerGroups = uow.ComputerRepository.GetAllComputerGroups(computerId).OrderBy(x => x.ImagingPriority).ThenBy(x => x.Name).ToList(); List <int> imagingServerIds = new List <int>(); if (computerGroups.Count() == 0) { //use default List <DtoClientComServers> clusterImagingServers; if (includePassive) { clusterImagingServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(defaultCluster.Id); } else { clusterImagingServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(defaultCluster.Id).Where(x => x.Role.Equals("Active")).ToList(); } if (clusterImagingServers != null) { if (clusterImagingServers.Count > 0) { imagingServerIds = clusterImagingServers.Select(x => x.ComServerId).ToList(); } else { return(null); //default cluster has no imaging servers } } } else { foreach (var group in computerGroups) { //check if assigned cluster has any imaging servers, if not, go to next group if (group.ClusterId == -1) { group.ClusterId = defaultCluster.Id; } List <DtoClientComServers> clusterImagingServers; if (includePassive) { clusterImagingServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(group.ClusterId); } else { clusterImagingServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(group.ClusterId).Where(x => x.Role.Equals("Active")).ToList(); } if (clusterImagingServers != null) { if (clusterImagingServers.Count > 0) { imagingServerIds = clusterImagingServers.Select(x => x.ComServerId).ToList(); break; //use first found imaging cluster } } } if (imagingServerIds.Count == 0) { //no groups with an imaging server found for this computer, use default cluster //use default List <DtoClientComServers> clusterImagingServers; if (includePassive) { clusterImagingServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(defaultCluster.Id); } else { clusterImagingServers = uow.ComServerClusterServerRepository.GetImagingClusterServers(defaultCluster.Id).Where(x => x.Role.Equals("Active")).ToList(); } if (clusterImagingServers != null) { if (clusterImagingServers.Count > 0) { imagingServerIds = clusterImagingServers.Select(x => x.ComServerId).ToList(); } else { return(null); //default cluster has no tftp servers } } } } var listComServers = new List <EntityClientComServer>(); foreach (var comServerId in imagingServerIds) { var comServer = uow.ClientComServerRepository.GetById(comServerId); listComServers.Add(comServer); } return(listComServers); }