public override bool Apply(DiscoDataContext Database, Device Device) { if (this.FieldAction == EntityState.Added || this.FieldAction == EntityState.Modified) { DeviceDetail detail = Database.DeviceDetails.FirstOrDefault(dd => dd.DeviceSerialNumber == Device.SerialNumber && dd.Scope == DeviceDetail.ScopeHardware && dd.Key == DeviceDetail.HardwareKeyLanMacAddress); if (detail == null) { detail = new DeviceDetail() { Device = Device, DeviceSerialNumber = Device.SerialNumber, Scope = DeviceDetail.ScopeHardware, Key = DeviceDetail.HardwareKeyLanMacAddress }; Database.DeviceDetails.Add(detail); } detail.Value = parsedValue; return true; } else { return false; } }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { friendlyValue = Value; // Validate if (string.IsNullOrWhiteSpace(Value)) this.parsedValue = Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId; else if (!int.TryParse(Value, out parsedValue)) return Error("The Profile Identifier must be a number"); var p = Cache.DeviceProfiles.FirstOrDefault(dp => dp.Id == parsedValue); if (p == null) return Error(string.Format("The identifier ({0}) does not match any Device Profile", Value)); friendlyValue = string.Format("{0} [{1}]", p.Description, p.Id); if (ExistingDevice == null) return Success(EntityState.Added); else if (ExistingDevice != null && ExistingDevice.DeviceProfileId != parsedValue) { var previousProfile = Cache.DeviceProfiles.FirstOrDefault(dp => dp.Id == ExistingDevice.DeviceProfileId); friendlyPreviousValue = string.Format("{0} [{1}]", previousProfile.Description, previousProfile.Id); return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { friendlyValue = Value; // Validate if (string.IsNullOrWhiteSpace(Value)) this.parsedValue = 1; // Default Model else if (!int.TryParse(Value, out parsedValue)) return Error("The Model Identifier must be a number"); var m = Cache.DeviceModels.FirstOrDefault(dm => dm.Id == parsedValue); if (m == null) return Error(string.Format("The identifier ({0}) does not match any Device Model", Value)); friendlyValue = string.Format("{0} [{1}]", m.Description, m.Id); if (ExistingDevice == null) return Success(EntityState.Added); else if (ExistingDevice != null && ExistingDevice.DeviceModelId != parsedValue) { friendlyPreviousValue = null; if (ExistingDevice.DeviceModelId.HasValue) { var previousModel = Cache.DeviceModels.FirstOrDefault(dm => dm.Id == ExistingDevice.DeviceModelId.Value); friendlyPreviousValue = string.Format("{0} [{1}]", previousModel.Description, previousModel.Id); } return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { if (string.IsNullOrWhiteSpace(Value)) parsedValue = null; else { parsedValue = Value.Trim(); } if (ExistingDevice == null && parsedValue != null) return Success(EntityState.Added); else if (ExistingDevice != null) { var detail = ExistingDevice.DeviceDetails.FirstOrDefault(dd => dd.Scope == DeviceDetail.ScopeHardware && dd.Key == DeviceDetail.HardwareKeyLanMacAddress); if (detail == null && parsedValue == null) return Success(EntityState.Unchanged); else if (detail == null && parsedValue != null) { return Success(EntityState.Modified); } else if (detail.Value != parsedValue) { previousValue = detail.Value; return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); } else return Success(EntityState.Unchanged); }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { // Validate if (string.IsNullOrWhiteSpace(Value)) return Error("The Device Serial Number is required"); else { parsedValue = Value.Trim(); if (parsedValue.Length > maxLength) return Error($"Cannot be more than {maxLength} characters"); if (parsedValue.Contains(@"/")) return Error(@"The '/' character is not allowed."); if (parsedValue.Contains(@"\")) return Error(@"The '\' character is not allowed."); } // Duplicate var duplicate = Context.RawData .Take(RecordIndex) .Select((r, i) => Tuple.Create(i, ParseRawDeviceSerialNumber(r[Context.HeaderDeviceSerialNumberIndex]))) .Where(r => IsDeviceSerialNumberValid(r.Item2)) .FirstOrDefault(r => r.Item2.Equals(parsedValue, StringComparison.OrdinalIgnoreCase)); if (duplicate != null) return Error($"This Device Serial Number was already present on Row {duplicate.Item1 + 1}"); // No action required return Success(EntityState.Unchanged); }
public static string GetActiveDirectoryStringValue(Device Device, string PropertyName, int Index = 0) { var objectValue = GetActiveDirectoryObjectValue(Device, PropertyName, Index); string stringValue = objectValue as string; if (stringValue == null && objectValue != null) stringValue = objectValue.ToString(); return stringValue; }
public static object GetActiveDirectoryObjectValue(Device Device, string PropertyName, int Index = 0) { var adMachineAccount = Device.ActiveDirectoryAccount(PropertyName); if (adMachineAccount != null) return adMachineAccount.GetPropertyValues<object>(PropertyName).Skip(Index).FirstOrDefault(); else return null; }
public bool Apply(DiscoDataContext Database) { if (RecordAction == EntityState.Detached || !HasError) { Device device; if (RecordAction == EntityState.Unchanged) { // Unchanged - No Action Required return false; } else if (RecordAction == EntityState.Modified) { device = Database.Devices.Find(this.DeviceSerialNumber); } else if (RecordAction == EntityState.Added) { // Use 'Add Device Offline' default if available var deviceProfileId = Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId; if (deviceProfileId == 0) { deviceProfileId = Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId; } // Create Device device = new Device() { SerialNumber = DeviceSerialNumber.ToUpper(), CreatedDate = DateTime.Now, AllowUnauthenticatedEnrol = true, DeviceProfileId = deviceProfileId, DeviceModelId = 1 // Default 'Unknown Device Model' }; Database.Devices.Add(device); } else { // Invalid State return false; } bool changesMade = (RecordAction == EntityState.Added); foreach (var field in Fields.Cast<DeviceImportFieldBase>()) { changesMade = field.Apply(Database, device) || changesMade; } // Commit Changes if (changesMade) Database.SaveChanges(); return changesMade; } // Record has Errors return false; }
public static bool UpdateLastNetworkLogonDate(Device Device) { const string ldapFilterTemplate = "(&(objectCategory=Computer)(sAMAccountName={0}))"; string[] ldapProperties = new string[] { "lastLogon", "lastLogonTimestamp" }; DateTime? lastLogon = null; if (!string.IsNullOrEmpty(Device.DeviceDomainId) && Device.DeviceDomainId.Contains('\\')) { var context = ActiveDirectory.Context; string deviceSamAccountName; ADDomain deviceDomain; ActiveDirectory.ParseDomainAccountId(Device.DeviceDomainId + "$", out deviceSamAccountName, out deviceDomain); var ldapFilter = string.Format(ldapFilterTemplate, ADHelpers.EscapeLdapQuery(deviceSamAccountName)); IEnumerable<ADDomainController> domainControllers; if (context.SearchAllForestServers) domainControllers = deviceDomain.GetAllReachableDomainControllers(); else domainControllers = deviceDomain.GetReachableSiteDomainControllers(); lastLogon = domainControllers.Select(dc => { var result = dc.SearchEntireDomain(ldapFilter, ldapProperties, ActiveDirectory.SingleSearchResult).FirstOrDefault(); if (result != null) { long lastLogonValue = default(long); long lastLogonTimestampValue = default(long); lastLogonValue = result.Value<long>("lastLogon"); lastLogonTimestampValue = result.Value<long>("lastLogonTimestamp"); long highedValue = Math.Max(lastLogonValue, lastLogonTimestampValue); if (highedValue > 0) return (DateTime?)new DateTime((DateTime.FromFileTime(highedValue).Ticks / 10000000L) * 10000000L); else return null; } return null; }).Where(dt => dt.HasValue).Max(); } if (lastLogon.HasValue && ( !Device.LastNetworkLogonDate.HasValue || Device.LastNetworkLogonDate.Value < lastLogon )) { Device.LastNetworkLogonDate = lastLogon; return true; } return false; }
public override bool Apply(DiscoDataContext Database, Device Device) { if (this.FieldAction == EntityState.Added || this.FieldAction == EntityState.Modified) { Device.DeviceModelId = this.parsedValue; return true; } else { return false; } }
public override bool Apply(DiscoDataContext Database, Device Device) { if (this.FieldAction == EntityState.Modified || this.FieldAction == EntityState.Added) { Device.AllowUnauthenticatedEnrol = parsedValue; return true; } else { return false; } }
public override bool Apply(DiscoDataContext Database, Device Device) { if (this.FieldAction == EntityState.Modified) { // Decommission or Recommission Device Device.DecommissionedDate = this.parsedValue; if (setReason) Device.DecommissionReason = this.parsedValue.HasValue ? (DecommissionReasons?)DecommissionReasons.EndOfLife : null; return true; } else { return false; } }
public static int GetActiveDirectoryIntegerValue(Device Device, string PropertyName, int Index = 0) { var objectValue = GetActiveDirectoryObjectValue(Device, PropertyName, Index); if (objectValue == null) return default(int); else { int intValue; try { intValue = (int)Convert.ChangeType(objectValue, typeof(int)); } catch (Exception) { throw; } return intValue; } }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { friendlyValue = Value; // Validate if (string.IsNullOrWhiteSpace(Value)) this.parsedValue = null; // Default = null else { int valueInt; if (int.TryParse(Value, out valueInt)) this.parsedValue = valueInt; else return Error("The Batch Identifier must be a number"); } if (this.parsedValue.HasValue) { var b = Cache.DeviceBatches.FirstOrDefault(db => db.Id == parsedValue); if (b == null) return Error(string.Format("The identifier ({0}) does not match any Device Batch", Value)); friendlyValue = string.Format("{0} [{1}]", b.Name, b.Id); } else friendlyValue = null; if (ExistingDevice == null) return Success(EntityState.Added); else if (ExistingDevice != null && ExistingDevice.DeviceBatchId != parsedValue) { DeviceBatch previousBatch = null; if (ExistingDevice.DeviceBatchId.HasValue) previousBatch = Cache.DeviceBatches.FirstOrDefault(db => db.Id == ExistingDevice.DeviceBatchId.Value); if (previousBatch != null) friendlyPreviousValue = string.Format("{0} [{1}]", previousBatch.Name, previousBatch.Id); return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { if (string.IsNullOrWhiteSpace(Value)) { rawValue = null; parsedValue = null; } else { DecommissionReasons valueReason; if (!decommissionReasonsMap.Value.TryGetValue(Value.Trim(), out valueReason)) { rawValue = Value.Trim(); return Error("Cannot parse the value as a Decommission Reason"); } else { parsedValue = valueReason; } } if (parsedValue.HasValue && !Values.ContainsKey(DeviceImportFieldTypes.DeviceDecommissionedDate)) { string errorMessage; if (!DeviceDecommissionedDateImportField.CanDecommissionDevice(ExistingDevice, Values, out errorMessage)) return Error(errorMessage); setDate = true; } else if (parsedValue.HasValue && string.IsNullOrWhiteSpace(Values[DeviceImportFieldTypes.DeviceDecommissionedDate])) { setDate = true; } if (ExistingDevice != null && ExistingDevice.DecommissionReason != parsedValue) { previousValue = ExistingDevice.DecommissionReason; return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { if (string.IsNullOrWhiteSpace(Value)) parsedValue = null; else { parsedValue = Value.Trim(); if (parsedValue.Length > 250) return Error("Cannot be more than 250 characters"); } if (ExistingDevice == null && parsedValue != null) return Success(EntityState.Added); else if (ExistingDevice != null && ExistingDevice.Location != parsedValue) { previousValue = ExistingDevice.Location; return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { friendlyValue = Value; if (!ParseBoolean(Value, out parsedValue)) return Error("Expected a Boolean expression (True, 1, Yes, On, False, 0, No, Off)"); friendlyValue = parsedValue.ToString(); if (parsedValue == true) { // Check Decommissioned bool? importDecommissioning = null; if (Values.ContainsKey(DeviceImportFieldTypes.DeviceDecommissionedDate) || Values.ContainsKey(DeviceImportFieldTypes.DeviceDecommissionedReason)) importDecommissioning = Values.ContainsKey(DeviceImportFieldTypes.DeviceDecommissionedDate) && !string.IsNullOrWhiteSpace(Values[DeviceImportFieldTypes.DeviceDecommissionedDate]) || Values.ContainsKey(DeviceImportFieldTypes.DeviceDecommissionedReason) && !string.IsNullOrWhiteSpace(Values[DeviceImportFieldTypes.DeviceDecommissionedReason]); if (importDecommissioning.HasValue && importDecommissioning.Value) return Error("Cannot enrol a device being decommissioned"); if (ExistingDevice != null && ExistingDevice.DecommissionedDate.HasValue && !importDecommissioning.HasValue) { return Error("Cannot enrol a decommissioned device"); } } if (ExistingDevice == null && parsedValue != false) // Default: True { return Success(EntityState.Added); } else if (ExistingDevice != null && ExistingDevice.AllowUnauthenticatedEnrol != parsedValue) { friendlyPreviousValue = ExistingDevice.AllowUnauthenticatedEnrol.ToString(); return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); }
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, DeviceImportContext Context, int RecordIndex, string DeviceSerialNumber, Device ExistingDevice, Dictionary<DeviceImportFieldTypes, string> Values, string Value) { if (string.IsNullOrWhiteSpace(Value)) { rawValue = null; parsedValue = null; } else { DateTime valueDateTime; if (!DateTime.TryParse(Value.Trim(), CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AssumeLocal, out valueDateTime)) { rawValue = Value.Trim(); return Error(string.Format("Cannot parse the value as a Date/Time using {0} culture (system default).", CultureInfo.CurrentCulture.Name)); } else { // Accuracy to the second (remove any milliseconds) parsedValue = new DateTime((valueDateTime.Ticks / 10000000L) * 10000000L); } } string errorMessage; if (parsedValue.HasValue && !CanDecommissionDevice(ExistingDevice, Values, out errorMessage)) return Error(errorMessage); setReason = !Values.ContainsKey(DeviceImportFieldTypes.DeviceDecommissionedReason) || (parsedValue.HasValue && string.IsNullOrWhiteSpace(Values[DeviceImportFieldTypes.DeviceDecommissionedReason])); if (ExistingDevice != null && ExistingDevice.DecommissionedDate != parsedValue) { previousValue = ExistingDevice.DecommissionedDate; return Success(EntityState.Modified); } else return Success(EntityState.Unchanged); }
public abstract ProvisionAuthorityCertificatesResult ProvisionAuthorityCertificates(DiscoDataContext Database, Device Device, Enrol Enrolment);
public static bool CanDecommissionDevice(Device Device, Dictionary<DeviceImportFieldTypes, string> Values, out string ErrorMessage) { if (Device == null) { ErrorMessage = "Cannot decommission new devices"; return false; } // Check device is assigned (or being removed in this import) if ((!Values.ContainsKey(DeviceImportFieldTypes.AssignedUserId) && Device.AssignedUserId != null) || (Values.ContainsKey(DeviceImportFieldTypes.AssignedUserId) && !string.IsNullOrWhiteSpace(Values[DeviceImportFieldTypes.AssignedUserId]))) { if (Device.AssignedUserId != null) ErrorMessage = string.Format("The device is assigned to a user ({0} [{1}]) and cannot be decommissioned", Device.AssignedUser.DisplayName, Device.AssignedUser.UserId); else ErrorMessage = string.Format("The device is being assigned to a user ({0}) and cannot be decommissioned", Values[DeviceImportFieldTypes.AssignedUserId]); return false; } // Check device doesn't have any open jobs var openJobCount = Device.Jobs.Count(j => !j.ClosedDate.HasValue); if (openJobCount > 0) { ErrorMessage = string.Format("The device is associated with {0} open job{1} and cannot be decommissioned", openJobCount, openJobCount == 1 ? null : "s"); return false; } ErrorMessage = null; return true; }
private void UpdateDeviceProfileId(Device device, string DeviceProfileId) { if (!string.IsNullOrEmpty(DeviceProfileId)) { int pId; if (int.TryParse(DeviceProfileId, out pId)) { var p = Database.DeviceProfiles.Find(pId); if (p != null) { device.DeviceProfileId = p.Id; device.DeviceProfile = p; // Update AD Account if (ActiveDirectory.IsValidDomainAccountId(device.DeviceDomainId)) { var adMachineAccount = ActiveDirectory.RetrieveADMachineAccount(device.DeviceDomainId); if (adMachineAccount != null) adMachineAccount.SetDescription(device); } Database.SaveChanges(); return; } } } throw new Exception("Invalid Device Profile Id"); }
private void UpdateDeviceBatchId(Device device, string DeviceBatchId) { if (!string.IsNullOrEmpty(DeviceBatchId)) { int bId; if (int.TryParse(DeviceBatchId, out bId)) { var b = Database.DeviceBatches.Find(bId); if (b != null) { device.DeviceBatchId = b.Id; device.DeviceBatch = b; Database.SaveChanges(); return; } } } else { // Null Id - No Batch device.DeviceBatchId = null; device.DeviceBatch = null; Database.SaveChanges(); return; } throw new Exception("Invalid Device Batch Id"); }
private void UpdateAssetNumber(Device device, string AssetNumber) { if (string.IsNullOrWhiteSpace(AssetNumber)) device.AssetNumber = null; else device.AssetNumber = AssetNumber.Trim(); Database.SaveChanges(); }
private void UpdateLocation(Device device, string Location) { if (string.IsNullOrWhiteSpace(Location)) device.Location = null; else device.Location = Location.Trim(); Database.SaveChanges(); }
public static Job Create(DiscoDataContext Database, Device device, User user, JobType type, List<JobSubType> subTypes, User initialTech, bool addAutoQueues = true) { Job j = new Job() { JobType = type, OpenedTechUserId = initialTech.UserId, OpenedTechUser = initialTech, OpenedDate = DateTime.Now }; // Device if (device != null) { j.Device = device; j.DeviceSerialNumber = device.SerialNumber; } // User if (user != null) { j.User = user; j.UserId = user.UserId; } // Sub Types List<JobSubType> jobSubTypes = subTypes.ToList(); j.JobSubTypes = jobSubTypes; Database.Jobs.Add(j); // Job Queues if (addAutoQueues) { var queues = from st in subTypes from jq in st.JobQueues group st by jq into g select new { queue = g.Key, subTypes = g }; foreach (var queue in queues) { var commentBuilder = new StringBuilder("Automatically added by:").AppendLine(); foreach (var subType in queue.subTypes) { commentBuilder.AppendLine().Append("* ").Append(subType.Description); } var jqj = new JobQueueJob() { JobQueueId = queue.queue.Id, Job = j, AddedDate = DateTime.Now, AddedUserId = initialTech.UserId, AddedComment = commentBuilder.ToString(), SLAExpiresDate = queue.queue.DefaultSLAExpiry.HasValue ? (DateTime?)DateTime.Now.AddMinutes(queue.queue.DefaultSLAExpiry.Value) : null, Priority = JobQueuePriority.Normal }; Database.JobQueueJobs.Add(jqj); } } switch (type.Id) { case JobType.JobTypeIds.HWar: Database.JobMetaWarranties.Add(new JobMetaWarranty() { Job = j }); break; case JobType.JobTypeIds.HNWar: Database.JobMetaNonWarranties.Add(new JobMetaNonWarranty() { Job = j }); if (device != null) { // Add Job Components var components = Database.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var addedComponents = new List<DeviceComponent>(); foreach (var c in components) { if (c.JobSubTypes.Count == 0) { // No Filter addedComponents.Add(c); } else { foreach (var st in c.JobSubTypes) { foreach (var jst in jobSubTypes) { if (st.JobTypeId == jst.JobTypeId && st.Id == jst.Id) { addedComponents.Add(c); break; } } if (addedComponents.Contains(c)) break; } } } foreach (var c in addedComponents) Database.JobComponents.Add(new JobComponent() { Job = j, TechUserId = initialTech.UserId, Cost = c.Cost, Description = c.Description }); } break; } return j; }
private void UpdateAssignedUserId(Device device, string UserId) { var daus = Database.DeviceUserAssignments.Where(m => m.DeviceSerialNumber == device.SerialNumber && m.UnassignedDate == null); User u = null; if (!string.IsNullOrEmpty(UserId)) { u = UserService.GetUser(UserId, Database, true); if (u == null) throw new Exception("Invalid Username"); } device.AssignDevice(Database, u); Database.SaveChanges(); }
private void UpdateAllowUnauthenticatedEnrol(Device device, string AllowUnauthenticatedEnrol) { bool bAllowUnauthenticatedEnrol; if (string.IsNullOrEmpty(AllowUnauthenticatedEnrol) || !bool.TryParse(AllowUnauthenticatedEnrol, out bAllowUnauthenticatedEnrol)) { throw new Exception("Invalid AllowUnauthenticatedEnrol Value"); } if (device.AllowUnauthenticatedEnrol != bAllowUnauthenticatedEnrol) { device.AllowUnauthenticatedEnrol = bAllowUnauthenticatedEnrol; Database.SaveChanges(); } }
private void UpdateDetailACAdapter(Device device, string ACAdapter) { if (string.IsNullOrWhiteSpace(ACAdapter)) device.DeviceDetails.ACAdapter(device, null); else device.DeviceDetails.ACAdapter(device, ACAdapter.Trim()); Database.SaveChanges(); }
private void UpdateDetailBattery(Device device, string Battery) { if (string.IsNullOrWhiteSpace(Battery)) device.DeviceDetails.Battery(device, null); else device.DeviceDetails.Battery(device, Battery.Trim()); Database.SaveChanges(); }
private void UpdateDetailKeyboard(Device device, string Keyboard) { if (string.IsNullOrWhiteSpace(Keyboard)) device.DeviceDetails.Keyboard(device, null); else device.DeviceDetails.Keyboard(device, Keyboard.Trim()); Database.SaveChanges(); }