diff --git a/Disco.BI/BI/DeviceBI/DeviceModelBI.cs b/Disco.BI/BI/DeviceBI/DeviceModelBI.cs new file mode 100644 index 00000000..ad7d70cc --- /dev/null +++ b/Disco.BI/BI/DeviceBI/DeviceModelBI.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Disco.Data.Repository; +using Disco.Models.Repository; + +namespace Disco.BI +{ + public static class DeviceModelBI + { + + // Added: 2013-02-07 G# + // Ensure Duplicate Device Models are not created by creating only one Device Model at a time + // http://www.discoict.com.au/forum/support/2013/2/duplicate-device-models.aspx + // Thanks to Michael Vorster for reporting this problem. + private static object _CreateDeviceModelLock = new object(); + public static Tuple GetOrCreateDeviceModel(this DbSet DeviceModelsSet, string Manufacturer, string Model, string ModelType) + { + // Already Exists? + var deviceModel = DeviceModelsSet.FirstOrDefault(dm => dm.Manufacturer == Manufacturer && dm.Model == Model); + if (deviceModel == null) + { + // Ensure only one thread/request at a time + lock (_CreateDeviceModelLock) + { + // Check again now that lock is enforced + deviceModel = DeviceModelsSet.FirstOrDefault(dm => dm.Manufacturer == Manufacturer && dm.Model == Model); + + if (deviceModel == null) + { + // Create the Device Model in a different DataContext so we don't have to commit unrelated changes + using (DiscoDataContext dbContext = new DiscoDataContext()) + { + var addDeviceModel = new DeviceModel + { + Manufacturer = Manufacturer, + Model = Model, + ModelType = ModelType, + Description = string.Format("{0} {1}", Manufacturer, Model) + }; + dbContext.DeviceModels.Add(addDeviceModel); + dbContext.SaveChanges(); + } + + // Obtain the Device Model with the in-scope DataContext + // - Overhead acknowledged, but reasonable given the infrequency of occurrence + deviceModel = DeviceModelsSet.FirstOrDefault(dm => dm.Manufacturer == Manufacturer && dm.Model == Model); + return new Tuple(deviceModel, true); + } + } + } + + return new Tuple(deviceModel, false); + } + // Added: 2013-02-07 G# + + } +} diff --git a/Disco.BI/BI/DeviceBI/Enrol.cs b/Disco.BI/BI/DeviceBI/Enrol.cs index c5166870..6657f6b8 100644 --- a/Disco.BI/BI/DeviceBI/Enrol.cs +++ b/Disco.BI/BI/DeviceBI/Enrol.cs @@ -1,621 +1,580 @@ -using System; -using System.Linq; -using System.Text.RegularExpressions; -using Disco.BI.Interop.ActiveDirectory; -using Disco.BI.Extensions; -using Disco.Data.Configuration.Modules; -using Disco.Data.Repository; -using Disco.Models.ClientServices; -using Disco.Models.Interop.ActiveDirectory; -using Disco.Models.Repository; -using Tamir.SharpSsh; -using Disco.Services.Plugins; -using Disco.Services.Plugins.Features.CertificateProvider; - -namespace Disco.BI.DeviceBI -{ - public class DeviceEnrol - { - public enum EnrolmentTypes - { - Normal, - Mac = 5, - MacSecure - } - - private static Regex SshPromptRegEx = new Regex("[\\$,\\#]", RegexOptions.Multiline); - public static MacSecureEnrolResponse MacSecureEnrol(DiscoDataContext dbContext, string Host) - { - MacEnrol trustedRequest = new MacEnrol(); - string sessionId = System.Guid.NewGuid().ToString("B"); - MacSecureEnrolResponse MacSecureEnrol; - try - { - EnrolmentLog.LogSessionStarting(sessionId, Host, EnrolmentTypes.MacSecure); - EnrolmentLog.LogSessionProgress(sessionId, 0, string.Format("Connecting to '{0}' as '{1}'", Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername)); - SshShell shell = new SshShell(Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername, dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); - try - { - shell.ExpectPattern = "#"; - shell.Connect(); - EnrolmentLog.LogSessionProgress(sessionId, 10, "Connected, Authenticating"); - var output = shell.Expect(SshPromptRegEx); - bool sessionElevated = false; - EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); - if (!output.TrimEnd(new char[0]).EndsWith("#")) - { - EnrolmentLog.LogSessionProgress(sessionId, 22, "Connected, Elevating Credentials"); - shell.WriteLine("sudo -k"); - System.Threading.Thread.Sleep(250); - output = shell.Expect(SshPromptRegEx); - EnrolmentLog.LogSessionProgress(sessionId, 25, "Connected, Elevating Credentials"); - EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); - shell.WriteLine("sudo -s -S"); - System.Threading.Thread.Sleep(250); - output = shell.Expect(":"); - EnrolmentLog.LogSessionProgress(sessionId, 27, "Connected, Elevating Credentials"); - EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); - shell.WriteLine(dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); - System.Threading.Thread.Sleep(250); - output = shell.Expect(SshPromptRegEx); - sessionElevated = true; - EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); - } - EnrolmentLog.LogSessionProgress(sessionId, 20, "Retrieving Serial Number"); - trustedRequest.DeviceSerialNumber = ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Serial Number\" | cut -d \":\" -f 2-", sessionId); - EnrolmentLog.LogSessionDevice(sessionId, trustedRequest.DeviceSerialNumber, null); - EnrolmentLog.LogSessionProgress(sessionId, 30, "Retrieving Hardware UUID"); - trustedRequest.DeviceUUID = ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Hardware UUID:\" | cut -d \":\" -f 2-", sessionId); - EnrolmentLog.LogSessionProgress(sessionId, 40, "Retrieving Computer Name"); - trustedRequest.DeviceComputerName = ParseMacShellCommand(shell, "scutil --get ComputerName", sessionId); - EnrolmentLog.LogSessionProgress(sessionId, 50, "Retrieving Ethernet MAC Address"); - string lanNicId = ParseMacShellCommand(shell, "system_profiler SPEthernetDataType | egrep -o \"en0|en1|en2|en3|en4|en5|en6\"", sessionId); - if (!string.IsNullOrWhiteSpace(lanNicId)) - { - trustedRequest.DeviceLanMacAddress = ParseMacShellCommand(shell, string.Format("ifconfig {0} | grep ether | cut -d \" \" -f 2-", lanNicId), sessionId); - } - EnrolmentLog.LogSessionProgress(sessionId, 65, "Retrieving Wireless MAC Address"); - string wlanNicId = ParseMacShellCommand(shell, "system_profiler SPAirPortDataType | egrep -o \"en0|en1|en2|en3|en4|en5|en6\"", sessionId); - if (!string.IsNullOrWhiteSpace(wlanNicId)) - { - trustedRequest.DeviceWlanMacAddress = ParseMacShellCommand(shell, string.Format("ifconfig {0} | grep ether | cut -d \" \" -f 2-", wlanNicId), sessionId); - } - trustedRequest.DeviceManufacturer = "Apple Inc."; - EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Model"); - trustedRequest.DeviceModel = ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Model Identifier:\" | cut -d \":\" -f 2-", sessionId); - EnrolmentLog.LogSessionProgress(sessionId, 90, "Retrieving Model Type"); - trustedRequest.DeviceModelType = ParseMacModelType(ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Model Name:\" | cut -d \":\" -f 2-", sessionId)); - EnrolmentLog.LogSessionProgress(sessionId, 99, "Disconnecting"); - output = ParseMacModelType(ParseMacShellCommand(shell, "exit", sessionId)); - if (sessionElevated) - { - output = ParseMacModelType(ParseMacShellCommand(shell, "exit", sessionId)); - } - if (shell.Connected) - { - shell.Close(); - } - EnrolmentLog.LogSessionProgress(sessionId, 100, "Disconnected, Starting Disco Enrolment"); - MacSecureEnrolResponse response = MacSecureEnrolResponse.FromMacEnrolResponse(MacEnrol(dbContext, trustedRequest, true, sessionId)); - EnrolmentLog.LogSessionFinished(sessionId); - MacSecureEnrol = response; - } - catch (System.Exception ex) - { - throw ex; - } - finally - { - if (shell != null) - { - bool connected = shell.Connected; - if (connected) - { - shell.Close(); - } - } - } - } - catch (System.Exception ex) - { - EnrolmentLog.LogSessionError(sessionId, ex); - throw ex; - } - return MacSecureEnrol; - } - - #region "Mac Enrol Helpers" - - private static string ParseMacModelType(string ModelName) - { - string ParseMacModelType; - if (!string.IsNullOrWhiteSpace(ModelName)) - { - string mn = ModelName.ToLower(); - if (mn.Contains("imac") || mn.Contains("mini")) - { - ParseMacModelType = "Desktop"; - return ParseMacModelType; - } - if (mn.Contains("macbook")) - { - ParseMacModelType = "Mobile"; - return ParseMacModelType; - } - if (mn.Contains("xserve")) - { - ParseMacModelType = "Server"; - return ParseMacModelType; - } - } - ParseMacModelType = "Unknown"; - return ParseMacModelType; - } - - private static string ParseMacShellCommand(SshShell Shell, string Command, string LogSessionId) - { - Shell.WriteLine(Command); - System.Threading.Thread.Sleep(250); - string Response = Shell.Expect(SshPromptRegEx); - Response = Response.Replace("\r", string.Empty); - EnrolmentLog.LogSessionDiagnosticInformation(LogSessionId, Response); - bool flag = Response.Contains("\n"); - string ParseMacShellCommand; - if (flag) - { - string[] ResponseLines = Response.Split(new char[] - { - '\n' - }); - switch (ResponseLines.Length) - { - case 0: - case 1: - { - ParseMacShellCommand = string.Empty; - break; - } - case 2: - case 3: - { - ParseMacShellCommand = ResponseLines[1].Trim(); - break; - } - default: - { - System.Text.StringBuilder ResponseBuilder = new System.Text.StringBuilder(); - int num = ResponseLines.Length - 2; - int lineIndex = 1; - while (true) - { - int arg_111_0 = lineIndex; - int num2 = num; - if (arg_111_0 > num2) - { - break; - } - ResponseBuilder.AppendLine(ResponseLines[lineIndex]); - lineIndex++; - } - ParseMacShellCommand = ResponseBuilder.ToString().Trim(); - break; - } - } - } - else - { - ParseMacShellCommand = Response; - } - return ParseMacShellCommand; - } - - #endregion - - public static MacEnrolResponse MacEnrol(DiscoDataContext dbContext, MacEnrol Request, bool Trusted, string OpenSessionId = null) - { - string sessionId; - if (OpenSessionId == null) - { - sessionId = System.Guid.NewGuid().ToString("B"); - EnrolmentLog.LogSessionStarting(sessionId, Request.DeviceSerialNumber, EnrolmentTypes.Mac); - } - else - { - sessionId = OpenSessionId; - } - EnrolmentLog.LogSessionDeviceInfo(sessionId, Request); - MacEnrolResponse response = new MacEnrolResponse(); - try - { - EnrolmentLog.LogSessionProgress(sessionId, 10, "Querying Database"); - Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceProfile").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); - if (!Trusted) - { - if (RepoDevice == null) - throw new EnrolSafeException(string.Format("Unknown Device Serial Number (SN: '{0}')", Request.DeviceSerialNumber)); - if (!RepoDevice.AllowUnauthenticatedEnrol) - throw new EnrolSafeException(string.Format("Device isn't allowed an Unauthenticated Enrolment (SN: '{0}')", Request.DeviceSerialNumber)); - } - if (RepoDevice == null) - { - EnrolmentLog.LogSessionProgress(sessionId, 50, "New Device, Building Disco Instance"); - EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); - DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); - DeviceModel deviceModel = dbContext.DeviceModels.Where(dm => dm.Manufacturer == Request.DeviceManufacturer.Trim() && dm.Model == Request.DeviceModel.Trim()).FirstOrDefault(); - if (deviceModel == null) - { - deviceModel = new DeviceModel - { - Manufacturer = Request.DeviceManufacturer.Trim(), - Model = Request.DeviceModel.Trim(), - ModelType = Request.DeviceModelType.Trim(), - Description = string.Format("{0} {1}", Request.DeviceManufacturer.Trim(), Request.DeviceModel) - }; - dbContext.DeviceModels.Add(deviceModel); - EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim()); - } - else - { - EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, deviceModel.Id); - } - RepoDevice = new Device - { - SerialNumber = Request.DeviceSerialNumber, - ComputerName = Request.DeviceComputerName, - DeviceProfile = deviceProfile, - DeviceModel = deviceModel, - AllowUnauthenticatedEnrol = false, - Active = true, - CreatedDate = DateTime.Now, - EnrolledDate = DateTime.Now - }; - dbContext.Devices.Add(RepoDevice); - } - else - { - EnrolmentLog.LogSessionProgress(sessionId, 50, "Existing Device, Updating Disco Instance"); - EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); - if (!RepoDevice.DeviceModelId.HasValue || RepoDevice.DeviceModelId.Value == 1) - { - DeviceModel deviceModel = dbContext.DeviceModels.Where(dm => dm.Manufacturer == Request.DeviceManufacturer.Trim() && dm.Model == Request.DeviceModel.Trim()).FirstOrDefault(); - if (deviceModel == null) - { - deviceModel = new DeviceModel - { - Manufacturer = Request.DeviceManufacturer.Trim(), - Model = Request.DeviceModel.Trim(), - ModelType = Request.DeviceModelType.Trim(), - Description = string.Format("{0} {1}", Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim()) - }; - dbContext.DeviceModels.Add(deviceModel); - EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim()); - } - else - { - EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, deviceModel.Id); - } - RepoDevice.DeviceModel = deviceModel; - } - else - { - EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, RepoDevice.DeviceModelId); - } - RepoDevice.ComputerName = Request.DeviceComputerName; - if (!RepoDevice.EnrolledDate.HasValue) - { - RepoDevice.EnrolledDate = DateTime.Now; - } - } - RepoDevice.LastEnrolDate = DateTime.Now; - RepoDevice.AllowUnauthenticatedEnrol = false; - // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. - //DeviceProfileConfiguration RepoDeviceProfileContext = RepoDevice.DeviceProfile.Configuration(Context); - EnrolmentLog.LogSessionProgress(sessionId, 90, "Building Response"); - //if (RepoDeviceProfileContext.DistributionType == DeviceProfileConfiguration.DeviceProfileDistributionTypes.OneToOne && RepoDevice.AssignedUser != null) - if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne && RepoDevice.AssignedUser != null) - { - ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); - EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); - response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; - response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; - response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; - response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; - } - response.DeviceComputerName = RepoDevice.ComputerName; - EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully"); - } - catch (EnrolSafeException ex) - { - EnrolmentLog.LogSessionError(sessionId, ex); - return new MacEnrolResponse { ErrorMessage = ex.Message }; - } - catch (System.Exception ex2) - { - EnrolmentLog.LogSessionError(sessionId, ex2); - throw ex2; - } - finally - { - if (OpenSessionId == null) - EnrolmentLog.LogSessionFinished(sessionId); - } - return response; - } - public static EnrolResponse Enrol(DiscoDataContext dbContext, string Username, Models.ClientServices.Enrol Request) - { - ActiveDirectoryMachineAccount MachineInfo = null; - EnrolResponse response = new EnrolResponse(); - User authenticatedUser = null; - bool isAuthenticated = false; - string sessionId = System.Guid.NewGuid().ToString("B"); - response.SessionId = sessionId; - EnrolmentLog.LogSessionStarting(sessionId, Request.DeviceSerialNumber, EnrolmentTypes.Normal); - EnrolmentLog.LogSessionDeviceInfo(sessionId, Request); - try - { - EnrolmentLog.LogSessionProgress(sessionId, 10, "Loading User Data"); - if (!string.IsNullOrWhiteSpace(Username)) - { - authenticatedUser = UserBI.UserCache.GetUser(Username, dbContext); - isAuthenticated = (authenticatedUser != null); - } - EnrolmentLog.LogSessionProgress(sessionId, 13, "Loading Device Data"); - - Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceModel").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); - EnrolmentLog.LogSessionProgress(sessionId, 15, "Discovering User/Device Disco Permissions"); - if (isAuthenticated) - { - if (authenticatedUser.Type != "Admin") - { - if (authenticatedUser.Type != "Computer") - throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); - if (!authenticatedUser.Id.Equals(string.Format("{0}$", Request.DeviceComputerName), System.StringComparison.InvariantCultureIgnoreCase)) - throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); - } - } - else - { - if (RepoDevice == null) - throw new EnrolSafeException(string.Format("Unknown Device Serial Number (SN: '{0}')", Request.DeviceSerialNumber)); - if (!RepoDevice.AllowUnauthenticatedEnrol) - throw new EnrolSafeException(string.Format("Device isn't allowed an Unauthenticated Enrolment (SN: '{0}')", Request.DeviceSerialNumber)); - } - if (Request.DeviceIsPartOfDomain && !string.IsNullOrWhiteSpace(Request.DeviceComputerName)) - { - EnrolmentLog.LogSessionProgress(sessionId, 20, "Loading Active Directory Computer Account"); - System.Guid? uuidGuid = null; - System.Guid? macAddressGuid = null; - if (!string.IsNullOrEmpty(Request.DeviceUUID)) - uuidGuid = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromUUID(Request.DeviceUUID); - if (!string.IsNullOrEmpty(Request.DeviceLanMacAddress)) - macAddressGuid = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromMACAddress(Request.DeviceLanMacAddress); - MachineInfo = ActiveDirectory.GetMachineAccount(Request.DeviceComputerName, uuidGuid, macAddressGuid); - } - if (RepoDevice == null) - { - EnrolmentLog.LogSessionProgress(sessionId, 30, "New Device, Creating Disco Instance"); - EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); - DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); - DeviceModel deviceModel = dbContext.DeviceModels.Where(dm => dm.Manufacturer == Request.DeviceManufacturer.Trim() && dm.Model == Request.DeviceModel.Trim()).FirstOrDefault(); - if (deviceModel == null) - { - deviceModel = new DeviceModel - { - Manufacturer = Request.DeviceManufacturer.Trim(), - Model = Request.DeviceModel.Trim(), - ModelType = Request.DeviceModelType.Trim(), - Description = string.Format("{0} {1}", Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim()) - }; - dbContext.DeviceModels.Add(deviceModel); - EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim()); - } - else - { - EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, deviceModel.Id); - } - RepoDevice = new Device - { - SerialNumber = Request.DeviceSerialNumber, - ComputerName = Request.DeviceComputerName, - DeviceProfile = deviceProfile, - DeviceModel = deviceModel, - AllowUnauthenticatedEnrol = false, - Active = true, - CreatedDate = DateTime.Now, - EnrolledDate = DateTime.Now, - LastEnrolDate = DateTime.Now - }; - dbContext.Devices.Add(RepoDevice); - } - else - { - EnrolmentLog.LogSessionProgress(sessionId, 30, "Existing Device, Updating Disco Instance"); - EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); - - DeviceModel deviceModel = dbContext.DeviceModels.Where(dm => dm.Manufacturer == Request.DeviceManufacturer.Trim() && dm.Model == Request.DeviceModel.Trim()).FirstOrDefault(); - if (deviceModel == null) - { - deviceModel = new DeviceModel - { - Manufacturer = Request.DeviceManufacturer.Trim(), - Model = Request.DeviceModel.Trim(), - ModelType = Request.DeviceModelType.Trim(), - Description = string.Format("{0} {1}", Request.DeviceManufacturer.Trim(), Request.DeviceModel) - }; - dbContext.DeviceModels.Add(deviceModel); - RepoDevice.DeviceModel = deviceModel; - EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim()); - } - else - { - if (!RepoDevice.DeviceModelId.HasValue || RepoDevice.DeviceModelId.Value != deviceModel.Id) - { - RepoDevice.DeviceModel = deviceModel; - } - EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, RepoDevice.DeviceModelId); - } - - if (!RepoDevice.EnrolledDate.HasValue) - RepoDevice.EnrolledDate = DateTime.Now; - RepoDevice.LastEnrolDate = DateTime.Now; - } - - if (MachineInfo == null) - { - if (isAuthenticated || RepoDevice.AllowUnauthenticatedEnrol) - { - if (RepoDevice.DeviceProfile.ProvisionADAccount) - { - EnrolmentLog.LogSessionProgress(sessionId, 50, "Provisioning an Active Directory Computer Account"); - if (string.IsNullOrEmpty(RepoDevice.ComputerName) || RepoDevice.DeviceProfile.EnforceComputerNameConvention) - RepoDevice.ComputerName = RepoDevice.ComputerNameRender(dbContext); - EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, RepoDevice.SerialNumber, RepoDevice.ComputerName); - MachineInfo = ActiveDirectory.GetMachineAccount(RepoDevice.ComputerName); - response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId); - response.RequireReboot = true; - } - if (MachineInfo != null) - { - response.DeviceComputerName = MachineInfo.Name; - response.DeviceDomainName = MachineInfo.Domain; - } - else - { - response.DeviceComputerName = RepoDevice.ComputerName; - response.DeviceDomainName = RepoDevice.ComputerName; - } - } - else - { - RepoDevice.ComputerName = Request.DeviceComputerName; - response.DeviceComputerName = Request.DeviceComputerName; - response.DeviceDomainName = RepoDevice.ComputerName; - } - } - else - { - RepoDevice.ComputerName = MachineInfo.Name; - response.DeviceComputerName = MachineInfo.Name; - response.DeviceDomainName = MachineInfo.Domain; - - // Enforce Computer Name Convention - if (RepoDevice.DeviceProfile.EnforceComputerNameConvention) - { - var calculatedComputerName = RepoDevice.ComputerNameRender(dbContext); - if (!Request.DeviceComputerName.Equals(calculatedComputerName, StringComparison.InvariantCultureIgnoreCase)) - { - EnrolmentLog.LogSessionProgress(sessionId, 50, string.Format("Renaming Device: {0} -> {1}", Request.DeviceComputerName, calculatedComputerName)); - EnrolmentLog.LogSessionTaskRenamingDevice(sessionId, Request.DeviceComputerName, calculatedComputerName); - - RepoDevice.ComputerName = calculatedComputerName; - response.DeviceComputerName = calculatedComputerName; - - // Create New Account - response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId); - response.RequireReboot = true; - } - } - - // Enforce Organisation Unit - if (response.OfflineDomainJoin == null && RepoDevice.DeviceProfile.EnforceOrganisationalUnit) - { - if ((RepoDevice.DeviceProfile.OrganisationalUnit == null && MachineInfo.ParentDistinguishedName.Equals("CN=Computers", StringComparison.InvariantCultureIgnoreCase)) // Null (Default) OU - || !MachineInfo.ParentDistinguishedName.Equals(RepoDevice.DeviceProfile.OrganisationalUnit, StringComparison.InvariantCultureIgnoreCase)) // Custom OU - { - string newOU = RepoDevice.DeviceProfile.OrganisationalUnit ?? "CN=Computers"; - - EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisation Unit: {0} -> {1}", MachineInfo.ParentDistinguishedName, newOU)); - EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, MachineInfo.ParentDistinguishedName, newOU); - MachineInfo.MoveOrganisationUnit(RepoDevice.DeviceProfile.OrganisationalUnit); - MachineInfo = ActiveDirectory.GetMachineAccount(MachineInfo.sAMAccountName); - response.RequireReboot = true; - } - } - - } - if (MachineInfo != null) - { - EnrolmentLog.LogSessionProgress(sessionId, 75, "Updating Active Directory Computer Account Properties"); - MachineInfo.UpdateNetbootGUID(Request.DeviceUUID, Request.DeviceLanMacAddress); - if (RepoDevice.AssignedUser != null) - MachineInfo.SetDescription(RepoDevice); - } - if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne) - { - if (RepoDevice.AssignedUser == null) - { - response.AllowBootstrapperUninstall = false; - } - else - { - EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Active Directory Assigned User Account"); - ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); - EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); - response.AllowBootstrapperUninstall = true; - response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; - response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; - response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; - response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; - } - } - else - { - response.AllowBootstrapperUninstall = true; - } - if (!string.IsNullOrEmpty(Request.DeviceWlanMacAddress) && !string.IsNullOrEmpty(RepoDevice.DeviceProfile.CertificateProviderId)) - { - EnrolmentLog.LogSessionProgress(sessionId, 90, "Provisioning a Wireless Certificate"); - - var allocationResult = RepoDevice.AllocateCertificate(dbContext); - var deviceCertificate = allocationResult.Item1; - if (deviceCertificate != null) - { - bool certAlreadyInstalled = false; - if (Request.DeviceCertificates != null && Request.DeviceCertificates.Count > 0) - { - foreach (string existingCertName in Request.DeviceCertificates) - { - if (existingCertName.Contains(deviceCertificate.Name)) - { - certAlreadyInstalled = true; - break; - } - } - } - if (!certAlreadyInstalled) - { - EnrolmentLog.LogSessionTaskProvisioningWirelessCertificate(sessionId, RepoDevice.SerialNumber, deviceCertificate.Name); - response.DeviceCertificate = System.Convert.ToBase64String(deviceCertificate.Content); - } - } - response.DeviceCertificateRemoveExisting = allocationResult.Item2; - } - - // Reset 'AllowUnauthenticatedEnrol' - if (RepoDevice.AllowUnauthenticatedEnrol) - RepoDevice.AllowUnauthenticatedEnrol = false; - - EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully"); - } - catch (EnrolSafeException ex) - { - EnrolmentLog.LogSessionError(sessionId, ex); - return new EnrolResponse - { - SessionId = sessionId, - ErrorMessage = ex.Message - }; - } - catch (System.Exception ex2) - { - EnrolmentLog.LogSessionError(sessionId, ex2); - throw ex2; - } - finally - { - EnrolmentLog.LogSessionFinished(sessionId); - } - return response; - } - } -} +using System; +using System.Linq; +using System.Text.RegularExpressions; +using Disco.BI.Interop.ActiveDirectory; +using Disco.BI.Extensions; +using Disco.Data.Configuration.Modules; +using Disco.Data.Repository; +using Disco.Models.ClientServices; +using Disco.Models.Interop.ActiveDirectory; +using Disco.Models.Repository; +using Tamir.SharpSsh; +using Disco.Services.Plugins; +using Disco.Services.Plugins.Features.CertificateProvider; + +namespace Disco.BI.DeviceBI +{ + public class DeviceEnrol + { + public enum EnrolmentTypes + { + Normal, + Mac = 5, + MacSecure + } + + private static Regex SshPromptRegEx = new Regex("[\\$,\\#]", RegexOptions.Multiline); + public static MacSecureEnrolResponse MacSecureEnrol(DiscoDataContext dbContext, string Host) + { + MacEnrol trustedRequest = new MacEnrol(); + string sessionId = System.Guid.NewGuid().ToString("B"); + MacSecureEnrolResponse MacSecureEnrol; + try + { + EnrolmentLog.LogSessionStarting(sessionId, Host, EnrolmentTypes.MacSecure); + EnrolmentLog.LogSessionProgress(sessionId, 0, string.Format("Connecting to '{0}' as '{1}'", Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername)); + SshShell shell = new SshShell(Host, dbContext.DiscoConfiguration.Bootstrapper.MacSshUsername, dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); + try + { + shell.ExpectPattern = "#"; + shell.Connect(); + EnrolmentLog.LogSessionProgress(sessionId, 10, "Connected, Authenticating"); + var output = shell.Expect(SshPromptRegEx); + bool sessionElevated = false; + EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); + if (!output.TrimEnd(new char[0]).EndsWith("#")) + { + EnrolmentLog.LogSessionProgress(sessionId, 22, "Connected, Elevating Credentials"); + shell.WriteLine("sudo -k"); + System.Threading.Thread.Sleep(250); + output = shell.Expect(SshPromptRegEx); + EnrolmentLog.LogSessionProgress(sessionId, 25, "Connected, Elevating Credentials"); + EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); + shell.WriteLine("sudo -s -S"); + System.Threading.Thread.Sleep(250); + output = shell.Expect(":"); + EnrolmentLog.LogSessionProgress(sessionId, 27, "Connected, Elevating Credentials"); + EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); + shell.WriteLine(dbContext.DiscoConfiguration.Bootstrapper.MacSshPassword); + System.Threading.Thread.Sleep(250); + output = shell.Expect(SshPromptRegEx); + sessionElevated = true; + EnrolmentLog.LogSessionDiagnosticInformation(sessionId, output); + } + EnrolmentLog.LogSessionProgress(sessionId, 20, "Retrieving Serial Number"); + trustedRequest.DeviceSerialNumber = ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Serial Number\" | cut -d \":\" -f 2-", sessionId); + EnrolmentLog.LogSessionDevice(sessionId, trustedRequest.DeviceSerialNumber, null); + EnrolmentLog.LogSessionProgress(sessionId, 30, "Retrieving Hardware UUID"); + trustedRequest.DeviceUUID = ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Hardware UUID:\" | cut -d \":\" -f 2-", sessionId); + EnrolmentLog.LogSessionProgress(sessionId, 40, "Retrieving Computer Name"); + trustedRequest.DeviceComputerName = ParseMacShellCommand(shell, "scutil --get ComputerName", sessionId); + EnrolmentLog.LogSessionProgress(sessionId, 50, "Retrieving Ethernet MAC Address"); + string lanNicId = ParseMacShellCommand(shell, "system_profiler SPEthernetDataType | egrep -o \"en0|en1|en2|en3|en4|en5|en6\"", sessionId); + if (!string.IsNullOrWhiteSpace(lanNicId)) + { + trustedRequest.DeviceLanMacAddress = ParseMacShellCommand(shell, string.Format("ifconfig {0} | grep ether | cut -d \" \" -f 2-", lanNicId), sessionId); + } + EnrolmentLog.LogSessionProgress(sessionId, 65, "Retrieving Wireless MAC Address"); + string wlanNicId = ParseMacShellCommand(shell, "system_profiler SPAirPortDataType | egrep -o \"en0|en1|en2|en3|en4|en5|en6\"", sessionId); + if (!string.IsNullOrWhiteSpace(wlanNicId)) + { + trustedRequest.DeviceWlanMacAddress = ParseMacShellCommand(shell, string.Format("ifconfig {0} | grep ether | cut -d \" \" -f 2-", wlanNicId), sessionId); + } + trustedRequest.DeviceManufacturer = "Apple Inc."; + EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Model"); + trustedRequest.DeviceModel = ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Model Identifier:\" | cut -d \":\" -f 2-", sessionId); + EnrolmentLog.LogSessionProgress(sessionId, 90, "Retrieving Model Type"); + trustedRequest.DeviceModelType = ParseMacModelType(ParseMacShellCommand(shell, "system_profiler SPHardwareDataType | grep \"Model Name:\" | cut -d \":\" -f 2-", sessionId)); + EnrolmentLog.LogSessionProgress(sessionId, 99, "Disconnecting"); + output = ParseMacModelType(ParseMacShellCommand(shell, "exit", sessionId)); + if (sessionElevated) + { + output = ParseMacModelType(ParseMacShellCommand(shell, "exit", sessionId)); + } + if (shell.Connected) + { + shell.Close(); + } + EnrolmentLog.LogSessionProgress(sessionId, 100, "Disconnected, Starting Disco Enrolment"); + MacSecureEnrolResponse response = MacSecureEnrolResponse.FromMacEnrolResponse(MacEnrol(dbContext, trustedRequest, true, sessionId)); + EnrolmentLog.LogSessionFinished(sessionId); + MacSecureEnrol = response; + } + catch (System.Exception ex) + { + throw ex; + } + finally + { + if (shell != null) + { + bool connected = shell.Connected; + if (connected) + { + shell.Close(); + } + } + } + } + catch (System.Exception ex) + { + EnrolmentLog.LogSessionError(sessionId, ex); + throw ex; + } + return MacSecureEnrol; + } + + #region "Mac Enrol Helpers" + + private static string ParseMacModelType(string ModelName) + { + string ParseMacModelType; + if (!string.IsNullOrWhiteSpace(ModelName)) + { + string mn = ModelName.ToLower(); + if (mn.Contains("imac") || mn.Contains("mini")) + { + ParseMacModelType = "Desktop"; + return ParseMacModelType; + } + if (mn.Contains("macbook")) + { + ParseMacModelType = "Mobile"; + return ParseMacModelType; + } + if (mn.Contains("xserve")) + { + ParseMacModelType = "Server"; + return ParseMacModelType; + } + } + ParseMacModelType = "Unknown"; + return ParseMacModelType; + } + + private static string ParseMacShellCommand(SshShell Shell, string Command, string LogSessionId) + { + Shell.WriteLine(Command); + System.Threading.Thread.Sleep(250); + string Response = Shell.Expect(SshPromptRegEx); + Response = Response.Replace("\r", string.Empty); + EnrolmentLog.LogSessionDiagnosticInformation(LogSessionId, Response); + bool flag = Response.Contains("\n"); + string ParseMacShellCommand; + if (flag) + { + string[] ResponseLines = Response.Split(new char[] + { + '\n' + }); + switch (ResponseLines.Length) + { + case 0: + case 1: + { + ParseMacShellCommand = string.Empty; + break; + } + case 2: + case 3: + { + ParseMacShellCommand = ResponseLines[1].Trim(); + break; + } + default: + { + System.Text.StringBuilder ResponseBuilder = new System.Text.StringBuilder(); + int num = ResponseLines.Length - 2; + int lineIndex = 1; + while (true) + { + int arg_111_0 = lineIndex; + int num2 = num; + if (arg_111_0 > num2) + { + break; + } + ResponseBuilder.AppendLine(ResponseLines[lineIndex]); + lineIndex++; + } + ParseMacShellCommand = ResponseBuilder.ToString().Trim(); + break; + } + } + } + else + { + ParseMacShellCommand = Response; + } + return ParseMacShellCommand; + } + + #endregion + + public static MacEnrolResponse MacEnrol(DiscoDataContext dbContext, MacEnrol Request, bool Trusted, string OpenSessionId = null) + { + string sessionId; + if (OpenSessionId == null) + { + sessionId = System.Guid.NewGuid().ToString("B"); + EnrolmentLog.LogSessionStarting(sessionId, Request.DeviceSerialNumber, EnrolmentTypes.Mac); + } + else + { + sessionId = OpenSessionId; + } + EnrolmentLog.LogSessionDeviceInfo(sessionId, Request); + MacEnrolResponse response = new MacEnrolResponse(); + try + { + EnrolmentLog.LogSessionProgress(sessionId, 10, "Querying Database"); + Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceProfile").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); + if (!Trusted) + { + if (RepoDevice == null) + throw new EnrolSafeException(string.Format("Unknown Device Serial Number (SN: '{0}')", Request.DeviceSerialNumber)); + if (!RepoDevice.AllowUnauthenticatedEnrol) + throw new EnrolSafeException(string.Format("Device isn't allowed an Unauthenticated Enrolment (SN: '{0}')", Request.DeviceSerialNumber)); + } + if (RepoDevice == null) + { + EnrolmentLog.LogSessionProgress(sessionId, 50, "New Device, Building Disco Instance"); + EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); + DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); + + var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + DeviceModel deviceModel = deviceModelResult.Item1; + if (deviceModelResult.Item2) + EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); + else + EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, deviceModel.Id); + + RepoDevice = new Device + { + SerialNumber = Request.DeviceSerialNumber, + ComputerName = Request.DeviceComputerName, + DeviceProfile = deviceProfile, + DeviceModel = deviceModel, + AllowUnauthenticatedEnrol = false, + Active = true, + CreatedDate = DateTime.Now, + EnrolledDate = DateTime.Now + }; + dbContext.Devices.Add(RepoDevice); + } + else + { + EnrolmentLog.LogSessionProgress(sessionId, 50, "Existing Device, Updating Disco Instance"); + EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); + if (!RepoDevice.DeviceModelId.HasValue || RepoDevice.DeviceModelId.Value == 1) + { + var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + DeviceModel deviceModel = deviceModelResult.Item1; + if (deviceModelResult.Item2) + EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); + else + EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, deviceModel.Id); + + RepoDevice.DeviceModel = deviceModel; + } + else + { + EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, RepoDevice.DeviceModelId); + } + RepoDevice.ComputerName = Request.DeviceComputerName; + if (!RepoDevice.EnrolledDate.HasValue) + { + RepoDevice.EnrolledDate = DateTime.Now; + } + } + RepoDevice.LastEnrolDate = DateTime.Now; + RepoDevice.AllowUnauthenticatedEnrol = false; + // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. + //DeviceProfileConfiguration RepoDeviceProfileContext = RepoDevice.DeviceProfile.Configuration(Context); + EnrolmentLog.LogSessionProgress(sessionId, 90, "Building Response"); + //if (RepoDeviceProfileContext.DistributionType == DeviceProfileConfiguration.DeviceProfileDistributionTypes.OneToOne && RepoDevice.AssignedUser != null) + if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne && RepoDevice.AssignedUser != null) + { + ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); + EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); + response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; + response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; + response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; + response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; + } + response.DeviceComputerName = RepoDevice.ComputerName; + EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully"); + } + catch (EnrolSafeException ex) + { + EnrolmentLog.LogSessionError(sessionId, ex); + return new MacEnrolResponse { ErrorMessage = ex.Message }; + } + catch (System.Exception ex2) + { + EnrolmentLog.LogSessionError(sessionId, ex2); + throw ex2; + } + finally + { + if (OpenSessionId == null) + EnrolmentLog.LogSessionFinished(sessionId); + } + return response; + } + public static EnrolResponse Enrol(DiscoDataContext dbContext, string Username, Models.ClientServices.Enrol Request) + { + ActiveDirectoryMachineAccount MachineInfo = null; + EnrolResponse response = new EnrolResponse(); + User authenticatedUser = null; + bool isAuthenticated = false; + string sessionId = System.Guid.NewGuid().ToString("B"); + response.SessionId = sessionId; + EnrolmentLog.LogSessionStarting(sessionId, Request.DeviceSerialNumber, EnrolmentTypes.Normal); + EnrolmentLog.LogSessionDeviceInfo(sessionId, Request); + try + { + EnrolmentLog.LogSessionProgress(sessionId, 10, "Loading User Data"); + if (!string.IsNullOrWhiteSpace(Username)) + { + authenticatedUser = UserBI.UserCache.GetUser(Username, dbContext); + isAuthenticated = (authenticatedUser != null); + } + EnrolmentLog.LogSessionProgress(sessionId, 13, "Loading Device Data"); + + Device RepoDevice = dbContext.Devices.Include("AssignedUser").Include("DeviceModel").Include("DeviceProfile").Where(d => d.SerialNumber == Request.DeviceSerialNumber).FirstOrDefault(); + EnrolmentLog.LogSessionProgress(sessionId, 15, "Discovering User/Device Disco Permissions"); + if (isAuthenticated) + { + if (authenticatedUser.Type != "Admin") + { + if (authenticatedUser.Type != "Computer") + throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); + if (!authenticatedUser.Id.Equals(string.Format("{0}$", Request.DeviceComputerName), System.StringComparison.InvariantCultureIgnoreCase)) + throw new EnrolSafeException(string.Format("Connection not correctly authenticated (SN: {0}; Auth User: {1}; User Type: {2})", Request.DeviceSerialNumber, authenticatedUser.Id, authenticatedUser.Type)); + } + } + else + { + if (RepoDevice == null) + throw new EnrolSafeException(string.Format("Unknown Device Serial Number (SN: '{0}')", Request.DeviceSerialNumber)); + if (!RepoDevice.AllowUnauthenticatedEnrol) + throw new EnrolSafeException(string.Format("Device isn't allowed an Unauthenticated Enrolment (SN: '{0}')", Request.DeviceSerialNumber)); + } + if (Request.DeviceIsPartOfDomain && !string.IsNullOrWhiteSpace(Request.DeviceComputerName)) + { + EnrolmentLog.LogSessionProgress(sessionId, 20, "Loading Active Directory Computer Account"); + System.Guid? uuidGuid = null; + System.Guid? macAddressGuid = null; + if (!string.IsNullOrEmpty(Request.DeviceUUID)) + uuidGuid = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromUUID(Request.DeviceUUID); + if (!string.IsNullOrEmpty(Request.DeviceLanMacAddress)) + macAddressGuid = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromMACAddress(Request.DeviceLanMacAddress); + MachineInfo = ActiveDirectory.GetMachineAccount(Request.DeviceComputerName, uuidGuid, macAddressGuid); + } + if (RepoDevice == null) + { + EnrolmentLog.LogSessionProgress(sessionId, 30, "New Device, Creating Disco Instance"); + EnrolmentLog.LogSessionTaskAddedDevice(sessionId, Request.DeviceSerialNumber); + DeviceProfile deviceProfile = dbContext.DeviceProfiles.Find(dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId); + + + var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + DeviceModel deviceModel = deviceModelResult.Item1; + if (deviceModelResult.Item2) + EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); + else + EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, deviceModel.Id); + + RepoDevice = new Device + { + SerialNumber = Request.DeviceSerialNumber, + ComputerName = Request.DeviceComputerName, + DeviceProfile = deviceProfile, + DeviceModel = deviceModel, + AllowUnauthenticatedEnrol = false, + Active = true, + CreatedDate = DateTime.Now, + EnrolledDate = DateTime.Now, + LastEnrolDate = DateTime.Now + }; + dbContext.Devices.Add(RepoDevice); + } + else + { + EnrolmentLog.LogSessionProgress(sessionId, 30, "Existing Device, Updating Disco Instance"); + EnrolmentLog.LogSessionTaskUpdatingDevice(sessionId, Request.DeviceSerialNumber); + + var deviceModelResult = dbContext.DeviceModels.GetOrCreateDeviceModel(Request.DeviceManufacturer.Trim(), Request.DeviceModel.Trim(), Request.DeviceModel.Trim()); + DeviceModel deviceModel = deviceModelResult.Item1; + if (deviceModelResult.Item2) + EnrolmentLog.LogSessionTaskCreatedDeviceModel(sessionId, Request.DeviceSerialNumber, deviceModelResult.Item1.Manufacturer, deviceModelResult.Item1.Model); + else + EnrolmentLog.LogSessionDevice(sessionId, Request.DeviceSerialNumber, deviceModel.Id); + + RepoDevice.DeviceModel = deviceModel; + + if (!RepoDevice.EnrolledDate.HasValue) + RepoDevice.EnrolledDate = DateTime.Now; + RepoDevice.LastEnrolDate = DateTime.Now; + } + + if (MachineInfo == null) + { + if (isAuthenticated || RepoDevice.AllowUnauthenticatedEnrol) + { + if (RepoDevice.DeviceProfile.ProvisionADAccount) + { + EnrolmentLog.LogSessionProgress(sessionId, 50, "Provisioning an Active Directory Computer Account"); + if (string.IsNullOrEmpty(RepoDevice.ComputerName) || RepoDevice.DeviceProfile.EnforceComputerNameConvention) + RepoDevice.ComputerName = RepoDevice.ComputerNameRender(dbContext); + EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, RepoDevice.SerialNumber, RepoDevice.ComputerName); + MachineInfo = ActiveDirectory.GetMachineAccount(RepoDevice.ComputerName); + response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId); + response.RequireReboot = true; + } + if (MachineInfo != null) + { + response.DeviceComputerName = MachineInfo.Name; + response.DeviceDomainName = MachineInfo.Domain; + } + else + { + response.DeviceComputerName = RepoDevice.ComputerName; + response.DeviceDomainName = RepoDevice.ComputerName; + } + } + else + { + RepoDevice.ComputerName = Request.DeviceComputerName; + response.DeviceComputerName = Request.DeviceComputerName; + response.DeviceDomainName = RepoDevice.ComputerName; + } + } + else + { + RepoDevice.ComputerName = MachineInfo.Name; + response.DeviceComputerName = MachineInfo.Name; + response.DeviceDomainName = MachineInfo.Domain; + + // Enforce Computer Name Convention + if (RepoDevice.DeviceProfile.EnforceComputerNameConvention) + { + var calculatedComputerName = RepoDevice.ComputerNameRender(dbContext); + if (!Request.DeviceComputerName.Equals(calculatedComputerName, StringComparison.InvariantCultureIgnoreCase)) + { + EnrolmentLog.LogSessionProgress(sessionId, 50, string.Format("Renaming Device: {0} -> {1}", Request.DeviceComputerName, calculatedComputerName)); + EnrolmentLog.LogSessionTaskRenamingDevice(sessionId, Request.DeviceComputerName, calculatedComputerName); + + RepoDevice.ComputerName = calculatedComputerName; + response.DeviceComputerName = calculatedComputerName; + + // Create New Account + response.OfflineDomainJoin = ActiveDirectory.OfflineDomainJoinProvision(ref MachineInfo, RepoDevice.ComputerName, RepoDevice.DeviceProfile.OrganisationalUnit, sessionId); + response.RequireReboot = true; + } + } + + // Enforce Organisation Unit + if (response.OfflineDomainJoin == null && RepoDevice.DeviceProfile.EnforceOrganisationalUnit) + { + if ((RepoDevice.DeviceProfile.OrganisationalUnit == null && MachineInfo.ParentDistinguishedName.Equals("CN=Computers", StringComparison.InvariantCultureIgnoreCase)) // Null (Default) OU + || !MachineInfo.ParentDistinguishedName.Equals(RepoDevice.DeviceProfile.OrganisationalUnit, StringComparison.InvariantCultureIgnoreCase)) // Custom OU + { + string newOU = RepoDevice.DeviceProfile.OrganisationalUnit ?? "CN=Computers"; + + EnrolmentLog.LogSessionProgress(sessionId, 65, string.Format("Moving Device Organisation Unit: {0} -> {1}", MachineInfo.ParentDistinguishedName, newOU)); + EnrolmentLog.LogSessionTaskMovingDeviceOrganisationUnit(sessionId, MachineInfo.ParentDistinguishedName, newOU); + MachineInfo.MoveOrganisationUnit(RepoDevice.DeviceProfile.OrganisationalUnit); + MachineInfo = ActiveDirectory.GetMachineAccount(MachineInfo.sAMAccountName); + response.RequireReboot = true; + } + } + + } + if (MachineInfo != null) + { + EnrolmentLog.LogSessionProgress(sessionId, 75, "Updating Active Directory Computer Account Properties"); + MachineInfo.UpdateNetbootGUID(Request.DeviceUUID, Request.DeviceLanMacAddress); + if (RepoDevice.AssignedUser != null) + MachineInfo.SetDescription(RepoDevice); + } + if (RepoDevice.DeviceProfile.DistributionType == DeviceProfile.DistributionTypes.OneToOne) + { + if (RepoDevice.AssignedUser == null) + { + response.AllowBootstrapperUninstall = false; + } + else + { + EnrolmentLog.LogSessionProgress(sessionId, 80, "Retrieving Active Directory Assigned User Account"); + ActiveDirectoryUserAccount AssignedUserInfo = ActiveDirectory.GetUserAccount(RepoDevice.AssignedUser.Id); + EnrolmentLog.LogSessionTaskAssigningUser(sessionId, RepoDevice.SerialNumber, AssignedUserInfo.DisplayName, AssignedUserInfo.sAMAccountName, AssignedUserInfo.Domain, AssignedUserInfo.ObjectSid); + response.AllowBootstrapperUninstall = true; + response.DeviceAssignedUserUsername = AssignedUserInfo.sAMAccountName; + response.DeviceAssignedUserDomain = AssignedUserInfo.Domain; + response.DeviceAssignedUserName = AssignedUserInfo.DisplayName; + response.DeviceAssignedUserSID = AssignedUserInfo.ObjectSid; + } + } + else + { + response.AllowBootstrapperUninstall = true; + } + if (!string.IsNullOrEmpty(Request.DeviceWlanMacAddress) && !string.IsNullOrEmpty(RepoDevice.DeviceProfile.CertificateProviderId)) + { + EnrolmentLog.LogSessionProgress(sessionId, 90, "Provisioning a Wireless Certificate"); + + var allocationResult = RepoDevice.AllocateCertificate(dbContext); + var deviceCertificate = allocationResult.Item1; + if (deviceCertificate != null) + { + bool certAlreadyInstalled = false; + if (Request.DeviceCertificates != null && Request.DeviceCertificates.Count > 0) + { + foreach (string existingCertName in Request.DeviceCertificates) + { + if (existingCertName.Contains(deviceCertificate.Name)) + { + certAlreadyInstalled = true; + break; + } + } + } + if (!certAlreadyInstalled) + { + EnrolmentLog.LogSessionTaskProvisioningWirelessCertificate(sessionId, RepoDevice.SerialNumber, deviceCertificate.Name); + response.DeviceCertificate = System.Convert.ToBase64String(deviceCertificate.Content); + } + } + response.DeviceCertificateRemoveExisting = allocationResult.Item2; + } + + // Reset 'AllowUnauthenticatedEnrol' + if (RepoDevice.AllowUnauthenticatedEnrol) + RepoDevice.AllowUnauthenticatedEnrol = false; + + EnrolmentLog.LogSessionProgress(sessionId, 100, "Completed Successfully"); + } + catch (EnrolSafeException ex) + { + EnrolmentLog.LogSessionError(sessionId, ex); + return new EnrolResponse + { + SessionId = sessionId, + ErrorMessage = ex.Message + }; + } + catch (System.Exception ex2) + { + EnrolmentLog.LogSessionError(sessionId, ex2); + throw ex2; + } + finally + { + EnrolmentLog.LogSessionFinished(sessionId); + } + return response; + } + } +} diff --git a/Disco.Data/Repository/DiscoDataSeeder.cs b/Disco.Data/Repository/DiscoDataSeeder.cs index 296a639e..0c96c544 100644 --- a/Disco.Data/Repository/DiscoDataSeeder.cs +++ b/Disco.Data/Repository/DiscoDataSeeder.cs @@ -1,270 +1,303 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Disco.Models.Repository; - -namespace Disco.Data.Repository -{ - public static class DiscoDataSeeder - { - public static void SeedDatabase(this DiscoDataContext context) - { - context.SeedDeploymentId(); - context.SeedDeviceModels(); - context.SeedDeviceProfiles(); - context.SeedJobTypes(); - context.SeedJobSubTypes(); - } - - public static void SeedDeploymentId(this DiscoDataContext context) - { - if (context.ConfigurationItems.Count(ci => ci.Scope == "System" && ci.Key == "DeploymentId") == 0) - { - var deploymentId = Guid.NewGuid().ToString("D"); - context.ConfigurationItems.Add(new ConfigurationItem { Scope = "System", Key = "DeploymentId", Value = deploymentId }); - } - } - public static void SeedJobTypes(this DiscoDataContext context) - { - if (context.JobTypes.Count() == 0) - { - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HWar, Description = "Hardware - Warranty" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HNWar, Description = "Hardware - Non-Warranty" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HMisc, Description = "Hardware - Misc" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SImg, Description = "Software - Reimage" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SApp, Description = "Software - Application" }); - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SOS, Description = "Software - Operating System" }); - } - // 2012-05-22 - #region "User Management" Added - if (context.JobTypes.Count(jt => jt.Id == JobType.JobTypeIds.UMgmt) == 0) - context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.UMgmt, Description = "User - Management" }); - #endregion - // End - } - public static void SeedDeviceModels(this DiscoDataContext context) - { - if (context.DeviceModels.Count() == 0) - { - context.DeviceModels.Add(new DeviceModel { Manufacturer = "Unknown", Model = "Unknown", Description = "Unknown Device Model" }); - } - UpdateDeviceModelConfiguration(context); - // Removed: 2013-01-14 G# - //UpdateDeviceModelImageStorage(context); - } - public static void SeedDeviceProfiles(this DiscoDataContext context) - { - if (context.DeviceProfiles.Count() == 0) - { - context.DeviceProfiles.Add(new DeviceProfile { ShortName = "WS", Name = "Default", Description = "Initial Default Workstation Profile", ComputerNameTemplate = "DeviceProfile.ShortName + ''-'' + SerialNumber" }); - } - } - public static void SeedJobSubTypes(this DiscoDataContext context) - { - if (context.JobSubTypes.Count() == 0) - { - context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bag" }); - context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HWar, Description = "Battery" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Inner" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bluetooth Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HWar, Description = "CPU" }); - context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Hard Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Keyboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Motherboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HWar, Description = "Mouse/Track Pad" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Cord/Socket" }); - context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HWar, Description = "RAM" }); - context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HWar, Description = "Replacement Device" }); - context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HWar, Description = "Screen" }); - context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HWar, Description = "Speakers" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HWar, Description = "Web Camera" }); - context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Wireless Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HWar, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bag" }); - context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Battery" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Inner" }); - context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Top" }); - context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bluetooth Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HNWar, Description = "CPU" }); - context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Hard Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Keyboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Motherboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Mouse/Track Pad" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Cord/Socket" }); - context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HNWar, Description = "RAM" }); - context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Replacement Device" }); - context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Screen" }); - context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Speakers" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Web Camera" }); - context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Wireless Adapter" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "ExternalHardDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Hard Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "IWB", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Interactive Whiteboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "InternetDongle", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Internet Dongle" }); - context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Keyboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "MobilePhone", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Mobile Phone" }); - context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Mouse" }); - context.JobSubTypes.Add(new JobSubType { Id = "MP3Player", JobTypeId = JobType.JobTypeIds.HMisc, Description = "MP3 Player" }); - context.JobSubTypes.Add(new JobSubType { Id = "PrinterScanner", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Printer/Scanner" }); - context.JobSubTypes.Add(new JobSubType { Id = "Projector", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Projector" }); - context.JobSubTypes.Add(new JobSubType { Id = "USBFlashDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "USB Flash Drive" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Web Camera" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "ContentIllegal", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Illegal" }); - context.JobSubTypes.Add(new JobSubType { Id = "ContentInappropriate", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Inappropriate" }); - context.JobSubTypes.Add(new JobSubType { Id = "CorruptOS", JobTypeId = JobType.JobTypeIds.SImg, Description = "Corrupt Operating System" }); - context.JobSubTypes.Add(new JobSubType { Id = "HardwareChanges", JobTypeId = JobType.JobTypeIds.SImg, Description = "Hardware Changes" }); - context.JobSubTypes.Add(new JobSubType { Id = "Malware", JobTypeId = JobType.JobTypeIds.SImg, Description = "Malware" }); - context.JobSubTypes.Add(new JobSubType { Id = "Performance", JobTypeId = JobType.JobTypeIds.SImg, Description = "Performance" }); - context.JobSubTypes.Add(new JobSubType { Id = "UserRequest", JobTypeId = JobType.JobTypeIds.SImg, Description = "User Request" }); - context.JobSubTypes.Add(new JobSubType { Id = "UpdatedImage", JobTypeId = JobType.JobTypeIds.SImg, Description = "Updated Image" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SImg, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "CurriculumTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Curriculum Tool" }); - context.JobSubTypes.Add(new JobSubType { Id = "GamingEntertainment", JobTypeId = JobType.JobTypeIds.SApp, Description = "Gaming/Entertainment" }); - context.JobSubTypes.Add(new JobSubType { Id = "ImageManipulation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Image Manipulation" }); - context.JobSubTypes.Add(new JobSubType { Id = "MultimediaPlayback", JobTypeId = JobType.JobTypeIds.SApp, Description = "Multimedia Playback" }); - context.JobSubTypes.Add(new JobSubType { Id = "Presentation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Presentation" }); - context.JobSubTypes.Add(new JobSubType { Id = "Spreadsheet", JobTypeId = JobType.JobTypeIds.SApp, Description = "Spreadsheet" }); - context.JobSubTypes.Add(new JobSubType { Id = "StaffTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Staff Tool" }); - context.JobSubTypes.Add(new JobSubType { Id = "StudentReporting", JobTypeId = JobType.JobTypeIds.SApp, Description = "Student Reporting" }); - context.JobSubTypes.Add(new JobSubType { Id = "VideoEditing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Video Editing" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebBrowser", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser" }); - context.JobSubTypes.Add(new JobSubType { Id = "WebBrowserPlugin", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser Plugin" }); - context.JobSubTypes.Add(new JobSubType { Id = "WordProcessing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Word Processing" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SApp, Description = "Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "Appearance", JobTypeId = JobType.JobTypeIds.SOS, Description = "Appearance & Personalisation" }); - context.JobSubTypes.Add(new JobSubType { Id = "DisplaySettings", JobTypeId = JobType.JobTypeIds.SOS, Description = "Display Settings" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversIWB", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Interactive Whiteboard" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversPrintScan", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Printers/Scanners" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversSystem", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - System" }); - context.JobSubTypes.Add(new JobSubType { Id = "DriversOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "Group Policy", JobTypeId = JobType.JobTypeIds.SOS, Description = "Group Policy" }); - context.JobSubTypes.Add(new JobSubType { Id = "KeyboardMouseConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Keyboard/Mouse Configuration" }); - context.JobSubTypes.Add(new JobSubType { Id = "MalwareProtection", JobTypeId = JobType.JobTypeIds.SOS, Description = "Malware Protection" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkDrives", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network Drives" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkWired", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wired" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkWireless", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wireless" }); - context.JobSubTypes.Add(new JobSubType { Id = "NetworkOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Other" }); - context.JobSubTypes.Add(new JobSubType { Id = "PatchUpdate", JobTypeId = JobType.JobTypeIds.SOS, Description = "Patches/Updates" }); - context.JobSubTypes.Add(new JobSubType { Id = "PowerManagement", JobTypeId = JobType.JobTypeIds.SOS, Description = "Power Management" }); - context.JobSubTypes.Add(new JobSubType { Id = "PrintersScanners", JobTypeId = JobType.JobTypeIds.SOS, Description = "Printers/Scanners" }); - context.JobSubTypes.Add(new JobSubType { Id = "SoundConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Sound Configuration" }); - context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SOS, Description = "Other" }); - } - - // Feature Request 2012-04-27 by Elijah: https://disco.uservoice.com/forums/159707-feedback/suggestions/2803945-customisable-job-sub-types - #region "Optical Drive" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "OpticalDrive") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Optical Drive" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "OpticalDrive") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Optical Drive" }); - #endregion - // End Feature Request - - // 2012-05-22 - #region "User Management" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.UMgmt) == 0) - { - context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Infringement, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Infringement }); - context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Contact, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Contact }); - } - #endregion - // End - - // 2012-05-29 - Audits - #region "Audit" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HMisc && jst.Id == "Audit") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Audit" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.SApp && jst.Id == "Audit") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.SApp, Description = "Audit" }); - #endregion - // End - - // Feature Request 2012-06-16 by James: https://disco.uservoice.com/forums/159707-feedback/suggestions/3002911-add-in-microphone-in-hardware-warranty-and-non-war - #region "Microphone" Added - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "Microphone") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Microphone" }); - if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "Microphone") == 0) - context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HWar, Description = "Microphone" }); - #endregion - // End Feature Request - } - - private static void UpdateDeviceModelConfiguration(this DiscoDataContext context) - { - if (context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).Count() > 0) - { - var configurationItems = context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).ToList(); - - var deviceProfiles = context.DeviceProfiles.ToDictionary(dp => dp.Id); - foreach (var configurationItem in configurationItems) - { - int profileId = int.Parse(configurationItem.Scope.Substring(configurationItem.Scope.IndexOf(":") + 1)); - DeviceProfile dp; - if (deviceProfiles.TryGetValue(profileId, out dp)) - { - switch (configurationItem.Key) - { - case "ComputerNameTemplate": - dp.ComputerNameTemplate = configurationItem.Value; - break; - case "DistributionType": - dp.DistributionType = (DeviceProfile.DistributionTypes)(int.Parse(configurationItem.Value)); - break; - case "OrganisationalUnit": - dp.OrganisationalUnit = configurationItem.Value; - break; - case "AllocateWirelessCertificate": - if (bool.Parse(configurationItem.Value)) - dp.CertificateProviderId = ""; - else - dp.CertificateProviderId = null; - break; - default: - continue; // Unknown Configuration Item - Leave in DB & Ignore - } - } - // Remove from DB - context.ConfigurationItems.Remove(configurationItem); - } - } - - } - - // Removed: 2013-01-14 G# -// private static void UpdateDeviceModelImageStorage(this DiscoDataContext dbContext) -// { -//#pragma warning disable 0618 -// var updateModels = dbContext.DeviceModels.Where(dm => dm.Image != null); -// if (updateModels.Count() > 0) -// { -// var dataStoreLocation = dbContext.ConfigurationItems.Where(ci => ci.Scope == "System" && ci.Key == "DataStoreLocation").Select(ci => ci.Value).FirstOrDefault(); -// if (!string.IsNullOrEmpty(dataStoreLocation) && System.IO.Directory.Exists(dataStoreLocation)) -// { -// var deviceModelImagesLocation = System.IO.Path.Combine(dataStoreLocation, "DeviceModelImages"); -// if (!System.IO.Directory.Exists(deviceModelImagesLocation)) -// System.IO.Directory.CreateDirectory(deviceModelImagesLocation); -// foreach (var model in updateModels) -// { -// var modelpath = System.IO.Path.Combine(deviceModelImagesLocation, string.Format("{0}.png", model.Id)); - -// if (model.Image != null && model.Image.Length > 0) -// { -// System.IO.File.WriteAllBytes(modelpath, model.Image); -// } -// model.Image = null; -// } -// } -// } -//#pragma warning restore 0618 -// } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Disco.Models.Repository; + +namespace Disco.Data.Repository +{ + public static class DiscoDataSeeder + { + public static void SeedDatabase(this DiscoDataContext context) + { + context.SeedDeploymentId(); + context.SeedDeviceModels(); + context.SeedDeviceProfiles(); + context.SeedJobTypes(); + context.SeedJobSubTypes(); + } + + public static void SeedDeploymentId(this DiscoDataContext context) + { + if (context.ConfigurationItems.Count(ci => ci.Scope == "System" && ci.Key == "DeploymentId") == 0) + { + var deploymentId = Guid.NewGuid().ToString("D"); + context.ConfigurationItems.Add(new ConfigurationItem { Scope = "System", Key = "DeploymentId", Value = deploymentId }); + } + } + public static void SeedJobTypes(this DiscoDataContext context) + { + if (context.JobTypes.Count() == 0) + { + context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HWar, Description = "Hardware - Warranty" }); + context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HNWar, Description = "Hardware - Non-Warranty" }); + context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.HMisc, Description = "Hardware - Misc" }); + context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SImg, Description = "Software - Reimage" }); + context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SApp, Description = "Software - Application" }); + context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.SOS, Description = "Software - Operating System" }); + } + // 2012-05-22 + #region "User Management" Added + if (context.JobTypes.Count(jt => jt.Id == JobType.JobTypeIds.UMgmt) == 0) + context.JobTypes.Add(new JobType { Id = JobType.JobTypeIds.UMgmt, Description = "User - Management" }); + #endregion + // End + } + public static void SeedDeviceModels(this DiscoDataContext context) + { + if (context.DeviceModels.Count() == 0) + { + context.DeviceModels.Add(new DeviceModel { Manufacturer = "Unknown", Model = "Unknown", Description = "Unknown Device Model" }); + } + UpdateDeviceModelConfiguration(context); + // Removed: 2013-01-14 G# + //UpdateDeviceModelImageStorage(context); + + // Added: 2013-02-07 G# + UpdateDeviceModelDuplicates(context); + } + public static void SeedDeviceProfiles(this DiscoDataContext context) + { + if (context.DeviceProfiles.Count() == 0) + { + context.DeviceProfiles.Add(new DeviceProfile { ShortName = "WS", Name = "Default", Description = "Initial Default Workstation Profile", ComputerNameTemplate = "DeviceProfile.ShortName + ''-'' + SerialNumber" }); + } + } + public static void SeedJobSubTypes(this DiscoDataContext context) + { + if (context.JobSubTypes.Count() == 0) + { + context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bag" }); + context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HWar, Description = "Battery" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Bottom" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Case Top" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Inner" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bezel - Screen Top" }); + context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Bluetooth Adapter" }); + context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HWar, Description = "CPU" }); + context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Hard Drive" }); + context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Keyboard" }); + context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HWar, Description = "Motherboard" }); + context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HWar, Description = "Mouse/Track Pad" }); + context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Adapter" }); + context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HWar, Description = "Power Cord/Socket" }); + context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HWar, Description = "RAM" }); + context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HWar, Description = "Replacement Device" }); + context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HWar, Description = "Screen" }); + context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HWar, Description = "Speakers" }); + context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HWar, Description = "Web Camera" }); + context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HWar, Description = "Wireless Adapter" }); + context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HWar, Description = "Other" }); + context.JobSubTypes.Add(new JobSubType { Id = "Bag", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bag" }); + context.JobSubTypes.Add(new JobSubType { Id = "Battery", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Battery" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseBottom", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Bottom" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelCaseTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Case Top" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenInner", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Inner" }); + context.JobSubTypes.Add(new JobSubType { Id = "BezelScreenTop", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bezel - Screen Top" }); + context.JobSubTypes.Add(new JobSubType { Id = "BluetoothAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Bluetooth Adapter" }); + context.JobSubTypes.Add(new JobSubType { Id = "CPU", JobTypeId = JobType.JobTypeIds.HNWar, Description = "CPU" }); + context.JobSubTypes.Add(new JobSubType { Id = "HardDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Hard Drive" }); + context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Keyboard" }); + context.JobSubTypes.Add(new JobSubType { Id = "Motherboard", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Motherboard" }); + context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Mouse/Track Pad" }); + context.JobSubTypes.Add(new JobSubType { Id = "PowerAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Adapter" }); + context.JobSubTypes.Add(new JobSubType { Id = "PowerCord", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Power Cord/Socket" }); + context.JobSubTypes.Add(new JobSubType { Id = "RAM", JobTypeId = JobType.JobTypeIds.HNWar, Description = "RAM" }); + context.JobSubTypes.Add(new JobSubType { Id = "ReplacementDevice", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Replacement Device" }); + context.JobSubTypes.Add(new JobSubType { Id = "Screen", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Screen" }); + context.JobSubTypes.Add(new JobSubType { Id = "Speakers", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Speakers" }); + context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Web Camera" }); + context.JobSubTypes.Add(new JobSubType { Id = "WirelessAdapter", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Wireless Adapter" }); + context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Other" }); + context.JobSubTypes.Add(new JobSubType { Id = "ExternalHardDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Hard Drive" }); + context.JobSubTypes.Add(new JobSubType { Id = "IWB", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Interactive Whiteboard" }); + context.JobSubTypes.Add(new JobSubType { Id = "InternetDongle", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Internet Dongle" }); + context.JobSubTypes.Add(new JobSubType { Id = "Keyboard", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Keyboard" }); + context.JobSubTypes.Add(new JobSubType { Id = "MobilePhone", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Mobile Phone" }); + context.JobSubTypes.Add(new JobSubType { Id = "Mouse", JobTypeId = JobType.JobTypeIds.HMisc, Description = "External Mouse" }); + context.JobSubTypes.Add(new JobSubType { Id = "MP3Player", JobTypeId = JobType.JobTypeIds.HMisc, Description = "MP3 Player" }); + context.JobSubTypes.Add(new JobSubType { Id = "PrinterScanner", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Printer/Scanner" }); + context.JobSubTypes.Add(new JobSubType { Id = "Projector", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Projector" }); + context.JobSubTypes.Add(new JobSubType { Id = "USBFlashDrive", JobTypeId = JobType.JobTypeIds.HMisc, Description = "USB Flash Drive" }); + context.JobSubTypes.Add(new JobSubType { Id = "WebCamera", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Web Camera" }); + context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Other" }); + context.JobSubTypes.Add(new JobSubType { Id = "ContentIllegal", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Illegal" }); + context.JobSubTypes.Add(new JobSubType { Id = "ContentInappropriate", JobTypeId = JobType.JobTypeIds.SImg, Description = "Content - Inappropriate" }); + context.JobSubTypes.Add(new JobSubType { Id = "CorruptOS", JobTypeId = JobType.JobTypeIds.SImg, Description = "Corrupt Operating System" }); + context.JobSubTypes.Add(new JobSubType { Id = "HardwareChanges", JobTypeId = JobType.JobTypeIds.SImg, Description = "Hardware Changes" }); + context.JobSubTypes.Add(new JobSubType { Id = "Malware", JobTypeId = JobType.JobTypeIds.SImg, Description = "Malware" }); + context.JobSubTypes.Add(new JobSubType { Id = "Performance", JobTypeId = JobType.JobTypeIds.SImg, Description = "Performance" }); + context.JobSubTypes.Add(new JobSubType { Id = "UserRequest", JobTypeId = JobType.JobTypeIds.SImg, Description = "User Request" }); + context.JobSubTypes.Add(new JobSubType { Id = "UpdatedImage", JobTypeId = JobType.JobTypeIds.SImg, Description = "Updated Image" }); + context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SImg, Description = "Other" }); + context.JobSubTypes.Add(new JobSubType { Id = "CurriculumTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Curriculum Tool" }); + context.JobSubTypes.Add(new JobSubType { Id = "GamingEntertainment", JobTypeId = JobType.JobTypeIds.SApp, Description = "Gaming/Entertainment" }); + context.JobSubTypes.Add(new JobSubType { Id = "ImageManipulation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Image Manipulation" }); + context.JobSubTypes.Add(new JobSubType { Id = "MultimediaPlayback", JobTypeId = JobType.JobTypeIds.SApp, Description = "Multimedia Playback" }); + context.JobSubTypes.Add(new JobSubType { Id = "Presentation", JobTypeId = JobType.JobTypeIds.SApp, Description = "Presentation" }); + context.JobSubTypes.Add(new JobSubType { Id = "Spreadsheet", JobTypeId = JobType.JobTypeIds.SApp, Description = "Spreadsheet" }); + context.JobSubTypes.Add(new JobSubType { Id = "StaffTool", JobTypeId = JobType.JobTypeIds.SApp, Description = "Staff Tool" }); + context.JobSubTypes.Add(new JobSubType { Id = "StudentReporting", JobTypeId = JobType.JobTypeIds.SApp, Description = "Student Reporting" }); + context.JobSubTypes.Add(new JobSubType { Id = "VideoEditing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Video Editing" }); + context.JobSubTypes.Add(new JobSubType { Id = "WebBrowser", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser" }); + context.JobSubTypes.Add(new JobSubType { Id = "WebBrowserPlugin", JobTypeId = JobType.JobTypeIds.SApp, Description = "Web Browser Plugin" }); + context.JobSubTypes.Add(new JobSubType { Id = "WordProcessing", JobTypeId = JobType.JobTypeIds.SApp, Description = "Word Processing" }); + context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SApp, Description = "Other" }); + context.JobSubTypes.Add(new JobSubType { Id = "Appearance", JobTypeId = JobType.JobTypeIds.SOS, Description = "Appearance & Personalisation" }); + context.JobSubTypes.Add(new JobSubType { Id = "DisplaySettings", JobTypeId = JobType.JobTypeIds.SOS, Description = "Display Settings" }); + context.JobSubTypes.Add(new JobSubType { Id = "DriversIWB", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Interactive Whiteboard" }); + context.JobSubTypes.Add(new JobSubType { Id = "DriversPrintScan", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Printers/Scanners" }); + context.JobSubTypes.Add(new JobSubType { Id = "DriversSystem", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - System" }); + context.JobSubTypes.Add(new JobSubType { Id = "DriversOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Drivers - Other" }); + context.JobSubTypes.Add(new JobSubType { Id = "Group Policy", JobTypeId = JobType.JobTypeIds.SOS, Description = "Group Policy" }); + context.JobSubTypes.Add(new JobSubType { Id = "KeyboardMouseConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Keyboard/Mouse Configuration" }); + context.JobSubTypes.Add(new JobSubType { Id = "MalwareProtection", JobTypeId = JobType.JobTypeIds.SOS, Description = "Malware Protection" }); + context.JobSubTypes.Add(new JobSubType { Id = "NetworkDrives", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network Drives" }); + context.JobSubTypes.Add(new JobSubType { Id = "NetworkWired", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wired" }); + context.JobSubTypes.Add(new JobSubType { Id = "NetworkWireless", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Wireless" }); + context.JobSubTypes.Add(new JobSubType { Id = "NetworkOther", JobTypeId = JobType.JobTypeIds.SOS, Description = "Network - Other" }); + context.JobSubTypes.Add(new JobSubType { Id = "PatchUpdate", JobTypeId = JobType.JobTypeIds.SOS, Description = "Patches/Updates" }); + context.JobSubTypes.Add(new JobSubType { Id = "PowerManagement", JobTypeId = JobType.JobTypeIds.SOS, Description = "Power Management" }); + context.JobSubTypes.Add(new JobSubType { Id = "PrintersScanners", JobTypeId = JobType.JobTypeIds.SOS, Description = "Printers/Scanners" }); + context.JobSubTypes.Add(new JobSubType { Id = "SoundConfig", JobTypeId = JobType.JobTypeIds.SOS, Description = "Sound Configuration" }); + context.JobSubTypes.Add(new JobSubType { Id = "Other", JobTypeId = JobType.JobTypeIds.SOS, Description = "Other" }); + } + + // Feature Request 2012-04-27 by Elijah: https://disco.uservoice.com/forums/159707-feedback/suggestions/2803945-customisable-job-sub-types + #region "Optical Drive" Added + if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "OpticalDrive") == 0) + context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Optical Drive" }); + if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "OpticalDrive") == 0) + context.JobSubTypes.Add(new JobSubType { Id = "OpticalDrive", JobTypeId = JobType.JobTypeIds.HWar, Description = "Optical Drive" }); + #endregion + // End Feature Request + + // 2012-05-22 + #region "User Management" Added + if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.UMgmt) == 0) + { + context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Infringement, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Infringement }); + context.JobSubTypes.Add(new JobSubType { Id = JobSubType.UserManagementJobSubTypes.Contact, JobTypeId = JobType.JobTypeIds.UMgmt, Description = JobSubType.UserManagementJobSubTypes.Contact }); + } + #endregion + // End + + // 2012-05-29 - Audits + #region "Audit" Added + if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HMisc && jst.Id == "Audit") == 0) + context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.HMisc, Description = "Audit" }); + if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.SApp && jst.Id == "Audit") == 0) + context.JobSubTypes.Add(new JobSubType { Id = "Audit", JobTypeId = JobType.JobTypeIds.SApp, Description = "Audit" }); + #endregion + // End + + // Feature Request 2012-06-16 by James: https://disco.uservoice.com/forums/159707-feedback/suggestions/3002911-add-in-microphone-in-hardware-warranty-and-non-war + #region "Microphone" Added + if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HNWar && jst.Id == "Microphone") == 0) + context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HNWar, Description = "Microphone" }); + if (context.JobSubTypes.Count(jst => jst.JobTypeId == JobType.JobTypeIds.HWar && jst.Id == "Microphone") == 0) + context.JobSubTypes.Add(new JobSubType { Id = "Microphone", JobTypeId = JobType.JobTypeIds.HWar, Description = "Microphone" }); + #endregion + // End Feature Request + } + + private static void UpdateDeviceModelConfiguration(this DiscoDataContext context) + { + if (context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).Count() > 0) + { + var configurationItems = context.ConfigurationItems.Where(c => c.Scope.StartsWith("DeviceProfile:")).ToList(); + + var deviceProfiles = context.DeviceProfiles.ToDictionary(dp => dp.Id); + foreach (var configurationItem in configurationItems) + { + int profileId = int.Parse(configurationItem.Scope.Substring(configurationItem.Scope.IndexOf(":") + 1)); + DeviceProfile dp; + if (deviceProfiles.TryGetValue(profileId, out dp)) + { + switch (configurationItem.Key) + { + case "ComputerNameTemplate": + dp.ComputerNameTemplate = configurationItem.Value; + break; + case "DistributionType": + dp.DistributionType = (DeviceProfile.DistributionTypes)(int.Parse(configurationItem.Value)); + break; + case "OrganisationalUnit": + dp.OrganisationalUnit = configurationItem.Value; + break; + case "AllocateWirelessCertificate": + if (bool.Parse(configurationItem.Value)) + dp.CertificateProviderId = ""; + else + dp.CertificateProviderId = null; + break; + default: + continue; // Unknown Configuration Item - Leave in DB & Ignore + } + } + // Remove from DB + context.ConfigurationItems.Remove(configurationItem); + } + } + + } + + // Removed: 2013-01-14 G# + // private static void UpdateDeviceModelImageStorage(this DiscoDataContext dbContext) + // { + //#pragma warning disable 0618 + // var updateModels = dbContext.DeviceModels.Where(dm => dm.Image != null); + // if (updateModels.Count() > 0) + // { + // var dataStoreLocation = dbContext.ConfigurationItems.Where(ci => ci.Scope == "System" && ci.Key == "DataStoreLocation").Select(ci => ci.Value).FirstOrDefault(); + // if (!string.IsNullOrEmpty(dataStoreLocation) && System.IO.Directory.Exists(dataStoreLocation)) + // { + // var deviceModelImagesLocation = System.IO.Path.Combine(dataStoreLocation, "DeviceModelImages"); + // if (!System.IO.Directory.Exists(deviceModelImagesLocation)) + // System.IO.Directory.CreateDirectory(deviceModelImagesLocation); + // foreach (var model in updateModels) + // { + // var modelpath = System.IO.Path.Combine(deviceModelImagesLocation, string.Format("{0}.png", model.Id)); + + // if (model.Image != null && model.Image.Length > 0) + // { + // System.IO.File.WriteAllBytes(modelpath, model.Image); + // } + // model.Image = null; + // } + // } + // } + //#pragma warning restore 0618 + // } + + // Added: 2013-02-07 G# + // Fix previous problem with duplicate device models being created if new devices enrol at the same time + // http://www.discoict.com.au/forum/support/2013/2/duplicate-device-models.aspx + // Thanks to Michael Vorster for reporting this problem. + private static void UpdateDeviceModelDuplicates(this DiscoDataContext dbContext) + { + var deviceModels = dbContext.DeviceModels.ToList(); + var duplicateModels = deviceModels.GroupBy(g => string.Format("{0}|{1}", g.Manufacturer, g.Model)).Where(g => g.Count() > 1); + foreach (var duplicateModel in duplicateModels) + { + var primaryModel = duplicateModel.OrderBy(dm => dm.Id).First(); + + foreach (var redundantModel in duplicateModel.Where(m => m != primaryModel)) + { + foreach (var affectedDevice in dbContext.Devices.Where(d => d.DeviceModelId == redundantModel.Id)) + { + affectedDevice.DeviceModelId = primaryModel.Id; + } + if (!redundantModel.Description.EndsWith("** REDUNDANT **")) + { + if (redundantModel.Description.Length > 484) + redundantModel.Description = string.Format("{0} ** REDUNDANT **", redundantModel.Description.Substring(0, 484)); + else + redundantModel.Description = string.Format("{0} ** REDUNDANT **", redundantModel.Description); + } + } + } + } + // End Added: 2013-02-07 G# + } +}