refactor: simplify export metadata construction

This commit is contained in:
Gary Sharp
2025-02-07 16:10:15 +11:00
parent 67f1c2a5d1
commit 2fce645066
30 changed files with 1432 additions and 1484 deletions
+2 -1
View File
@@ -49,8 +49,9 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="BI\Config\OrganisationAddress.cs" /> <Compile Include="BI\Config\OrganisationAddress.cs" />
<Compile Include="Exporting\ExportFieldMetadata.cs" /> <Compile Include="Exporting\ExportMetadataField.cs" />
<Compile Include="Exporting\ExportFormat.cs" /> <Compile Include="Exporting\ExportFormat.cs" />
<Compile Include="Exporting\ExportMetadata.cs" />
<Compile Include="Exporting\IExportRecord.cs" /> <Compile Include="Exporting\IExportRecord.cs" />
<Compile Include="Repository\Device\Flag\DeviceFlag.cs" /> <Compile Include="Repository\Device\Flag\DeviceFlag.cs" />
<Compile Include="Repository\Device\Flag\DeviceFlagAssignment.cs" /> <Compile Include="Repository\Device\Flag\DeviceFlagAssignment.cs" />
@@ -1,27 +0,0 @@
using System;
namespace Disco.Models.Exporting
{
public class ExportFieldMetadata<T> where T : IExportRecord
{
public string Name { get; set; }
public string ColumnName { get; set; }
public Type ValueType { get; set; }
public Func<T, object> Accessor { get; set; }
public Func<object, string> CsvEncoder { get; set; }
public ExportFieldMetadata(string name, Type valueType, Func<T, object> accessor, Func<object, string> csvEncoder)
{
Name = name;
ValueType = valueType;
Accessor = accessor;
CsvEncoder = csvEncoder;
}
public ExportFieldMetadata(string name, string columnName, Type valueType, Func<T, object> accessor, Func<object, string> csvEncoder)
: this(name, valueType, accessor, csvEncoder)
{
ColumnName = columnName;
}
}
}
+10
View File
@@ -0,0 +1,10 @@
using System.Collections.Generic;
namespace Disco.Models.Exporting
{
public class ExportMetadata<T>
: List<ExportMetadataField<T>> where T : IExportRecord
{
public List<string> IgnoreShortNames { get; } = new List<string>();
}
}
@@ -0,0 +1,20 @@
using System;
namespace Disco.Models.Exporting
{
public class ExportMetadataField<T> where T : IExportRecord
{
public string ColumnName { get; }
public Type ValueType { get; }
public Func<T, object> Accessor { get; }
public Func<object, string> CsvEncoder { get; }
public ExportMetadataField(string columnName, Type valueType, Func<T, object> accessor, Func<object, string> csvEncoder)
{
ColumnName = columnName;
ValueType = valueType;
Accessor = accessor;
CsvEncoder = csvEncoder;
}
}
}
@@ -56,6 +56,8 @@ namespace Disco.Models.Services.Users.UserFlags
public bool UserEmailAddress { get; set; } public bool UserEmailAddress { get; set; }
[Display(ShortName = "User", Name = "Custom Details", Description = "The custom details provided by plugins for the user assigned to the user flag")] [Display(ShortName = "User", Name = "Custom Details", Description = "The custom details provided by plugins for the user assigned to the user flag")]
public bool UserDetailCustom { get; set; } public bool UserDetailCustom { get; set; }
public bool HasAssignedUserDetails()
=> UserDisplayName || UserSurname || UserGivenName || UserPhoneNumber || UserEmailAddress || UserDetailCustom;
public static UserFlagExportOptions DefaultOptions() public static UserFlagExportOptions DefaultOptions()
{ {
+470
View File
@@ -0,0 +1,470 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Repository;
using Disco.Models.Services.Devices;
using Disco.Models.Services.Exporting;
using Disco.Services.Exporting;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Text.Json.Serialization;
namespace Disco.Services.Devices
{
public class DeviceExport : IExport<DeviceExportOptions, DeviceExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public DeviceExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "DeviceExport";
public string ExcelWorksheetName { get; } = "DeviceExport";
public string ExcelTableName { get; } = "Devices";
[JsonConstructor]
private DeviceExport()
{
}
public DeviceExport(string name, string description, bool timestampSuffix, DeviceExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public DeviceExport(DeviceExportOptions options)
: this("Device Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus taskStatus)
=> Exporter.Export(this, database, taskStatus);
private IQueryable<Device> BuildFilteredRecords(DiscoDataContext database)
{
var query = database.Devices
.Include(d => d.AssignedUser.UserDetails)
.Include(d => d.DeviceDetails);
switch (Options.ExportType)
{
case DeviceExportTypes.All:
break;
case DeviceExportTypes.Batch:
if (Options.ExportTypeTargetId.HasValue && Options.ExportTypeTargetId.Value > 0)
query = query.Where(d => d.DeviceBatchId != Options.ExportTypeTargetId);
else
query = query.Where(d => d.DeviceBatchId != null);
break;
case DeviceExportTypes.Model:
query = query.Where(d => d.DeviceModelId == Options.ExportTypeTargetId);
break;
case DeviceExportTypes.Profile:
query = query.Where(d => d.DeviceProfileId == Options.ExportTypeTargetId);
break;
default:
throw new ArgumentException($"Unknown Device Export Type '{Options.ExportType}'", nameof(Options.ExportType));
}
return query;
}
public List<DeviceExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus taskStatus)
{
var query = BuildFilteredRecords(database);
// Update Users
if (Options.AssignedUserDisplayName ||
Options.AssignedUserSurname ||
Options.AssignedUserGivenName ||
Options.AssignedUserPhoneNumber ||
Options.AssignedUserEmailAddress)
{
taskStatus.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Where(d => d.AssignedUserId != null).Select(d => d.AssignedUserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database, true);
}
catch (Exception) { } // Ignore Errors
}
}
// Update Last Network Logon Date
if (Options.DeviceLastNetworkLogon)
{
taskStatus.UpdateStatus(15, "Refreshing device last network logon dates from Active Directory");
try
{
Interop.ActiveDirectory.ADNetworkLogonDatesUpdateTask.UpdateLastNetworkLogonDates(database, ScheduledTaskMockStatus.Create("UpdateLastNetworkLogonDates"));
database.SaveChanges();
}
catch (Exception) { } // Ignore Errors
}
taskStatus.UpdateStatus(25, "Gathering database records");
var records = query.Select(d => new DeviceExportRecord()
{
Device = d,
DeviceDetails = d.DeviceDetails,
ModelId = d.DeviceModelId,
ModelDescription = d.DeviceModel.Description,
ModelManufacturer = d.DeviceModel.Manufacturer,
ModelModel = d.DeviceModel.Model,
ModelType = d.DeviceModel.ModelType,
BatchId = d.DeviceBatchId,
BatchName = d.DeviceBatch.Name,
BatchPurchaseDate = d.DeviceBatch.PurchaseDate,
BatchSupplier = d.DeviceBatch.Supplier,
BatchUnitCost = d.DeviceBatch.UnitCost,
BatchWarrantyValidUntilDate = d.DeviceBatch.WarrantyValidUntil,
BatchInsuredDate = d.DeviceBatch.InsuredDate,
BatchInsuranceSupplier = d.DeviceBatch.InsuranceSupplier,
BatchInsuredUntilDate = d.DeviceBatch.InsuredUntil,
ProfileId = d.DeviceProfileId,
ProfileName = d.DeviceProfile.Name,
ProfileShortName = d.DeviceProfile.ShortName,
DeviceUserAssignment = d.DeviceUserAssignments.Where(dua => dua.UnassignedDate == null).FirstOrDefault(),
AssignedUser = d.AssignedUser,
AssignedUserDetails = d.AssignedUser.UserDetails,
JobsTotalCount = d.Jobs.Count(),
JobsOpenCount = d.Jobs.Count(j => j.ClosedDate == null),
AttachmentsCount = d.DeviceAttachments.Count(),
DeviceCertificates = d.DeviceCertificates.Where(dc => dc.Enabled).OrderByDescending(dc => dc.AllocatedDate)
}).ToList();
// materialize device details
records.ForEach(r =>
{
if (Options.DetailBios)
r.DeviceDetailBios = r.DeviceDetails.Bios();
if (Options.DetailBaseBoard)
r.DeviceDetailBaseBoard = r.DeviceDetails.BaseBoard();
if (Options.DetailComputerSystem)
r.DeviceDetailComputerSystem = r.DeviceDetails.ComputerSystem();
if (Options.DetailProcessors)
r.DeviceDetailProcessors = r.DeviceDetails.Processors();
if (Options.DetailMemory)
r.DeviceDetailPhysicalMemory = r.DeviceDetails.PhysicalMemory();
if (Options.DetailDiskDrives)
r.DeviceDetailDiskDrives = r.DeviceDetails.DiskDrives();
if (Options.DetailLanAdapters || Options.DetailWLanAdapters)
{
r.DeviceDetailNetworkAdapters = r.DeviceDetails.NetworkAdapters();
if (r.DeviceDetailNetworkAdapters == null)
{
r.DeviceDetailLanMacAddresses = r.DeviceDetails.LanMacAddress()?.Split(';').Select(a => a.Trim()).ToList();
r.DeviceDetailWlanMacAddresses = r.DeviceDetails.WLanMacAddress()?.Split(';').Select(a => a.Trim()).ToList();
}
}
if (Options.DetailBatteries)
r.DeviceDetailBatteries = r.DeviceDetails.Batteries();
if (Options.AssignedUserDetailCustom && r.AssignedUser != null)
{
var detailsService = new DetailsProviderService(database);
r.AssignedUserCustomDetails = detailsService.GetDetails(r.AssignedUser);
}
});
return records;
}
public ExportMetadata<DeviceExportRecord> BuildMetadata(DiscoDataContext database, List<DeviceExportRecord> records, IScheduledTaskStatus taskStatus)
{
var metadata = new ExportMetadata<DeviceExportRecord>();
metadata.IgnoreShortNames.Add("Device");
metadata.IgnoreShortNames.Add("Details");
// Device
metadata.Add(Options, o => o.DeviceSerialNumber, r => r.Device.SerialNumber);
metadata.Add(Options, o => o.DeviceAssetNumber, r => r.Device.AssetNumber);
metadata.Add(Options, o => o.DeviceLocation, r => r.Device.Location);
metadata.Add(Options, o => o.DeviceComputerName, r => r.Device.DeviceDomainId);
metadata.Add(Options, o => o.DeviceLastNetworkLogon, r => r.Device.LastNetworkLogonDate);
metadata.Add(Options, o => o.DeviceCreatedDate, r => r.Device.CreatedDate);
metadata.Add(Options, o => o.DeviceFirstEnrolledDate, r => r.Device.EnrolledDate);
metadata.Add(Options, o => o.DeviceLastEnrolledDate, r => r.Device.LastEnrolDate);
metadata.Add(Options, o => o.DeviceAllowUnauthenticatedEnrol, r => r.Device.AllowUnauthenticatedEnrol);
metadata.Add(Options, o => o.DeviceDecommissionedDate, r => r.Device.DecommissionedDate);
metadata.Add(Options, o => o.DeviceDecommissionedReason, r => r.Device.DecommissionReason?.ToString());
// Model
metadata.Add(Options, o => o.ModelId, r => r.ModelId);
metadata.Add(Options, o => o.ModelDescription, r => r.ModelDescription);
metadata.Add(Options, o => o.ModelManufacturer, r => r.ModelManufacturer);
metadata.Add(Options, o => o.ModelModel, r => r.ModelModel);
metadata.Add(Options, o => o.ModelType, r => r.ModelType);
// Batch
metadata.Add(Options, o => o.BatchId, r => r.BatchId);
metadata.Add(Options, o => o.BatchName, r => r.BatchName);
metadata.Add(Options, o => o.BatchPurchaseDate, r => r.BatchPurchaseDate);
metadata.Add(Options, o => o.BatchSupplier, r => r.BatchSupplier);
metadata.Add(Options, o => o.BatchUnitCost, r => r.BatchUnitCost, Exporter.CsvEncoders.NullableCurrencyEncoder);
metadata.Add(Options, o => o.BatchWarrantyValidUntilDate, r => r.BatchWarrantyValidUntilDate);
metadata.Add(Options, o => o.BatchInsuredDate, r => r.BatchInsuredDate);
metadata.Add(Options, o => o.BatchInsuranceSupplier, r => r.BatchInsuranceSupplier);
metadata.Add(Options, o => o.BatchInsuredUntilDate, r => r.BatchInsuredUntilDate);
// Profile
metadata.Add(Options, o => o.ProfileId, r => r.ProfileId);
metadata.Add(Options, o => o.ProfileName, r => r.ProfileName);
metadata.Add(Options, o => o.ProfileShortName, r => r.ProfileShortName);
// User
metadata.Add(Options, o => o.AssignedUserId, r => r.AssignedUser?.UserId);
metadata.Add(Options, o => o.AssignedUserDate, r => r.DeviceUserAssignment?.AssignedDate);
metadata.Add(Options, o => o.AssignedUserDisplayName, r => r.AssignedUser?.DisplayName);
metadata.Add(Options, o => o.AssignedUserSurname, r => r.AssignedUser?.Surname);
metadata.Add(Options, o => o.AssignedUserGivenName, r => r.AssignedUser?.GivenName);
metadata.Add(Options, o => o.AssignedUserPhoneNumber, r => r.AssignedUser?.PhoneNumber);
metadata.Add(Options, o => o.AssignedUserEmailAddress, r => r.AssignedUser?.EmailAddress);
// User Custom Details
if (Options.AssignedUserDetailCustom)
{
var keys = records.Where(r => r.AssignedUserCustomDetails != null).SelectMany(r => r.AssignedUserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
foreach (var key in keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
metadata.Add(key, r => r.AssignedUserCustomDetails != null && r.AssignedUserCustomDetails.TryGetValue(key, out var value) ? value : null);
}
}
// Jobs
metadata.Add(Options, o => o.JobsTotalCount, r => r.JobsTotalCount);
metadata.Add(Options, o => o.JobsOpenCount, r => r.JobsOpenCount);
// Attachments
metadata.Add(Options, o => o.AttachmentsCount, r => r.AttachmentsCount);
// Certificates
if (Options.Certificates)
{
var certificateMaxCount = Math.Max(1, records.Max(r => r.DeviceCertificates?.Count() ?? 0));
for (int i = 0; i < certificateMaxCount; i++)
{
var v = i;
var index = i + 1;
metadata.Add($"Certificate{index}Name", r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.Name);
metadata.Add($"Certificate{index}AllocationDate", r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.AllocatedDate);
metadata.Add($"Certificate{index}ExpirationDate", r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.ExpirationDate);
metadata.Add($"Certificate{index}ProviderId", r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.ProviderId);
}
}
// Details
// BIOS
if (Options.DetailBios)
{
metadata.Add("BIOS Manufacturer", r => r.DeviceDetailBios?.FirstOrDefault()?.Manufacturer);
metadata.Add("BIOS Serial Number", r => r.DeviceDetailBios?.FirstOrDefault()?.SerialNumber);
metadata.Add("BIOS Version", r =>
{
var bios = r.DeviceDetailBios?.FirstOrDefault();
if (bios?.SMBIOSBIOSVersion != null)
return $"{bios.SMBIOSBIOSVersion} {bios.SMBIOSMajorVersion}.{bios.SMBIOSMinorVersion}";
else
return null;
});
metadata.Add("BIOS System Version", r =>
{
var bios = r.DeviceDetailBios?.FirstOrDefault();
if (bios?.SystemBiosMajorVersion.HasValue ?? false)
return $"{bios.SystemBiosMajorVersion}.{bios.SystemBiosMinorVersion}";
else
return null;
});
metadata.Add("BIOS Release Date", r => r.DeviceDetailBios?.FirstOrDefault()?.ReleaseDate);
}
// Base Board
if (Options.DetailBaseBoard)
{
metadata.Add("Base Board Manufacturer", r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Manufacturer);
metadata.Add("Base Board Model", r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Model);
metadata.Add("Base Board Product", r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Product);
metadata.Add("Base Board Part Number", r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.PartNumber);
metadata.Add("Base Board SKU", r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.SKU);
metadata.Add("Base Board Serial Number", r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.SerialNumber);
metadata.Add("Base Board Config Options", r =>
{
var baseBoard = r.DeviceDetailBaseBoard?.FirstOrDefault();
if (baseBoard?.ConfigOptions != null)
return string.Join("; ", baseBoard.ConfigOptions);
else
return null;
});
metadata.Add("Base Board Version", r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Version);
}
// Computer System
if (Options.DetailComputerSystem)
{
metadata.Add("System Description", r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.Description);
metadata.Add("System Form Factor", r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.PCSystemType);
metadata.Add("System Type", r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.SystemType);
metadata.Add("System Primary Owner Name", r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.PrimaryOwnerName);
metadata.Add("System Primary Owner Contact", r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.PrimaryOwnerContact);
metadata.Add("System Chassis SKU", r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.ChassisSKUNumber);
metadata.Add("System SKU", r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.SystemSKUNumber);
metadata.Add("System OEM Reference", r =>
{
var computerSystem = r.DeviceDetailComputerSystem?.FirstOrDefault();
if (computerSystem?.OEMStringArray != null)
return string.Join("; ", computerSystem.OEMStringArray);
else
return null;
});
metadata.Add("System Time Zone", r =>
{
var computerSystem = r.DeviceDetailComputerSystem?.FirstOrDefault();
if (computerSystem?.CurrentTimeZone.HasValue ?? false)
return $"{computerSystem.CurrentTimeZone.Value / 60:00}:{Math.Abs(computerSystem.CurrentTimeZone.Value % 60):00}";
else
return null;
});
metadata.Add("System Roles", r =>
{
var computerSystem = r.DeviceDetailComputerSystem?.FirstOrDefault();
if (computerSystem?.Roles != null)
return string.Join("; ", computerSystem.Roles);
else
return null;
});
}
// Processors
if (Options.DetailProcessors)
{
var processorMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailProcessors?.Count ?? 0));
for (int i = 0; i < processorMaxCount; i++)
{
var v = i;
var index = i + 1;
metadata.Add($"Processor{index}Name", r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.Name);
metadata.Add($"Processor{index}Description", r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.Description);
metadata.Add($"Processor{index}Architecture", r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.Architecture);
metadata.Add($"Processor{index}ClockSpeed", r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.MaxClockSpeedFriendly());
metadata.Add($"Processor{index}Cores", r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.NumberOfCores);
metadata.Add($"Processor{index}LogicalProcessors", r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.NumberOfLogicalProcessors);
}
}
// Memory
if (Options.DetailMemory)
{
metadata.Add("Memory Total Capacity", r => MeasurementUnitExtensions.ByteSizeToFriendly((ulong)(r.DeviceDetailPhysicalMemory?.Sum(m => (long)m.Capacity) ?? 0L)));
var memoryMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailPhysicalMemory?.Count ?? 0));
for (int i = 0; i < memoryMaxCount; i++)
{
var v = i;
var index = i + 1;
metadata.Add($"Memory{index}Location", r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.DeviceLocator);
metadata.Add($"Memory{index}Manufacturer", r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.Manufacturer);
metadata.Add($"Memory{index}PartNumber", r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.PartNumber);
metadata.Add($"Memory{index}SerialNumber", r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.SerialNumber);
metadata.Add($"Memory{index}Capacity", r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.CapacityFriendly());
metadata.Add($"Memory{index}ConfiguredClockSpeed", r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.ConfiguredClockSpeed);
}
}
// Disk Drives
if (Options.DetailDiskDrives)
{
var diskDriveMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailDiskDrives?.Count ?? 0));
for (int i = 0; i < diskDriveMaxCount; i++)
{
var v = i;
var index = i + 1;
metadata.Add($"Disk {index} Manufacturer", r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.Manufacturer);
metadata.Add($"Disk {index} Model", r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.Model);
metadata.Add($"Disk {index} Serial Number", r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.SerialNumber);
metadata.Add($"Disk {index} Firmware", r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.FirmwareRevision);
metadata.Add($"Disk {index} Size", r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.SizeFriendly());
metadata.Add($"Disk {index} Total Free Space", r => MeasurementUnitExtensions.ByteSizeToFriendly((ulong)(r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.Partitions?.Sum(p => (long)(p.LogicalDisk?.FreeSpace ?? 0L)) ?? 0L)));
}
}
// Local Network Adapters
if (Options.DetailLanAdapters)
{
var lanAdapterMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailNetworkAdapters?.Count(a => !a.IsWlanAdapter) ?? r.DeviceDetailLanMacAddresses?.Count ?? 0));
for (int i = 0; i < lanAdapterMaxCount; i++)
{
var v = i;
var index = i + 1;
metadata.Add($"Lan Adapter {index} Connection", r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.NetConnectionID);
metadata.Add($"Lan Adapter {index} Manufacturer", r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.Manufacturer);
metadata.Add($"Lan Adapter {index} Product Name", r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.ProductName);
metadata.Add($"Lan Adapter {index} Speed", r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.SpeedFriendly());
metadata.Add($"Lan Adapter {index} Mac Address", r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.MACAddress ?? r.DeviceDetailLanMacAddresses?.Skip(v).FirstOrDefault());
}
}
// Wireless Network Adapters
if (Options.DetailWLanAdapters)
{
var wlanAdapterMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailNetworkAdapters?.Count(a => a.IsWlanAdapter) ?? r.DeviceDetailWlanMacAddresses?.Count ?? 0));
for (int i = 0; i < wlanAdapterMaxCount; i++)
{
var v = i;
var index = i + 1;
metadata.Add($"Wlan Adapter {index} Connection", r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.NetConnectionID);
metadata.Add($"Wlan Adapter {index} Manufacturer", r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.Manufacturer);
metadata.Add($"Wlan Adapter {index} Product Name", r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.ProductName);
metadata.Add($"Wlan Adapter {index} Speed", r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.SpeedFriendly());
metadata.Add($"Wlan Adapter {index} Mac Address", r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.MACAddress ?? r.DeviceDetailWlanMacAddresses?.Skip(v).FirstOrDefault());
}
}
metadata.Add(Options, o => o.DetailACAdapter, r => r.DeviceDetails.Where(dd => dd.Key == DeviceDetail.HardwareKeyACAdapter).Select(dd => dd.Value).FirstOrDefault());
// Batteries
metadata.Add(Options, o => o.DetailBattery, r => r.DeviceDetails.Where(dd => dd.Key == DeviceDetail.HardwareKeyBattery).Select(dd => dd.Value).FirstOrDefault());
if (Options.DetailBatteries)
{
var batteriesMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailBatteries?.Count ?? 0));
for (int i = 0; i < batteriesMaxCount; i++)
{
var v = i;
var index = i + 1;
metadata.Add($"Battery {index} Name", r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Name);
metadata.Add($"Battery {index} Description", r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Description);
metadata.Add($"Battery {index} Availability", r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Availability);
metadata.Add($"Battery {index} Chemistry", r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Chemistry);
metadata.Add($"Battery {index} Design Voltage", r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.DesignVoltage);
metadata.Add($"Battery {index} Design Capacity", r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.DesignCapacity);
metadata.Add($"Battery {index} Capacity", r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.FullChargeCapacity);
}
}
metadata.Add(Options, o => o.DetailKeyboard, r => r.DeviceDetails.Where(dd => dd.Key == DeviceDetail.HardwareKeyKeyboard).Select(dd => dd.Value).FirstOrDefault());
metadata.Add(Options, o => o.DetailMdmHardwareData, r => r.DeviceDetails.MdmHardwareData());
return metadata;
}
}
}
@@ -1,484 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Repository;
using Disco.Models.Services.Devices;
using Disco.Models.Services.Exporting;
using Disco.Services.Exporting;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Disco.Services.Users;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Text.Json.Serialization;
namespace Disco.Services.Devices
{
using Metadata = ExportFieldMetadata<DeviceExportRecord>;
public class DeviceExportContext : IExportContext<DeviceExportOptions, DeviceExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public DeviceExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "DeviceExport";
public string ExcelWorksheetName { get; } = "DeviceExport";
public string ExcelTableName { get; } = "Devices";
[JsonConstructor]
private DeviceExportContext()
{
}
public DeviceExportContext(string name, string description, bool timestampSuffix, DeviceExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public DeviceExportContext(DeviceExportOptions options)
: this("Device Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus taskStatus)
=> Exporter.Export(database, this, taskStatus);
private IQueryable<Device> BuildFilteredRecords(DiscoDataContext database)
{
var query = database.Devices
.Include(d => d.AssignedUser.UserDetails)
.Include(d => d.DeviceDetails);
switch (Options.ExportType)
{
case DeviceExportTypes.All:
break;
case DeviceExportTypes.Batch:
if (Options.ExportTypeTargetId.HasValue && Options.ExportTypeTargetId.Value > 0)
query = query.Where(d => d.DeviceBatchId != Options.ExportTypeTargetId);
else
query = query.Where(d => d.DeviceBatchId != null);
break;
case DeviceExportTypes.Model:
query = query.Where(d => d.DeviceModelId == Options.ExportTypeTargetId);
break;
case DeviceExportTypes.Profile:
query = query.Where(d => d.DeviceProfileId == Options.ExportTypeTargetId);
break;
default:
throw new ArgumentException($"Unknown Device Export Type '{Options.ExportType}'", nameof(Options.ExportType));
}
return query;
}
public List<DeviceExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus taskStatus)
{
var query = BuildFilteredRecords(database);
// Update Users
if (Options.AssignedUserDisplayName ||
Options.AssignedUserSurname ||
Options.AssignedUserGivenName ||
Options.AssignedUserPhoneNumber ||
Options.AssignedUserEmailAddress)
{
taskStatus.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Where(d => d.AssignedUserId != null).Select(d => d.AssignedUserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database);
}
catch (Exception) { } // Ignore Errors
}
}
// Update Last Network Logon Date
if (Options.DeviceLastNetworkLogon)
{
taskStatus.UpdateStatus(15, "Refreshing device last network logon dates from Active Directory");
try
{
Interop.ActiveDirectory.ADNetworkLogonDatesUpdateTask.UpdateLastNetworkLogonDates(database, ScheduledTaskMockStatus.Create("UpdateLastNetworkLogonDates"));
database.SaveChanges();
}
catch (Exception) { } // Ignore Errors
}
taskStatus.UpdateStatus(25, "Gathering database records");
var records = query.Select(d => new DeviceExportRecord()
{
Device = d,
DeviceDetails = d.DeviceDetails,
ModelId = d.DeviceModelId,
ModelDescription = d.DeviceModel.Description,
ModelManufacturer = d.DeviceModel.Manufacturer,
ModelModel = d.DeviceModel.Model,
ModelType = d.DeviceModel.ModelType,
BatchId = d.DeviceBatchId,
BatchName = d.DeviceBatch.Name,
BatchPurchaseDate = d.DeviceBatch.PurchaseDate,
BatchSupplier = d.DeviceBatch.Supplier,
BatchUnitCost = d.DeviceBatch.UnitCost,
BatchWarrantyValidUntilDate = d.DeviceBatch.WarrantyValidUntil,
BatchInsuredDate = d.DeviceBatch.InsuredDate,
BatchInsuranceSupplier = d.DeviceBatch.InsuranceSupplier,
BatchInsuredUntilDate = d.DeviceBatch.InsuredUntil,
ProfileId = d.DeviceProfileId,
ProfileName = d.DeviceProfile.Name,
ProfileShortName = d.DeviceProfile.ShortName,
DeviceUserAssignment = d.DeviceUserAssignments.Where(dua => dua.UnassignedDate == null).FirstOrDefault(),
AssignedUser = d.AssignedUser,
AssignedUserDetails = d.AssignedUser.UserDetails,
JobsTotalCount = d.Jobs.Count(),
JobsOpenCount = d.Jobs.Count(j => j.ClosedDate == null),
AttachmentsCount = d.DeviceAttachments.Count(),
DeviceCertificates = d.DeviceCertificates.Where(dc => dc.Enabled).OrderByDescending(dc => dc.AllocatedDate)
}).ToList();
// materialize device details
records.ForEach(r =>
{
if (Options.DetailBios)
r.DeviceDetailBios = r.DeviceDetails.Bios();
if (Options.DetailBaseBoard)
r.DeviceDetailBaseBoard = r.DeviceDetails.BaseBoard();
if (Options.DetailComputerSystem)
r.DeviceDetailComputerSystem = r.DeviceDetails.ComputerSystem();
if (Options.DetailProcessors)
r.DeviceDetailProcessors = r.DeviceDetails.Processors();
if (Options.DetailMemory)
r.DeviceDetailPhysicalMemory = r.DeviceDetails.PhysicalMemory();
if (Options.DetailDiskDrives)
r.DeviceDetailDiskDrives = r.DeviceDetails.DiskDrives();
if (Options.DetailLanAdapters || Options.DetailWLanAdapters)
{
r.DeviceDetailNetworkAdapters = r.DeviceDetails.NetworkAdapters();
if (r.DeviceDetailNetworkAdapters == null)
{
r.DeviceDetailLanMacAddresses = r.DeviceDetails.LanMacAddress()?.Split(';').Select(a => a.Trim()).ToList();
r.DeviceDetailWlanMacAddresses = r.DeviceDetails.WLanMacAddress()?.Split(';').Select(a => a.Trim()).ToList();
}
}
if (Options.DetailBatteries)
r.DeviceDetailBatteries = r.DeviceDetails.Batteries();
if (Options.AssignedUserDetailCustom && r.AssignedUser != null)
{
var detailsService = new DetailsProviderService(database);
r.AssignedUserCustomDetails = detailsService.GetDetails(r.AssignedUser);
}
});
return records;
}
public List<Metadata> BuildMetadata(DiscoDataContext database, List<DeviceExportRecord> records, IScheduledTaskStatus taskStatus)
{
var processorMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailProcessors?.Count ?? 0));
var memoryMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailPhysicalMemory?.Count ?? 0));
var diskDriveMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailDiskDrives?.Count ?? 0));
var lanAdapterMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailNetworkAdapters?.Count(a => !a.IsWlanAdapter) ?? r.DeviceDetailLanMacAddresses?.Count ?? 0));
var wlanAdapterMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailNetworkAdapters?.Count(a => a.IsWlanAdapter) ?? r.DeviceDetailWlanMacAddresses?.Count ?? 0));
var certificateMaxCount = Math.Max(1, records.Max(r => r.DeviceCertificates?.Count() ?? 0));
var batteriesMaxCount = Math.Max(1, records.Max(r => r.DeviceDetailBatteries?.Count ?? 0));
IEnumerable<string> assignedUserDetailCustomKeys = null;
if (Options.AssignedUserDetailCustom)
assignedUserDetailCustomKeys = records.Where(r => r.AssignedUserCustomDetails != null).SelectMany(r => r.AssignedUserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var allAccessors = BuildRecordAccessors(processorMaxCount, memoryMaxCount, diskDriveMaxCount, lanAdapterMaxCount, wlanAdapterMaxCount, certificateMaxCount, batteriesMaxCount, assignedUserDetailCustomKeys);
return typeof(DeviceExportOptions).GetProperties()
.Where(p => p.PropertyType == typeof(bool))
.Select(p => new
{
property = p,
details = (DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault()
})
.Where(p => p.details != null && (bool)p.property.GetValue(Options))
.SelectMany(p =>
{
var fieldMetadata = allAccessors[p.property.Name];
fieldMetadata.ForEach(f =>
{
if (f.ColumnName == null)
f.ColumnName = (p.details.ShortName == "Device" || p.details.ShortName == "Details") ? p.details.Name : $"{p.details.ShortName} {p.details.Name}";
});
return fieldMetadata;
}).ToList();
}
private static Dictionary<string, List<Metadata>> BuildRecordAccessors(int processorMaxCount, int memoryMaxCount, int diskDriveMaxCount, int lanAdapterMaxCount, int wlanAdapterMaxCount, int certificateMaxCount, int batteriesMaxCount, IEnumerable<string> assignedUserDetailCustomKeys)
{
const string DateFormat = "yyyy-MM-dd";
const string DateTimeFormat = DateFormat + " HH:mm:ss";
Func<object, string> csvStringEncoded = (o) => o == null ? null : $"\"{((string)o).Replace("\"", "\"\"")}\"";
Func<object, string> csvToStringEncoded = (o) => o == null ? null : o.ToString();
Func<object, string> csvCurrencyEncoded = (o) => ((decimal?)o).HasValue ? ((decimal?)o).Value.ToString("C") : null;
Func<object, string> csvDateEncoded = (o) => ((DateTime)o).ToString(DateFormat);
Func<object, string> csvDateTimeEncoded = (o) => ((DateTime)o).ToString(DateTimeFormat);
Func<object, string> csvNullableDateEncoded = (o) => ((DateTime?)o).HasValue ? csvDateEncoded(o) : null;
Func<object, string> csvNullableDateTimeEncoded = (o) => ((DateTime?)o).HasValue ? csvDateTimeEncoded(o) : null;
var metadata = new Dictionary<string, List<Metadata>>();
// Device
metadata.Add(nameof(DeviceExportOptions.DeviceSerialNumber), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceSerialNumber), typeof(string), r => r.Device.SerialNumber, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceAssetNumber), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceAssetNumber), typeof(string), r => r.Device.AssetNumber, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceLocation), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceLocation), typeof(string), r => r.Device.Location, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceComputerName), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceComputerName), typeof(string), r => r.Device.DeviceDomainId, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceLastNetworkLogon), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceLastNetworkLogon), typeof(DateTime), r => r.Device.LastNetworkLogonDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceCreatedDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceCreatedDate), typeof(DateTime), r => r.Device.CreatedDate, csvDateTimeEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceFirstEnrolledDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceFirstEnrolledDate), typeof(DateTime), r => r.Device.EnrolledDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceLastEnrolledDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceLastEnrolledDate), typeof(DateTime), r => r.Device.LastEnrolDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceAllowUnauthenticatedEnrol), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceAllowUnauthenticatedEnrol), typeof(bool), r => r.Device.AllowUnauthenticatedEnrol, csvToStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceDecommissionedDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceDecommissionedDate), typeof(DateTime), r => r.Device.DecommissionedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceExportOptions.DeviceDecommissionedReason), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DeviceDecommissionedReason), typeof(string), r => r.Device.DecommissionReason, csvToStringEncoded) });
// Model
metadata.Add(nameof(DeviceExportOptions.ModelId), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ModelId), typeof(int), r => r.ModelId, csvToStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.ModelDescription), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ModelDescription), typeof(string), r => r.ModelDescription, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.ModelManufacturer), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ModelManufacturer), typeof(string), r => r.ModelManufacturer, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.ModelModel), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ModelModel), typeof(string), r => r.ModelModel, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.ModelType), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ModelType), typeof(string), r => r.ModelType, csvStringEncoded) });
// Batch
metadata.Add(nameof(DeviceExportOptions.BatchId), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchId), typeof(int), r => r.BatchId, csvToStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchName), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchName), typeof(string), r => r.BatchName, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchPurchaseDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchPurchaseDate), typeof(DateTime), r => r.BatchPurchaseDate, csvNullableDateEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchSupplier), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchSupplier), typeof(string), r => r.BatchSupplier, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchUnitCost), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchUnitCost), typeof(decimal), r => r.BatchUnitCost, csvCurrencyEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchWarrantyValidUntilDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchWarrantyValidUntilDate), typeof(DateTime), r => r.BatchWarrantyValidUntilDate, csvNullableDateEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchInsuredDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchInsuredDate), typeof(DateTime), r => r.BatchInsuredDate, csvNullableDateEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchInsuranceSupplier), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchInsuranceSupplier), typeof(string), r => r.BatchInsuranceSupplier, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.BatchInsuredUntilDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.BatchInsuredUntilDate), typeof(DateTime), r => r.BatchInsuredUntilDate, csvNullableDateEncoded) });
// Profile
metadata.Add(nameof(DeviceExportOptions.ProfileId), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ProfileId), typeof(int), r => r.ProfileId, csvToStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.ProfileName), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ProfileName), typeof(string), r => r.ProfileName, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.ProfileShortName), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.ProfileShortName), typeof(string), r => r.ProfileShortName, csvStringEncoded) });
// User
metadata.Add(nameof(DeviceExportOptions.AssignedUserId), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AssignedUserId), typeof(string), r => r.AssignedUser?.UserId, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.AssignedUserDate), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AssignedUserDate), typeof(DateTime), r => r.DeviceUserAssignment?.AssignedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceExportOptions.AssignedUserDisplayName), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AssignedUserDisplayName), typeof(string), r => r.AssignedUser?.DisplayName, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.AssignedUserSurname), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AssignedUserSurname), typeof(string), r => r.AssignedUser?.Surname, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.AssignedUserGivenName), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AssignedUserGivenName), typeof(string), r => r.AssignedUser?.GivenName, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.AssignedUserPhoneNumber), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AssignedUserPhoneNumber), typeof(string), r => r.AssignedUser?.PhoneNumber, csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.AssignedUserEmailAddress), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AssignedUserEmailAddress), typeof(string), r => r.AssignedUser?.EmailAddress, csvStringEncoded) });
if (assignedUserDetailCustomKeys != null)
{
var assignedUserDetailCustomFields = new List<Metadata>();
foreach (var detailKey in assignedUserDetailCustomKeys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
var key = detailKey;
assignedUserDetailCustomFields.Add(new Metadata(detailKey, detailKey, typeof(string), r => r.AssignedUserCustomDetails != null && r.AssignedUserCustomDetails.TryGetValue(key, out var value) ? value : null, csvStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.AssignedUserDetailCustom), assignedUserDetailCustomFields);
}
// Jobs
metadata.Add(nameof(DeviceExportOptions.JobsTotalCount), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.JobsTotalCount), typeof(int), r => r.JobsTotalCount, csvToStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.JobsOpenCount), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.JobsOpenCount), typeof(int), r => r.JobsOpenCount, csvToStringEncoded) });
// Attachments
metadata.Add(nameof(DeviceExportOptions.AttachmentsCount), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.AttachmentsCount), typeof(int), r => r.AttachmentsCount, csvToStringEncoded) });
// Certificates
var certificateFields = new List<Metadata>(certificateMaxCount * 4);
for (int i = 0; i < certificateMaxCount; i++)
{
var v = i;
var index = i + 1;
certificateFields.Add(new Metadata($"Certificate{index}Name", $"Certificate {index} Name", typeof(string), r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.Name, csvStringEncoded));
certificateFields.Add(new Metadata($"Certificate{index}AllocationDate", $"Certificate {index} Allocation Date", typeof(DateTime), r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.AllocatedDate, csvNullableDateTimeEncoded));
certificateFields.Add(new Metadata($"Certificate{index}ExpirationDate", $"Certificate {index} Expiration Date", typeof(DateTime), r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.ExpirationDate, csvNullableDateTimeEncoded));
certificateFields.Add(new Metadata($"Certificate{index}ProviderId", $"Certificate {index} Provider Id", typeof(string), r => r.DeviceCertificates.Skip(v).FirstOrDefault()?.ProviderId, csvStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.Certificates), certificateFields);
// Details
var biosFields = new List<Metadata>()
{
new Metadata("BIOSManufacturer", "BIOS Manufacturer", typeof(string), r => r.DeviceDetailBios?.FirstOrDefault()?.Manufacturer, csvStringEncoded),
new Metadata("BIOSSerialNumber", "BIOS Serial Number", typeof(string), r => r.DeviceDetailBios?.FirstOrDefault()?.SerialNumber, csvStringEncoded),
new Metadata("BIOSVersion", "BIOS Version", typeof(string), r => {
var bios = r.DeviceDetailBios?.FirstOrDefault();
if (bios?.SMBIOSBIOSVersion != null)
return $"{bios.SMBIOSBIOSVersion} {bios.SMBIOSMajorVersion}.{bios.SMBIOSMinorVersion}";
else
return null;
}, csvStringEncoded),
new Metadata("BIOSSystemVersion", "BIOS System Version", typeof(string), r => {
var bios = r.DeviceDetailBios?.FirstOrDefault();
if (bios?.SystemBiosMajorVersion.HasValue ?? false)
return $"{bios.SystemBiosMajorVersion}.{bios.SystemBiosMinorVersion}";
else
return null;
}, csvStringEncoded),
new Metadata("BIOSReleaseDate", "BIOS Release Date", typeof(DateTime), r => r.DeviceDetailBios?.FirstOrDefault()?.ReleaseDate, csvNullableDateTimeEncoded),
};
metadata.Add(nameof(DeviceExportOptions.DetailBios), biosFields);
var baseBoardFields = new List<Metadata>()
{
new Metadata("BaseBoardManufacturer", "Base Board Manufacturer", typeof(string), r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Manufacturer, csvStringEncoded),
new Metadata("BaseBoardModel", "Base Board Model", typeof(string), r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Model, csvStringEncoded),
new Metadata("BaseBoardProduct", "Base Board Product", typeof(string), r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Product, csvStringEncoded),
new Metadata("BaseBoardPartNumber", "Base Board Part Number", typeof(string), r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.PartNumber, csvStringEncoded),
new Metadata("BaseBoardSKU", "Base Board SKU", typeof(string), r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.SKU, csvStringEncoded),
new Metadata("BaseBoardSerialNumber", "Base Board Serial Number", typeof(string), r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.SerialNumber, csvStringEncoded),
new Metadata("BaseBoardConfigOptions", "Base Board Config Options", typeof(string), r => {
var baseBoard = r.DeviceDetailBaseBoard?.FirstOrDefault();
if (baseBoard?.ConfigOptions != null)
return string.Join("; ", baseBoard.ConfigOptions);
else
return null;
}, csvStringEncoded),
new Metadata("BaseBoardVersion", "Base Board Version", typeof(string), r => r.DeviceDetailBaseBoard?.FirstOrDefault()?.Version, csvStringEncoded),
};
metadata.Add(nameof(DeviceExportOptions.DetailBaseBoard), baseBoardFields);
var computerSystemFields = new List<Metadata>()
{
new Metadata("ComputerSystemDescription", "System Description", typeof(string), r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.Description, csvStringEncoded),
new Metadata("ComputerSystemPCSystemType", "System Form Factor", typeof(string), r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.PCSystemType, csvStringEncoded),
new Metadata("ComputerSystemSystemType", "System Type", typeof(string), r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.SystemType, csvStringEncoded),
new Metadata("ComputerSystemPrimaryOwnerName", "System Primary Owner Name", typeof(string), r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.PrimaryOwnerName, csvStringEncoded),
new Metadata("ComputerSystemPrimaryOwnerContact", "System Primary Owner Contact", typeof(string), r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.PrimaryOwnerContact, csvStringEncoded),
new Metadata("ComputerSystemChassisSKU", "System Chassis SKU", typeof(string), r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.ChassisSKUNumber, csvStringEncoded),
new Metadata("ComputerSystemSystemSKU", "System SKU", typeof(string), r => r.DeviceDetailComputerSystem?.FirstOrDefault()?.SystemSKUNumber, csvStringEncoded),
new Metadata("ComputerSystemOEMReference", "System OEM Reference", typeof(string), r => {
var computerSystem = r.DeviceDetailComputerSystem?.FirstOrDefault();
if (computerSystem?.OEMStringArray != null)
return string.Join("; ", computerSystem.OEMStringArray);
else
return null;
}, csvStringEncoded),
new Metadata("ComputerSystemCurrentTimeZone", "System Time Zone", typeof(string), r => {
var computerSystem = r.DeviceDetailComputerSystem?.FirstOrDefault();
if (computerSystem?.CurrentTimeZone.HasValue ?? false)
return $"{computerSystem.CurrentTimeZone.Value / 60:00}:{Math.Abs(computerSystem.CurrentTimeZone.Value % 60):00}";
else
return null;
}, csvStringEncoded),
new Metadata("ComputerSystemRoles", "System Roles", typeof(string), r => {
var computerSystem = r.DeviceDetailComputerSystem?.FirstOrDefault();
if (computerSystem?.Roles != null)
return string.Join("; ", computerSystem.Roles);
else
return null;
}, csvStringEncoded),
};
metadata.Add(nameof(DeviceExportOptions.DetailComputerSystem), computerSystemFields);
var processorFields = new List<Metadata>(processorMaxCount * 6);
for (int i = 0; i < processorMaxCount; i++)
{
var v = i;
var index = i + 1;
processorFields.Add(new Metadata($"Processor{index}Name", $"Processor {index} Name", typeof(string), r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.Name, csvStringEncoded));
processorFields.Add(new Metadata($"Processor{index}Description", $"Processor {index} Description", typeof(string), r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.Description, csvStringEncoded));
processorFields.Add(new Metadata($"Processor{index}Architecture", $"Processor {index} Architecture", typeof(string), r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.Architecture, csvStringEncoded));
processorFields.Add(new Metadata($"Processor{index}ClockSpeed", $"Processor {index} Clock Speed", typeof(string), r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.MaxClockSpeedFriendly(), csvStringEncoded));
processorFields.Add(new Metadata($"Processor{index}Cores", $"Processor {index} Cores", typeof(int), r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.NumberOfCores, csvToStringEncoded));
processorFields.Add(new Metadata($"Processor{index}LogicalProcessors", $"Processor {index} Logical Processors", typeof(int), r => r.DeviceDetailProcessors?.Skip(v).FirstOrDefault()?.NumberOfLogicalProcessors, csvToStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.DetailProcessors), processorFields);
var memoryFields = new List<Metadata>((memoryMaxCount * 6) + 1);
memoryFields.Add(new Metadata($"MemoryTotalCapacity", $"Memory Total Capacity", typeof(string), r => MeasurementUnitExtensions.ByteSizeToFriendly((ulong)(r.DeviceDetailPhysicalMemory?.Sum(m => (long)m.Capacity) ?? 0L)), csvStringEncoded));
for (int i = 0; i < memoryMaxCount; i++)
{
var v = i;
var index = i + 1;
memoryFields.Add(new Metadata($"Memory{index}Location", $"Memory {index} Location", typeof(string), r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.DeviceLocator, csvStringEncoded));
memoryFields.Add(new Metadata($"Memory{index}Manufacturer", $"Memory {index} Manufacturer", typeof(string), r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.Manufacturer, csvStringEncoded));
memoryFields.Add(new Metadata($"Memory{index}PartNumber", $"Memory {index} Part Number", typeof(string), r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.PartNumber, csvStringEncoded));
memoryFields.Add(new Metadata($"Memory{index}SerialNumber", $"Memory {index} Serial Number", typeof(string), r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.SerialNumber, csvStringEncoded));
memoryFields.Add(new Metadata($"Memory{index}Capacity", $"Memory {index} Capacity", typeof(string), r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.CapacityFriendly(), csvStringEncoded));
memoryFields.Add(new Metadata($"Memory{index}ConfiguredClockSpeed", $"Memory {index} Clock Speed", typeof(int), r => r.DeviceDetailPhysicalMemory?.Skip(v).FirstOrDefault()?.ConfiguredClockSpeed, csvToStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.DetailMemory), memoryFields);
var diskFields = new List<Metadata>(diskDriveMaxCount * 6);
for (int i = 0; i < diskDriveMaxCount; i++)
{
var v = i;
var index = i + 1;
diskFields.Add(new Metadata($"Disk{index}Manufacturer", $"Disk {index} Manufacturer", typeof(string), r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.Manufacturer, csvStringEncoded));
diskFields.Add(new Metadata($"Disk{index}Model", $"Disk {index} Model", typeof(string), r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.Model, csvStringEncoded));
diskFields.Add(new Metadata($"Disk{index}SerialNumber", $"Disk {index} Serial Number", typeof(string), r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.SerialNumber, csvStringEncoded));
diskFields.Add(new Metadata($"Disk{index}Firmware", $"Disk {index} Firmware", typeof(string), r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.FirmwareRevision, csvStringEncoded));
diskFields.Add(new Metadata($"Disk{index}Capacity", $"Disk {index} Size", typeof(string), r => r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.SizeFriendly(), csvStringEncoded));
diskFields.Add(new Metadata($"Disk{index}Capacity", $"Disk {index} Total Free Space", typeof(string), r => MeasurementUnitExtensions.ByteSizeToFriendly((ulong)(r.DeviceDetailDiskDrives?.Skip(v).FirstOrDefault()?.Partitions?.Sum(p => (long)(p.LogicalDisk?.FreeSpace ?? 0L)) ?? 0L)), csvStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.DetailDiskDrives), diskFields);
var lanAdapterFields = new List<Metadata>(lanAdapterMaxCount * 5);
for (int i = 0; i < lanAdapterMaxCount; i++)
{
var v = i;
var index = i + 1;
lanAdapterFields.Add(new Metadata($"LanAdapter{index}Connection", $"Lan Adapter {index} Connection", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.NetConnectionID, csvStringEncoded));
lanAdapterFields.Add(new Metadata($"LanAdapter{index}Manufacturer", $"Lan Adapter {index} Manufacturer", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.Manufacturer, csvStringEncoded));
lanAdapterFields.Add(new Metadata($"LanAdapter{index}ProductName", $"Lan Adapter {index} Product Name", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.ProductName, csvStringEncoded));
lanAdapterFields.Add(new Metadata($"LanAdapter{index}Speed", $"Lan Adapter {index} Speed", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.SpeedFriendly(), csvStringEncoded));
lanAdapterFields.Add(new Metadata($"LanAdapter{index}MacAddress", $"Lan Adapter {index} Mac Address", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => !a.IsWlanAdapter).Skip(v).FirstOrDefault()?.MACAddress ?? r.DeviceDetailLanMacAddresses?.Skip(v).FirstOrDefault(), csvStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.DetailLanAdapters), lanAdapterFields);
var fields = new List<Metadata>(wlanAdapterMaxCount * 5);
for (int i = 0; i < wlanAdapterMaxCount; i++)
{
var v = i;
var wlanAdapterFields = i + 1;
fields.Add(new Metadata($"WlanAdapter{wlanAdapterFields}Connection", $"Wlan Adapter {wlanAdapterFields} Connection", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.NetConnectionID, csvStringEncoded));
fields.Add(new Metadata($"WlanAdapter{wlanAdapterFields}Manufacturer", $"Wlan Adapter {wlanAdapterFields} Manufacturer", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.Manufacturer, csvStringEncoded));
fields.Add(new Metadata($"WlanAdapter{wlanAdapterFields}ProductName", $"Wlan Adapter {wlanAdapterFields} Product Name", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.ProductName, csvStringEncoded));
fields.Add(new Metadata($"WlanAdapter{wlanAdapterFields}Speed", $"Wlan Adapter {wlanAdapterFields} Speed", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.SpeedFriendly(), csvStringEncoded));
fields.Add(new Metadata($"WlanAdapter{wlanAdapterFields}MacAddress", $"Wlan Adapter {wlanAdapterFields} Mac Address", typeof(string), r => r.DeviceDetailNetworkAdapters?.Where(a => a.IsWlanAdapter).Skip(v).FirstOrDefault()?.MACAddress ?? r.DeviceDetailWlanMacAddresses?.Skip(v).FirstOrDefault(), csvStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.DetailWLanAdapters), fields);
metadata.Add(nameof(DeviceExportOptions.DetailACAdapter), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DetailACAdapter), typeof(string), r => r.DeviceDetails.Where(dd => dd.Key == DeviceDetail.HardwareKeyACAdapter).Select(dd => dd.Value).FirstOrDefault(), csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.DetailBattery), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DetailBattery), typeof(string), r => r.DeviceDetails.Where(dd => dd.Key == DeviceDetail.HardwareKeyBattery).Select(dd => dd.Value).FirstOrDefault(), csvStringEncoded) });
var batteriesFields = new List<Metadata>(processorMaxCount * 6);
for (int i = 0; i < batteriesMaxCount; i++)
{
var v = i;
var index = i + 1;
batteriesFields.Add(new Metadata($"Batteries{index}Name", $"Battery {index} Name", typeof(string), r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Name, csvStringEncoded));
batteriesFields.Add(new Metadata($"Batteries{index}Description", $"Battery {index} Description", typeof(string), r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Description, csvStringEncoded));
batteriesFields.Add(new Metadata($"Batteries{index}Availability", $"Battery {index} Availability", typeof(string), r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Availability, csvStringEncoded));
batteriesFields.Add(new Metadata($"Batteries{index}Chemistry", $"Battery {index} Chemistry", typeof(string), r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.Chemistry, csvStringEncoded));
batteriesFields.Add(new Metadata($"Batteries{index}DesignVoltage", $"Battery {index} Design Voltage", typeof(long), r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.DesignVoltage, csvToStringEncoded));
batteriesFields.Add(new Metadata($"Batteries{index}DesignCapacity", $"Battery {index} Design Capacity", typeof(int), r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.DesignCapacity, csvToStringEncoded));
batteriesFields.Add(new Metadata($"Batteries{index}FullChargeCapacity", $"Battery {index} Capacity", typeof(int), r => r.DeviceDetailBatteries?.Skip(v).FirstOrDefault()?.FullChargeCapacity, csvToStringEncoded));
}
metadata.Add(nameof(DeviceExportOptions.DetailBatteries), batteriesFields);
metadata.Add(nameof(DeviceExportOptions.DetailKeyboard), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DetailKeyboard), typeof(string), r => r.DeviceDetails.Where(dd => dd.Key == DeviceDetail.HardwareKeyKeyboard).Select(dd => dd.Value).FirstOrDefault(), csvStringEncoded) });
metadata.Add(nameof(DeviceExportOptions.DetailMdmHardwareData), new List<Metadata>() { new Metadata(nameof(DeviceExportOptions.DetailMdmHardwareData), typeof(string), r => r.DeviceDetails.MdmHardwareData(), csvStringEncoded) });
return metadata;
}
}
}
@@ -0,0 +1,195 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Services.Devices.DeviceFlag;
using Disco.Models.Services.Exporting;
using Disco.Services.Exporting;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Disco.Services.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace Disco.Services.Devices.DeviceFlags
{
public class DeviceFlagExport : IExport<DeviceFlagExportOptions, DeviceFlagExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public DeviceFlagExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "DeviceFlagExport";
public string ExcelWorksheetName { get; } = "DeviceFlagExport";
public string ExcelTableName { get; } = "DeviceFlags";
[JsonConstructor]
private DeviceFlagExport()
{
}
public DeviceFlagExport(string name, string description, bool timestampSuffix, DeviceFlagExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public DeviceFlagExport(DeviceFlagExportOptions options)
: this("Device Flag Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(this, database, status);
public List<DeviceFlagExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
var query = database.DeviceFlagAssignments
.Include(a => a.DeviceFlag);
if (Options.HasDeviceOptions())
query = query.Include(a => a.Device);
if (Options.HasDeviceModelOptions())
query = query.Include(a => a.Device.DeviceModel);
if (Options.HasDeviceBatchOptions())
query = query.Include(a => a.Device.DeviceBatch);
if (Options.HasDeviceProfileOptions())
query = query.Include(a => a.Device.DeviceProfile);
if (Options.HasAssignedUserOptions())
query = query.Include(a => a.Device.AssignedUser);
if (Options.AssignedUserDetailCustom)
query = query.Include(a => a.Device.AssignedUser.UserDetails);
query = query.Where(a => Options.DeviceFlagIds.Contains(a.DeviceFlagId));
if (Options.CurrentOnly)
{
query = query.Where(a => !a.RemovedDate.HasValue);
}
// Update Users
if (Options.HasAssignedUserOptions())
{
status.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Where(d => d.Device.AssignedUserId != null).Select(d => d.Device.AssignedUserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database, true);
}
catch (Exception) { } // Ignore Errors
}
}
status.UpdateStatus(15, "Extracting records from the database");
var records = query.Select(a => new DeviceFlagExportRecord()
{
Assignment = a
}).ToList();
if (Options.AssignedUserDetailCustom)
{
status.UpdateStatus(50, "Extracting custom user detail records");
var detailsService = new DetailsProviderService(database);
var cache = new Dictionary<string, Dictionary<string, string>>(StringComparer.Ordinal);
foreach (var record in records)
{
var userId = record.Assignment.Device.AssignedUserId;
if (userId == null)
continue;
if (!cache.TryGetValue(userId, out var details))
details = detailsService.GetDetails(record.Assignment.Device.AssignedUser);
record.AssignedUserCustomDetails = details;
}
}
return records;
}
public ExportMetadata<DeviceFlagExportRecord> BuildMetadata(DiscoDataContext database, List<DeviceFlagExportRecord> records, IScheduledTaskStatus status)
{
var metadata = new ExportMetadata<DeviceFlagExportRecord>();
metadata.IgnoreShortNames.Add("Device Flag");
// Device Flag
metadata.Add(Options, o => o.Id, r => r.Assignment.DeviceFlagId);
metadata.Add(Options, o => o.Name, r => r.Assignment.DeviceFlag.Name);
metadata.Add(Options, o => o.Description, r => r.Assignment.DeviceFlag.Description);
metadata.Add(Options, o => o.Icon, r => r.Assignment.DeviceFlag.Icon);
metadata.Add(Options, o => o.IconColour, r => r.Assignment.DeviceFlag.IconColour);
metadata.Add(Options, o => o.AssignmentId, r => r.Assignment.Id);
metadata.Add(Options, o => o.AddedDate, r => r.Assignment.AddedDate);
metadata.Add(Options, o => o.AddedUserId, r => r.Assignment.AddedUserId);
metadata.Add(Options, o => o.RemovedUserId, r => r.Assignment.RemovedUserId);
metadata.Add(Options, o => o.RemovedDate, r => r.Assignment.RemovedDate);
metadata.Add(Options, o => o.Comments, r => r.Assignment.Comments);
// Device
metadata.Add(Options, o => o.DeviceSerialNumber, r => r.Assignment.Device.SerialNumber);
metadata.Add(Options, o => o.DeviceAssetNumber, r => r.Assignment.Device.AssetNumber);
metadata.Add(Options, o => o.DeviceLocation, r => r.Assignment.Device.Location);
metadata.Add(Options, o => o.DeviceComputerName, r => r.Assignment.Device.DeviceDomainId);
metadata.Add(Options, o => o.DeviceLastNetworkLogon, r => r.Assignment.Device.LastNetworkLogonDate);
metadata.Add(Options, o => o.DeviceCreatedDate, r => r.Assignment.Device.CreatedDate);
metadata.Add(Options, o => o.DeviceFirstEnrolledDate, r => r.Assignment.Device.EnrolledDate);
metadata.Add(Options, o => o.DeviceLastEnrolledDate, r => r.Assignment.Device.LastEnrolDate);
metadata.Add(Options, o => o.DeviceAllowUnauthenticatedEnrol, r => r.Assignment.Device.AllowUnauthenticatedEnrol);
metadata.Add(Options, o => o.DeviceDecommissionedDate, r => r.Assignment.Device.DecommissionedDate);
metadata.Add(Options, o => o.DeviceDecommissionedReason, r => r.Assignment.Device.DecommissionReason?.ToString());
// Model
metadata.Add(Options, o => o.ModelId, r => r.Assignment.Device.DeviceModel.Id);
metadata.Add(Options, o => o.ModelDescription, r => r.Assignment.Device.DeviceModel.Description);
metadata.Add(Options, o => o.ModelManufacturer, r => r.Assignment.Device.DeviceModel.Manufacturer);
metadata.Add(Options, o => o.ModelModel, r => r.Assignment.Device.DeviceModel.Model);
metadata.Add(Options, o => o.ModelType, r => r.Assignment.Device.DeviceModel.ModelType);
// Batch
metadata.Add(Options, o => o.BatchId, r => r.Assignment.Device.DeviceBatch?.Id);
metadata.Add(Options, o => o.BatchName, r => r.Assignment.Device.DeviceBatch?.Name);
metadata.Add(Options, o => o.BatchPurchaseDate, r => r.Assignment.Device.DeviceBatch?.PurchaseDate);
metadata.Add(Options, o => o.BatchSupplier, r => r.Assignment.Device.DeviceBatch?.Supplier);
metadata.Add(Options, o => o.BatchUnitCost, r => r.Assignment.Device.DeviceBatch?.UnitCost, Exporter.CsvEncoders.NullableCurrencyEncoder);
metadata.Add(Options, o => o.BatchWarrantyValidUntilDate, r => r.Assignment.Device.DeviceBatch?.WarrantyValidUntil);
metadata.Add(Options, o => o.BatchInsuredDate, r => r.Assignment.Device.DeviceBatch?.InsuredDate);
metadata.Add(Options, o => o.BatchInsuranceSupplier, r => r.Assignment.Device.DeviceBatch?.InsuranceSupplier);
metadata.Add(Options, o => o.BatchInsuredUntilDate, r => r.Assignment.Device.DeviceBatch?.InsuredUntil);
// Profile
metadata.Add(Options, o => o.ProfileId, r => r.Assignment.Device.DeviceProfile?.Id);
metadata.Add(Options, o => o.ProfileName, r => r.Assignment.Device.DeviceProfile?.Name);
metadata.Add(Options, o => o.ProfileShortName, r => r.Assignment.Device.DeviceProfile?.ShortName);
// User
metadata.Add(Options, o => o.AssignedUserId, r => r.Assignment.Device?.AssignedUser?.UserId);
metadata.Add(Options, o => o.AssignedUserDisplayName, r => r.Assignment.Device?.AssignedUser?.DisplayName);
metadata.Add(Options, o => o.AssignedUserSurname, r => r.Assignment.Device?.AssignedUser?.Surname);
metadata.Add(Options, o => o.AssignedUserGivenName, r => r.Assignment.Device?.AssignedUser?.GivenName);
metadata.Add(Options, o => o.AssignedUserPhoneNumber, r => r.Assignment.Device?.AssignedUser?.PhoneNumber);
metadata.Add(Options, o => o.AssignedUserEmailAddress, r => r.Assignment.Device?.AssignedUser?.EmailAddress);
// User Custom Details
if (Options.AssignedUserDetailCustom)
{
var keys = records.Where(r => r.AssignedUserCustomDetails != null).SelectMany(r => r.AssignedUserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
foreach (var key in keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
metadata.Add(key, r => r.AssignedUserCustomDetails != null && r.AssignedUserCustomDetails.TryGetValue(key, out var value) ? value : null);
}
}
return metadata;
}
}
}
@@ -1,238 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Services.Devices.DeviceFlag;
using Disco.Models.Services.Exporting;
using Disco.Services.Exporting;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Disco.Services.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
namespace Disco.Services.Devices.DeviceFlags
{
using Metadata = ExportFieldMetadata<DeviceFlagExportRecord>;
public class DeviceFlagExportContext : IExportContext<DeviceFlagExportOptions, DeviceFlagExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public DeviceFlagExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "DeviceFlagExport";
public string ExcelWorksheetName { get; } = "DeviceFlagExport";
public string ExcelTableName { get; } = "DeviceFlags";
[JsonConstructor]
private DeviceFlagExportContext()
{
}
public DeviceFlagExportContext(string name, string description, bool timestampSuffix, DeviceFlagExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public DeviceFlagExportContext(DeviceFlagExportOptions options)
: this("Device Flag Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(database, this, status);
public List<DeviceFlagExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
var query = database.DeviceFlagAssignments
.Include(a => a.DeviceFlag);
if (Options.HasDeviceOptions())
query = query.Include(a => a.Device);
if (Options.HasDeviceModelOptions())
query = query.Include(a => a.Device.DeviceModel);
if (Options.HasDeviceBatchOptions())
query = query.Include(a => a.Device.DeviceBatch);
if (Options.HasDeviceProfileOptions())
query = query.Include(a => a.Device.DeviceProfile);
if (Options.HasAssignedUserOptions())
query = query.Include(a => a.Device.AssignedUser);
if (Options.AssignedUserDetailCustom)
query = query.Include(a => a.Device.AssignedUser.UserDetails);
query = query.Where(a => Options.DeviceFlagIds.Contains(a.DeviceFlagId));
if (Options.CurrentOnly)
{
query = query.Where(a => !a.RemovedDate.HasValue);
}
// Update Users
if (Options.HasAssignedUserOptions())
{
status.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Where(d => d.Device.AssignedUserId != null).Select(d => d.Device.AssignedUserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database);
}
catch (Exception) { } // Ignore Errors
}
}
status.UpdateStatus(15, "Extracting records from the database");
var records = query.Select(a => new DeviceFlagExportRecord()
{
Assignment = a
}).ToList();
if (Options.AssignedUserDetailCustom)
{
status.UpdateStatus(50, "Extracting custom user detail records");
var detailsService = new DetailsProviderService(database);
var cache = new Dictionary<string, Dictionary<string, string>>(StringComparer.Ordinal);
foreach (var record in records)
{
var userId = record.Assignment.Device.AssignedUserId;
if (userId == null)
continue;
if (!cache.TryGetValue(userId, out var details))
details = detailsService.GetDetails(record.Assignment.Device.AssignedUser);
record.AssignedUserCustomDetails = details;
}
}
return records;
}
public List<Metadata> BuildMetadata(DiscoDataContext database, List<DeviceFlagExportRecord> records, IScheduledTaskStatus status)
{
IEnumerable<string> userDetailCustomKeys = null;
if (Options.AssignedUserDetailCustom)
userDetailCustomKeys = records.Where(r => r.AssignedUserCustomDetails != null).SelectMany(r => r.AssignedUserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var accessors = BuildAccessors(userDetailCustomKeys);
return typeof(DeviceFlagExportOptions).GetProperties()
.Where(p => p.PropertyType == typeof(bool))
.Select(p => new
{
property = p,
details = (DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault()
})
.Where(p => p.details != null && p.property.Name != nameof(Options.CurrentOnly) && (bool)p.property.GetValue(Options))
.SelectMany(p =>
{
var fieldMetadata = accessors[p.property.Name];
fieldMetadata.ForEach(f =>
{
if (f.ColumnName == null)
f.ColumnName = (p.details.ShortName == "Device Flag") ? p.details.Name : $"{p.details.ShortName} {p.details.Name}";
});
return fieldMetadata;
}).ToList();
}
private static Dictionary<string, List<Metadata>> BuildAccessors(IEnumerable<string> userDetailsCustomKeys)
{
const string DateFormat = "yyyy-MM-dd";
const string DateTimeFormat = DateFormat + " HH:mm:ss";
Func<object, string> csvStringEncoded = (o) => o == null ? null : $"\"{((string)o).Replace("\"", "\"\"")}\"";
Func<object, string> csvToStringEncoded = (o) => o == null ? null : o.ToString();
Func<object, string> csvCurrencyEncoded = (o) => ((decimal?)o).HasValue ? ((decimal?)o).Value.ToString("C") : null;
Func<object, string> csvDateEncoded = (o) => ((DateTime)o).ToString(DateFormat);
Func<object, string> csvDateTimeEncoded = (o) => ((DateTime)o).ToString(DateTimeFormat);
Func<object, string> csvNullableDateEncoded = (o) => ((DateTime?)o).HasValue ? csvDateEncoded(o) : null;
Func<object, string> csvNullableDateTimeEncoded = (o) => ((DateTime?)o).HasValue ? csvDateTimeEncoded(o) : null;
var metadata = new Dictionary<string, List<Metadata>>();
// Device Flag
metadata.Add(nameof(DeviceFlagExportOptions.Id), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.Id), typeof(string), r => r.Assignment.DeviceFlagId, csvToStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.Name), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.Name), typeof(string), r => r.Assignment.DeviceFlag.Name, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.Description), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.Description), typeof(string), r => r.Assignment.DeviceFlag.Description, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.Icon), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.Icon), typeof(string), r => r.Assignment.DeviceFlag.Icon, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.IconColour), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.IconColour), typeof(string), r => r.Assignment.DeviceFlag.IconColour, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AssignmentId), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AssignmentId), typeof(string), r => r.Assignment.Id, csvToStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AddedDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AddedDate), typeof(string), r => r.Assignment.AddedDate, csvDateTimeEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AddedUserId), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AddedUserId), typeof(string), r => r.Assignment.AddedUserId, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.RemovedUserId), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.RemovedUserId), typeof(string), r => r.Assignment.RemovedUserId, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.RemovedDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.RemovedDate), typeof(string), r => r.Assignment.RemovedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.Comments), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.Comments), typeof(string), r => r.Assignment.Comments, csvStringEncoded) });
// Device
metadata.Add(nameof(DeviceFlagExportOptions.DeviceSerialNumber), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceSerialNumber), typeof(string), r => r.Assignment.Device.SerialNumber, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceAssetNumber), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceAssetNumber), typeof(string), r => r.Assignment.Device.AssetNumber, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceLocation), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceLocation), typeof(string), r => r.Assignment.Device.Location, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceComputerName), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceComputerName), typeof(string), r => r.Assignment.Device.DeviceDomainId, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceLastNetworkLogon), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceLastNetworkLogon), typeof(DateTime), r => r.Assignment.Device.LastNetworkLogonDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceCreatedDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceCreatedDate), typeof(DateTime), r => r.Assignment.Device.CreatedDate, csvDateTimeEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceFirstEnrolledDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceFirstEnrolledDate), typeof(DateTime), r => r.Assignment.Device.EnrolledDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceLastEnrolledDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceLastEnrolledDate), typeof(DateTime), r => r.Assignment.Device.LastEnrolDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceAllowUnauthenticatedEnrol), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceAllowUnauthenticatedEnrol), typeof(bool), r => r.Assignment.Device.AllowUnauthenticatedEnrol, csvToStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceDecommissionedDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceDecommissionedDate), typeof(DateTime), r => r.Assignment.Device.DecommissionedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.DeviceDecommissionedReason), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.DeviceDecommissionedReason), typeof(string), r => r.Assignment.Device.DecommissionReason, csvToStringEncoded) });
// Model
metadata.Add(nameof(DeviceFlagExportOptions.ModelId), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ModelId), typeof(int), r => r.Assignment.Device.DeviceModel.Id, csvToStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.ModelDescription), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ModelDescription), typeof(string), r => r.Assignment.Device.DeviceModel.Description, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.ModelManufacturer), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ModelManufacturer), typeof(string), r => r.Assignment.Device.DeviceModel.Manufacturer, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.ModelModel), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ModelModel), typeof(string), r => r.Assignment.Device.DeviceModel.Model, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.ModelType), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ModelType), typeof(string), r => r.Assignment.Device.DeviceModel.ModelType, csvStringEncoded) });
// Batch
metadata.Add(nameof(DeviceFlagExportOptions.BatchId), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchId), typeof(int), r => r.Assignment.Device.DeviceBatch?.Id, csvToStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchName), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchName), typeof(string), r => r.Assignment.Device.DeviceBatch?.Name, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchPurchaseDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchPurchaseDate), typeof(DateTime), r => r.Assignment.Device.DeviceBatch?.PurchaseDate, csvNullableDateEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchSupplier), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchSupplier), typeof(string), r => r.Assignment.Device.DeviceBatch?.Supplier, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchUnitCost), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchUnitCost), typeof(decimal), r => r.Assignment.Device.DeviceBatch?.UnitCost, csvCurrencyEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchWarrantyValidUntilDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchWarrantyValidUntilDate), typeof(DateTime), r => r.Assignment.Device.DeviceBatch?.WarrantyValidUntil, csvNullableDateEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchInsuredDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchInsuredDate), typeof(DateTime), r => r.Assignment.Device.DeviceBatch?.InsuredDate, csvNullableDateEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchInsuranceSupplier), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchInsuranceSupplier), typeof(string), r => r.Assignment.Device.DeviceBatch?.InsuranceSupplier, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.BatchInsuredUntilDate), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.BatchInsuredUntilDate), typeof(DateTime), r => r.Assignment.Device.DeviceBatch?.InsuredUntil, csvNullableDateEncoded) });
// Profile
metadata.Add(nameof(DeviceFlagExportOptions.ProfileId), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ProfileId), typeof(int), r => r.Assignment.Device.DeviceProfile?.Id, csvToStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.ProfileName), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ProfileName), typeof(string), r => r.Assignment.Device.DeviceProfile?.Name, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.ProfileShortName), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.ProfileShortName), typeof(string), r => r.Assignment.Device.DeviceProfile?.ShortName, csvStringEncoded) });
// User
metadata.Add(nameof(DeviceFlagExportOptions.AssignedUserId), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AssignedUserId), typeof(string), r => r.Assignment.Device?.AssignedUser?.UserId, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AssignedUserDisplayName), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AssignedUserDisplayName), typeof(string), r => r.Assignment.Device?.AssignedUser?.DisplayName, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AssignedUserSurname), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AssignedUserSurname), typeof(string), r => r.Assignment.Device?.AssignedUser?.Surname, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AssignedUserGivenName), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AssignedUserGivenName), typeof(string), r => r.Assignment.Device?.AssignedUser?.GivenName, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AssignedUserPhoneNumber), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AssignedUserPhoneNumber), typeof(string), r => r.Assignment.Device?.AssignedUser?.PhoneNumber, csvStringEncoded) });
metadata.Add(nameof(DeviceFlagExportOptions.AssignedUserEmailAddress), new List<Metadata>() { new Metadata(nameof(DeviceFlagExportOptions.AssignedUserEmailAddress), typeof(string), r => r.Assignment.Device?.AssignedUser?.EmailAddress, csvStringEncoded) });
if (userDetailsCustomKeys != null)
{
var userDetailCustomFields = new List<Metadata>();
foreach (var detailKey in userDetailsCustomKeys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
var key = detailKey;
userDetailCustomFields.Add(new Metadata(detailKey, detailKey, typeof(string), r => r.AssignedUserCustomDetails != null && r.AssignedUserCustomDetails.TryGetValue(key, out var value) ? value : null, csvStringEncoded));
}
metadata.Add(nameof(DeviceFlagExportOptions.AssignedUserDetailCustom), userDetailCustomFields);
}
return metadata;
}
}
}
+6 -6
View File
@@ -347,7 +347,7 @@
<Compile Include="Devices\DeviceDataStoreExtensions.cs" /> <Compile Include="Devices\DeviceDataStoreExtensions.cs" />
<Compile Include="Devices\DeviceDetailExtensions.cs" /> <Compile Include="Devices\DeviceDetailExtensions.cs" />
<Compile Include="Devices\DeviceExtensions.cs" /> <Compile Include="Devices\DeviceExtensions.cs" />
<Compile Include="Devices\DeviceFlags\DeviceFlagExportContext.cs" /> <Compile Include="Devices\DeviceFlags\DeviceFlagExport.cs" />
<Compile Include="Devices\DeviceModelExtensions.cs" /> <Compile Include="Devices\DeviceModelExtensions.cs" />
<Compile Include="Devices\DeviceProfileExtensions.cs" /> <Compile Include="Devices\DeviceProfileExtensions.cs" />
<Compile Include="Devices\DeviceBatchUpdatesHub.cs" /> <Compile Include="Devices\DeviceBatchUpdatesHub.cs" />
@@ -358,7 +358,7 @@
<Compile Include="Devices\Enrolment\EnrolmentTypes.cs" /> <Compile Include="Devices\Enrolment\EnrolmentTypes.cs" />
<Compile Include="Devices\Enrolment\LogMacAddressImportingTask.cs" /> <Compile Include="Devices\Enrolment\LogMacAddressImportingTask.cs" />
<Compile Include="Devices\Enrolment\MacDeviceEnrolment.cs" /> <Compile Include="Devices\Enrolment\MacDeviceEnrolment.cs" />
<Compile Include="Devices\DeviceExportContext.cs" /> <Compile Include="Devices\DeviceExport.cs" />
<Compile Include="Devices\DeviceFlags\Cache.cs" /> <Compile Include="Devices\DeviceFlags\Cache.cs" />
<Compile Include="Devices\DeviceFlags\DeviceFlagExtensions.cs" /> <Compile Include="Devices\DeviceFlags\DeviceFlagExtensions.cs" />
<Compile Include="Devices\DeviceFlags\DeviceFlagsBulkAssignTask.cs" /> <Compile Include="Devices\DeviceFlags\DeviceFlagsBulkAssignTask.cs" />
@@ -424,7 +424,7 @@
<Compile Include="Documents\ManagedGroups\DocumentTemplateManagedGroups.cs" /> <Compile Include="Documents\ManagedGroups\DocumentTemplateManagedGroups.cs" />
<Compile Include="Documents\ManagedGroups\DocumentTemplateUsersManagedGroup.cs" /> <Compile Include="Documents\ManagedGroups\DocumentTemplateUsersManagedGroup.cs" />
<Compile Include="Documents\QRCodeBinaryEncoder.cs" /> <Compile Include="Documents\QRCodeBinaryEncoder.cs" />
<Compile Include="Exporting\IExportContext.cs" /> <Compile Include="Exporting\IExport.cs" />
<Compile Include="Expressions\EvaluateExpressionParseException.cs" /> <Compile Include="Expressions\EvaluateExpressionParseException.cs" />
<Compile Include="Expressions\EvaluateExpressionPart.cs" /> <Compile Include="Expressions\EvaluateExpressionPart.cs" />
<Compile Include="Expressions\Expression.cs" /> <Compile Include="Expressions\Expression.cs" />
@@ -491,7 +491,7 @@
<Compile Include="Interop\VicEduDept\VicSmart.cs" /> <Compile Include="Interop\VicEduDept\VicSmart.cs" />
<Compile Include="Interop\DiscoServices\UpdateQuery.cs" /> <Compile Include="Interop\DiscoServices\UpdateQuery.cs" />
<Compile Include="Interop\DiscoServices\UpdateQueryTask.cs" /> <Compile Include="Interop\DiscoServices\UpdateQueryTask.cs" />
<Compile Include="Jobs\JobExportContext.cs" /> <Compile Include="Jobs\JobExport.cs" />
<Compile Include="Jobs\JobActionExtensions.cs" /> <Compile Include="Jobs\JobActionExtensions.cs" />
<Compile Include="Jobs\JobExtensions.cs" /> <Compile Include="Jobs\JobExtensions.cs" />
<Compile Include="Jobs\JobFlagExtensions.cs" /> <Compile Include="Jobs\JobFlagExtensions.cs" />
@@ -511,7 +511,7 @@
<Compile Include="Jobs\Statistics\DailyOpenedClosed.cs" /> <Compile Include="Jobs\Statistics\DailyOpenedClosed.cs" />
<Compile Include="Logging\LogBase.cs" /> <Compile Include="Logging\LogBase.cs" />
<Compile Include="Logging\LogContext.cs" /> <Compile Include="Logging\LogContext.cs" />
<Compile Include="Logging\LogExportContext.cs" /> <Compile Include="Logging\LogExport.cs" />
<Compile Include="Logging\LogReInitalizeJob.cs" /> <Compile Include="Logging\LogReInitalizeJob.cs" />
<Compile Include="Logging\Models\LogEvent.cs" /> <Compile Include="Logging\Models\LogEvent.cs" />
<Compile Include="Logging\Models\LogEventType.cs" /> <Compile Include="Logging\Models\LogEventType.cs" />
@@ -599,7 +599,7 @@
<Compile Include="Users\Contact\UserContactService.cs" /> <Compile Include="Users\Contact\UserContactService.cs" />
<Compile Include="Users\UserExtensions.cs" /> <Compile Include="Users\UserExtensions.cs" />
<Compile Include="Users\UserFlags\Cache.cs" /> <Compile Include="Users\UserFlags\Cache.cs" />
<Compile Include="Users\UserFlags\UserFlagExportContext.cs" /> <Compile Include="Users\UserFlags\UserFlagExport.cs" />
<Compile Include="Users\UserFlags\UserFlagExtensions.cs" /> <Compile Include="Users\UserFlags\UserFlagExtensions.cs" />
<Compile Include="Users\UserFlags\UserFlagUserDevicesManagedGroup.cs" /> <Compile Include="Users\UserFlags\UserFlagUserDevicesManagedGroup.cs" />
<Compile Include="Users\UserFlags\UserFlagUsersManagedGroup.cs" /> <Compile Include="Users\UserFlags\UserFlagUsersManagedGroup.cs" />
+4 -4
View File
@@ -9,15 +9,15 @@ namespace Disco.Services.Exporting
{ {
public class ExportTask : ScheduledTask public class ExportTask : ScheduledTask
{ {
private IExportContext context; private IExport context;
public override string TaskName { get => context?.Name ?? "Exporting"; } public override string TaskName { get => context?.Name ?? "Exporting"; }
public override bool SingleInstanceTask { get { return false; } } public override bool SingleInstanceTask { get { return false; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public static ExportTaskContext ScheduleNow(IExportContext exportContext) public static ExportTaskContext ScheduleNow(IExport export)
{ {
// Build Context // Build Context
var taskContext = new ExportTaskContext(exportContext); var taskContext = new ExportTaskContext(export);
// Build Data Map // Build Data Map
var task = new ExportTask(); var task = new ExportTask();
@@ -31,7 +31,7 @@ namespace Disco.Services.Exporting
private static string GetCacheKey(Guid exportId) => $"ExportTask_{exportId}"; private static string GetCacheKey(Guid exportId) => $"ExportTask_{exportId}";
public static ExportTaskContext ScheduleNowCacheResult(IExportContext exportContext, Func<Guid, string> returnUrlBuilder) public static ExportTaskContext ScheduleNowCacheResult(IExport exportContext, Func<Guid, string> returnUrlBuilder)
{ {
var taskContext = ScheduleNow(exportContext); var taskContext = ScheduleNow(exportContext);
@@ -6,13 +6,13 @@ namespace Disco.Services.Exporting
{ {
public class ExportTaskContext public class ExportTaskContext
{ {
public IExportContext ExportContext { get; } public IExport ExportContext { get; }
public ScheduledTaskStatus TaskStatus { get; internal set; } public ScheduledTaskStatus TaskStatus { get; internal set; }
public ExportResult Result { get; internal set; } public ExportResult Result { get; internal set; }
public Guid Id => ExportContext.Id; public Guid Id => ExportContext.Id;
public ExportTaskContext(IExportContext context) public ExportTaskContext(IExport context)
{ {
ExportContext = context; ExportContext = context;
} }
+99 -3
View File
@@ -5,16 +5,18 @@ using Disco.Models.Services.Exporting;
using Disco.Services.Tasks; using Disco.Services.Tasks;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data; using System.Data;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Linq.Expressions;
using System.Text; using System.Text;
namespace Disco.Services.Exporting namespace Disco.Services.Exporting
{ {
public static class Exporter public static class Exporter
{ {
public static ExportResult Export<T, R>(DiscoDataContext database, IExportContext<T, R> context, IScheduledTaskStatus status) public static ExportResult Export<T, R>(IExport<T, R> context, DiscoDataContext database, IScheduledTaskStatus status)
where T : IExportOptions, new() where T : IExportOptions, new()
where R : IExportRecord where R : IExportRecord
{ {
@@ -67,7 +69,7 @@ namespace Disco.Services.Exporting
}; };
} }
private static MemoryStream WriteCSV<T>(List<ExportFieldMetadata<T>> metadata, List<T> records) where T : IExportRecord private static MemoryStream WriteCSV<T>(List<ExportMetadataField<T>> metadata, List<T> records) where T : IExportRecord
{ {
var stream = new MemoryStream(); var stream = new MemoryStream();
@@ -98,7 +100,7 @@ namespace Disco.Services.Exporting
return stream; return stream;
} }
private static MemoryStream WriteXlsx<T>(string worksheetName, string tableName, List<ExportFieldMetadata<T>> metadata, List<T> records) where T : IExportRecord private static MemoryStream WriteXlsx<T>(string worksheetName, string tableName, List<ExportMetadataField<T>> metadata, List<T> records) where T : IExportRecord
{ {
var stream = new MemoryStream(); var stream = new MemoryStream();
@@ -127,5 +129,99 @@ namespace Disco.Services.Exporting
stream.Position = 0; stream.Position = 0;
return stream; return stream;
} }
public static void Add<T, O, V>(this ExportMetadata<T> metadata, O options, Expression<Func<O, bool>> optionAccessor, Func<T, V> valueAccessor, Func<object, string> csvValueEncoder = null, string columnName = null)
where T : IExportRecord
where O : IExportOptions
{
// is field enabled?
if (!optionAccessor.Compile().Invoke(options))
return;
if (columnName is null)
{
var member = ((MemberExpression)optionAccessor.Body).Member;
var attribute = (DisplayAttribute)member.GetCustomAttributes(typeof(DisplayAttribute), false).Single();
if (metadata.IgnoreShortNames.Contains(attribute.ShortName))
columnName = attribute.Name;
else
columnName = $"{attribute.ShortName} {attribute.Name}";
}
metadata.Add(columnName, valueAccessor, csvValueEncoder);
}
public static void Add<T, V>(this ExportMetadata<T> metadata, string columnName, Func<T, V> valueAccessor, Func<object, string> csvValueEncoder = null)
where T : IExportRecord
{
var valueType = typeof(V);
if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Nullable<>))
valueType = valueType.GetGenericArguments()[0];
if (csvValueEncoder is null)
csvValueEncoder = CsvEncoders.GetEncoder<V>();
var field = new ExportMetadataField<T>(columnName, valueType, (T i) => valueAccessor(i), csvValueEncoder);
metadata.Add(field);
}
public static class CsvEncoders
{
private static Dictionary<Type, Func<object, string>> encoders = new Dictionary<Type, Func<object, string>>()
{
{ typeof(string), StringEncoder },
{ typeof(object), ObjectToStringEncoder },
{ typeof(byte), ToStringEncoder },
{ typeof(byte?), ToStringEncoder },
{ typeof(decimal), ToStringEncoder },
{ typeof(decimal?), ToStringEncoder },
{ typeof(double), ToStringEncoder },
{ typeof(double?), ToStringEncoder },
{ typeof(float), ToStringEncoder },
{ typeof(float?), ToStringEncoder },
{ typeof(int), ToStringEncoder },
{ typeof(int?), ToStringEncoder },
{ typeof(uint), ToStringEncoder },
{ typeof(uint?), ToStringEncoder },
{ typeof(long), ToStringEncoder },
{ typeof(long?), ToStringEncoder },
{ typeof(ulong), ToStringEncoder },
{ typeof(ulong?), ToStringEncoder },
{ typeof(short), ToStringEncoder },
{ typeof(short?), ToStringEncoder },
{ typeof(ushort), ToStringEncoder },
{ typeof(ushort?), ToStringEncoder },
{ typeof(bool), ToStringEncoder },
{ typeof(bool?), ToStringEncoder },
{ typeof(DateTime), DateTimeEncoder },
{ typeof(DateTime?), NullableDateTimeEncoder },
};
public static readonly string DateFormat = "yyyy-MM-dd";
public static readonly string DateTimeFormat = DateFormat + " HH:mm:ss";
public static Func<object, string> StringEncoder = (o) => o == null ? null : $"\"{((string)o).Replace("\"", "\"\"")}\"";
public static Func<object, string> ObjectToStringEncoder = (o) => o == null ? null : o is string s ? StringEncoder(s) : o.ToString();
public static Func<object, string> ToStringEncoder = (o) => o == null ? null : o.ToString();
public static Func<object, string> CurrencyEncoder = (o) => ((decimal)o).ToString("C");
public static Func<object, string> NullableCurrencyEncoder = (o) => ((decimal?)o).HasValue ? ((decimal?)o).Value.ToString("C") : null;
public static Func<object, string> DateEncoder = (o) => ((DateTime)o).ToString(DateFormat);
public static Func<object, string> NullableDateEncoder = (o) => ((DateTime?)o).HasValue ? DateEncoder(o) : null;
public static Func<object, string> DateTimeEncoder = (o) => ((DateTime)o).ToString(DateTimeFormat);
public static Func<object, string> NullableDateTimeEncoder = (o) => ((DateTime?)o).HasValue ? DateTimeEncoder(o) : null;
public static Func<object, string> GetEncoder<T>()
=> GetEncoder(typeof(T));
public static Func<object, string> GetEncoder(Type type)
{
if (encoders.TryGetValue(type, out var encoder))
return encoder;
else
throw new NotSupportedException($"No encoder for type {type}");
}
}
} }
} }
@@ -8,7 +8,7 @@ using System.Text.Json.Serialization;
namespace Disco.Services.Exporting namespace Disco.Services.Exporting
{ {
public interface IExportContext public interface IExport
{ {
Guid Id { get; set; } Guid Id { get; set; }
string Name { get; set; } string Name { get; set; }
@@ -17,8 +17,8 @@ namespace Disco.Services.Exporting
ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status); ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status);
} }
public interface IExportContext<T, R> public interface IExport<T, R>
: IExportContext : IExport
where T : IExportOptions, new() where T : IExportOptions, new()
where R : IExportRecord where R : IExportRecord
{ {
@@ -34,6 +34,6 @@ namespace Disco.Services.Exporting
T Options { get; set; } T Options { get; set; }
List<R> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status); List<R> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status);
List<ExportFieldMetadata<R>> BuildMetadata(DiscoDataContext database, List<R> records, IScheduledTaskStatus status); ExportMetadata<R> BuildMetadata(DiscoDataContext database, List<R> records, IScheduledTaskStatus status);
} }
} }
+371
View File
@@ -0,0 +1,371 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Repository;
using Disco.Models.Services.Exporting;
using Disco.Models.Services.Jobs;
using Disco.Services.Exporting;
using Disco.Services.Jobs.JobQueues;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Disco.Services.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Disco.Services.Jobs
{
public class JobExport : IExport<JobExportOptions, JobExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public JobExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "JobExport";
public string ExcelWorksheetName { get; } = "JobExport";
public string ExcelTableName { get; } = "Jobs";
[JsonConstructor]
private JobExport()
{
}
public JobExport(string name, string description, bool timestampSuffix, JobExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public JobExport(JobExportOptions options)
: this("Job Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(this, database, status);
private IQueryable<Job> BuildFilteredRecords(DiscoDataContext database)
{
var o = Options;
var q = database.Jobs.Where(j => j.OpenedDate >= o.FilterStartDate);
if (o.FilterEndDate.HasValue)
q = q.Where(j => j.OpenedDate <= o.FilterEndDate);
if (o.FilterJobTypeId != null)
q = q.Where(j => j.JobTypeId == o.FilterJobTypeId);
if (o.FilterJobSubTypeIds?.Any() ?? false)
q = q.Where(j => j.JobSubTypes.Any(st => o.FilterJobSubTypeIds.Contains(st.Id)));
if (o.FilterJobQueueId.HasValue)
q = q.Where(j => j.JobQueues.Any(jq => !jq.RemovedDate.HasValue && jq.JobQueueId == o.FilterJobQueueId));
if (o.FilterJobStatusId != null)
{
if (o.FilterJobStatusId != Job.JobStatusIds.Closed)
q = q.Where(j => j.ClosedDate == null);
switch (o.FilterJobStatusId)
{
case Job.JobStatusIds.Open:
// already filtered
break;
case Job.JobStatusIds.AwaitingAccountingPayment:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.AccountingChargeAddedDate != null && j.JobMetaNonWarranty.AccountingChargePaidDate == null);
break;
case Job.JobStatusIds.AwaitingAccountingCharge:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.AccountingChargeRequiredDate == null && (j.JobMetaNonWarranty.AccountingChargePaidDate != null || j.JobMetaNonWarranty.AccountingChargeAddedDate != null));
break;
case Job.JobStatusIds.AwaitingDeviceReturn:
q = q.Where(j => j.DeviceReadyForReturn != null && j.DeviceReturnedDate == null);
break;
case Job.JobStatusIds.AwaitingInsuranceProcessing:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.IsInsuranceClaim && j.JobMetaInsurance.ClaimFormSentDate == null);
break;
case Job.JobStatusIds.AwaitingRepairs:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.RepairerLoggedDate != null && j.JobMetaNonWarranty.RepairerCompletedDate == null);
break;
case Job.JobStatusIds.AwaitingUserAction:
q = q.Where(j => j.WaitingForUserAction != null);
break;
case Job.JobStatusIds.AwaitingWarrantyRepair:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HWar && j.JobMetaWarranty.ExternalLoggedDate != null && j.JobMetaWarranty.ExternalCompletedDate == null);
break;
case Job.JobStatusIds.Closed:
q = q.Where(j => j.ClosedDate != null);
break;
default:
throw new ArgumentException($"Unknown Job Status Id: {o.FilterJobStatusId}", nameof(o.FilterJobStatusId));
}
}
return q;
}
public List<JobExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
database.Configuration.LazyLoadingEnabled = false;
database.Configuration.ProxyCreationEnabled = false;
var query = BuildFilteredRecords(database);
// Update Users
if (Options.UserDisplayName ||
Options.UserSurname ||
Options.UserGivenName ||
Options.UserPhoneNumber ||
Options.UserEmailAddress)
{
status.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Where(d => d.UserId != null).Select(d => d.UserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database, true);
}
catch (Exception) { } // Ignore Errors
}
}
// Update Last Network Logon Date
if (Options.DeviceLastNetworkLogon)
{
status.UpdateStatus(15, "Refreshing device last network logon dates from Active Directory");
try
{
Interop.ActiveDirectory.ADNetworkLogonDatesUpdateTask.UpdateLastNetworkLogonDates(database, ScheduledTaskMockStatus.Create("UpdateLastNetworkLogonDates"));
database.SaveChanges();
}
catch (Exception) { } // Ignore Errors
}
status.UpdateStatus(25, "Extracting records from the database");
var records = query.Select(j => new JobExportRecord()
{
Job = j,
JobTypeDescription = j.JobType.Description,
JobSubTypeDescriptions = j.JobSubTypes.Select(st => st.Description),
LogCount = j.JobLogs.Count(),
FirstLog = j.JobLogs.OrderBy(l => l.Id).FirstOrDefault(),
LastLog = j.JobLogs.OrderByDescending(l => l.Id).FirstOrDefault(),
AttachmentsCount = j.JobAttachments.Count(),
QueueCount = j.JobQueues.Count(),
QueueActiveCount = j.JobQueues.Count(q => !q.RemovedDate.HasValue),
QueueLatestActive = j.JobQueues.Where(q => !q.RemovedDate.HasValue).OrderByDescending(q => q.Id).FirstOrDefault(),
JobMetaWarranty = j.JobMetaWarranty,
JobMetaNonWarranty = j.JobMetaNonWarranty,
JobMetaInsurance = j.JobMetaInsurance,
User = j.User,
Device = j.Device,
DeviceModelId = j.Device.DeviceModelId,
DeviceModelDescription = j.Device.DeviceModel.Description,
DeviceModelManufacturer = j.Device.DeviceModel.Manufacturer,
DeviceModelModel = j.Device.DeviceModel.Model,
DeviceModelType = j.Device.DeviceModel.ModelType,
DeviceBatchId = j.Device.DeviceBatchId,
DeviceBatchName = j.Device.DeviceBatch.Name,
DeviceBatchPurchaseDate = j.Device.DeviceBatch.PurchaseDate,
DeviceBatchSupplier = j.Device.DeviceBatch.Supplier,
DeviceBatchUnitCost = j.Device.DeviceBatch.UnitCost,
DeviceBatchWarrantyValidUntilDate = j.Device.DeviceBatch.WarrantyValidUntil,
DeviceBatchInsuredDate = j.Device.DeviceBatch.InsuredDate,
DeviceBatchInsuranceSupplier = j.Device.DeviceBatch.InsuranceSupplier,
DeviceBatchInsuredUntilDate = j.Device.DeviceBatch.InsuredUntil,
DeviceProfileId = j.Device.DeviceProfileId,
DeviceProfileName = j.Device.DeviceProfile.Name,
DeviceProfileShortName = j.Device.DeviceProfile.ShortName,
}).ToList();
records.ForEach(r =>
{
if (Options.JobStatus)
{
r.JobStatus = JobExtensions.CalculateStatusId(
r.Job.ClosedDate,
r.Job.JobTypeId,
r.JobMetaWarranty?.ExternalLoggedDate,
r.JobMetaWarranty?.ExternalCompletedDate,
r.JobMetaNonWarranty?.RepairerLoggedDate,
r.JobMetaNonWarranty?.RepairerCompletedDate,
r.JobMetaNonWarranty?.AccountingChargeRequiredDate,
r.JobMetaNonWarranty?.AccountingChargeAddedDate,
r.JobMetaNonWarranty?.AccountingChargePaidDate,
r.JobMetaNonWarranty?.IsInsuranceClaim,
r.JobMetaInsurance?.ClaimFormSentDate,
r.Job.WaitingForUserAction,
r.Job.DeviceReadyForReturn,
r.Job.DeviceReturnedDate);
}
if (Options.UserDetailCustom && r.User != null)
{
var detailsService = new DetailsProviderService(database);
r.UserCustomDetails = detailsService.GetDetails(r.User);
}
});
return records;
}
public ExportMetadata<JobExportRecord> BuildMetadata(DiscoDataContext database, List<JobExportRecord> records, IScheduledTaskStatus status)
{
var metadata = new ExportMetadata<JobExportRecord>();
metadata.IgnoreShortNames.Add("Job");
metadata.IgnoreShortNames.Add("Job Details");
// Job
metadata.Add(Options, o => o.JobId, r => r.Job.Id);
metadata.Add(Options, o => o.JobStatus, r => Job.JobStatusIds.StatusDescriptions.TryGetValue(r.JobStatus, out var jobStatus) ? jobStatus : "Unknown");
metadata.Add(Options, o => o.JobType, r => r.JobTypeDescription);
metadata.Add(Options, o => o.JobSubTypes, r => string.Join(", ", r.JobSubTypeDescriptions));
metadata.Add(Options, o => o.JobOpenedDate, r => r.Job.OpenedDate);
metadata.Add(Options, o => o.JobOpenedUser, r => r.Job.OpenedTechUserId);
metadata.Add(Options, o => o.JobExpectedClosedDate, r => r.Job.ExpectedClosedDate);
metadata.Add(Options, o => o.JobClosedDate, r => r.Job.ClosedDate);
metadata.Add(Options, o => o.JobClosedUser, r => r.Job.ClosedTechUserId);
// Job Details
metadata.Add(Options, o => o.JobDeviceHeldDate, r => r.Job.DeviceHeld);
metadata.Add(Options, o => o.JobDeviceHeldUser, r => r.Job.DeviceHeldTechUserId);
metadata.Add(Options, o => o.JobDeviceHeldLocation, r => r.Job.DeviceHeldLocation);
metadata.Add(Options, o => o.JobDeviceReadyForReturnDate, r => r.Job.DeviceReadyForReturn);
metadata.Add(Options, o => o.JobDeviceReadyForReturnUser, r => r.Job.DeviceReadyForReturnTechUserId);
metadata.Add(Options, o => o.JobDeviceReturnedDate, r => r.Job.DeviceReturnedDate);
metadata.Add(Options, o => o.JobDeviceReturnedUser, r => r.Job.DeviceReturnedTechUserId);
metadata.Add(Options, o => o.JobWaitingForUserActionDate, r => r.Job.WaitingForUserAction);
// Job Logs
metadata.Add(Options, o => o.LogCount, r => r.LogCount);
metadata.Add(Options, o => o.LogFirstDate, r => r.FirstLog?.Timestamp);
metadata.Add(Options, o => o.LogFirstUser, r => r.FirstLog?.TechUserId);
metadata.Add(Options, o => o.LogFirstContent, r => r.FirstLog?.Comments);
metadata.Add(Options, o => o.LogLastDate, r => r.LastLog?.Timestamp);
metadata.Add(Options, o => o.LogLastUser, r => r.LastLog?.TechUserId);
metadata.Add(Options, o => o.LogLastContent, r => r.LastLog?.Comments);
// Attachments
metadata.Add(Options, o => o.AttachmentsCount, r => r.AttachmentsCount);
// Job Queues
metadata.Add(Options, o => o.JobQueueCount, r => r.QueueCount);
metadata.Add(Options, o => o.JobQueueActiveCount, r => r.QueueActiveCount);
metadata.Add(Options, o => o.JobQueueActiveLatest, r => r.QueueLatestActive?.JobQueueId == null ? null : JobQueueService.GetQueue(r.QueueLatestActive.JobQueueId).JobQueue.Name);
metadata.Add(Options, o => o.JobQueueActiveLatestAddedDate, r => r.QueueLatestActive?.AddedDate);
metadata.Add(Options, o => o.JobQueueActiveLatestAddedUser, r => r.QueueLatestActive?.AddedUserId);
// Warranty
metadata.Add(Options, o => o.JobWarrantyExternalName, r => r.JobMetaWarranty?.ExternalName);
metadata.Add(Options, o => o.JobWarrantyExternalReference, r => r.JobMetaWarranty?.ExternalReference);
metadata.Add(Options, o => o.JobWarrantyExternalLoggedDate, r => r.JobMetaWarranty?.ExternalLoggedDate);
metadata.Add(Options, o => o.JobWarrantyExternalCompletedDate, r => r.JobMetaWarranty?.ExternalCompletedDate);
// Non-Warranty
metadata.Add(Options, o => o.JobNonWarrantyAccountingChargeRequiredDate, r => r.JobMetaNonWarranty?.AccountingChargeRequiredDate);
metadata.Add(Options, o => o.JobNonWarrantyAccountingChargeAddedDate, r => r.JobMetaNonWarranty?.AccountingChargeAddedDate);
metadata.Add(Options, o => o.JobNonWarrantyAccountingChargePaidDate, r => r.JobMetaNonWarranty?.AccountingChargePaidDate);
metadata.Add(Options, o => o.JobNonWarrantyPurchaseOrderRaisedDate, r => r.JobMetaNonWarranty?.PurchaseOrderRaisedDate);
metadata.Add(Options, o => o.JobNonWarrantyPurchaseOrderReference, r => r.JobMetaNonWarranty?.PurchaseOrderReference);
metadata.Add(Options, o => o.JobNonWarrantyPurchaseOrderSentDate, r => r.JobMetaNonWarranty?.PurchaseOrderSentDate);
metadata.Add(Options, o => o.JobNonWarrantyInvoiceReceivedDate, r => r.JobMetaNonWarranty?.InvoiceReceivedDate);
metadata.Add(Options, o => o.JobNonWarrantyRepairerName, r => r.JobMetaNonWarranty?.RepairerName);
metadata.Add(Options, o => o.JobNonWarrantyRepairerLoggedDate, r => r.JobMetaNonWarranty?.RepairerLoggedDate);
metadata.Add(Options, o => o.JobNonWarrantyRepairerReference, r => r.JobMetaNonWarranty?.RepairerReference);
metadata.Add(Options, o => o.JobNonWarrantyRepairerCompletedDate, r => r.JobMetaNonWarranty?.RepairerCompletedDate);
// Insurance
metadata.Add(Options, o => o.JobMetaInsuranceLossOrDamageDate, r => r.JobMetaInsurance?.LossOrDamageDate);
metadata.Add(Options, o => o.JobMetaInsuranceEventLocation, r => r.JobMetaInsurance?.EventLocation);
metadata.Add(Options, o => o.JobMetaInsuranceDescription, r => r.JobMetaInsurance?.Description);
metadata.Add(Options, o => o.JobMetaInsuranceThirdPartyCausedName, r => r.JobMetaInsurance?.ThirdPartyCausedName);
metadata.Add(Options, o => o.JobMetaInsuranceThirdPartyCausedWhy, r => r.JobMetaInsurance?.ThirdPartyCausedWhy);
metadata.Add(Options, o => o.JobMetaInsuranceWitnessesNamesAddresses, r => r.JobMetaInsurance?.WitnessesNamesAddresses);
metadata.Add(Options, o => o.JobMetaInsuranceBurglaryTheftMethodOfEntry, r => r.JobMetaInsurance?.BurglaryTheftMethodOfEntry);
metadata.Add(Options, o => o.JobMetaInsurancePropertyLastSeenDate, r => r.JobMetaInsurance?.PropertyLastSeenDate);
metadata.Add(Options, o => o.JobMetaInsurancePoliceNotifiedStation, r => r.JobMetaInsurance?.PoliceNotifiedStation);
metadata.Add(Options, o => o.JobMetaInsurancePoliceNotifiedDate, r => r.JobMetaInsurance?.PoliceNotifiedDate);
metadata.Add(Options, o => o.JobMetaInsurancePoliceNotifiedCrimeReportNo, r => r.JobMetaInsurance?.PoliceNotifiedCrimeReportNo);
metadata.Add(Options, o => o.JobMetaInsuranceRecoverReduceAction, r => r.JobMetaInsurance?.RecoverReduceAction);
metadata.Add(Options, o => o.JobMetaInsuranceOtherInterestedParties, r => r.JobMetaInsurance?.OtherInterestedParties);
metadata.Add(Options, o => o.JobMetaInsuranceDateOfPurchase, r => r.JobMetaInsurance?.DateOfPurchase);
metadata.Add(Options, o => o.JobMetaInsuranceClaimFormSentDate, r => r.JobMetaInsurance?.ClaimFormSentDate);
metadata.Add(Options, o => o.JobMetaInsuranceInsurer, r => r.JobMetaInsurance?.Insurer);
metadata.Add(Options, o => o.JobMetaInsuranceInsurerReference, r => r.JobMetaInsurance?.InsurerReference);
// User Management
metadata.Add(Options, o => o.JobUserManagementFlags, r => r.Job.Flags?.ToString());
// User
metadata.Add(Options, o => o.UserId, r => r.User?.UserId);
metadata.Add(Options, o => o.UserDisplayName, r => r.User?.DisplayName);
metadata.Add(Options, o => o.UserSurname, r => r.User?.Surname);
metadata.Add(Options, o => o.UserGivenName, r => r.User?.GivenName);
metadata.Add(Options, o => o.UserPhoneNumber, r => r.User?.PhoneNumber);
metadata.Add(Options, o => o.UserEmailAddress, r => r.User?.EmailAddress);
// User Custom Details
if (Options.UserDetailCustom)
{
var keys = records.Where(r => r.UserCustomDetails != null).SelectMany(r => r.UserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
foreach (var key in keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
metadata.Add(key, r => r.UserCustomDetails != null && r.UserCustomDetails.TryGetValue(key, out var value) ? value : null);
}
}
// Device
metadata.Add(Options, o => o.DeviceSerialNumber, r => r.Device?.SerialNumber);
metadata.Add(Options, o => o.DeviceAssetNumber, r => r.Device?.AssetNumber);
metadata.Add(Options, o => o.DeviceLocation, r => r.Device?.Location);
metadata.Add(Options, o => o.DeviceComputerName, r => r.Device?.DeviceDomainId);
metadata.Add(Options, o => o.DeviceLastNetworkLogon, r => r.Device?.LastNetworkLogonDate);
metadata.Add(Options, o => o.DeviceCreatedDate, r => r.Device?.CreatedDate);
metadata.Add(Options, o => o.DeviceFirstEnrolledDate, r => r.Device?.EnrolledDate);
metadata.Add(Options, o => o.DeviceLastEnrolledDate, r => r.Device?.LastEnrolDate);
metadata.Add(Options, o => o.DeviceAllowUnauthenticatedEnrol, r => r.Device?.AllowUnauthenticatedEnrol);
metadata.Add(Options, o => o.DeviceDecommissionedDate, r => r.Device?.DecommissionedDate);
metadata.Add(Options, o => o.DeviceDecommissionedReason, r => r.Device?.DecommissionReason?.ToString());
// Model
metadata.Add(Options, o => o.DeviceModelId, r => r.DeviceModelId);
metadata.Add(Options, o => o.DeviceModelDescription, r => r.DeviceModelDescription);
metadata.Add(Options, o => o.DeviceModelManufacturer, r => r.DeviceModelManufacturer);
metadata.Add(Options, o => o.DeviceModelModel, r => r.DeviceModelModel);
metadata.Add(Options, o => o.DeviceModelType, r => r.DeviceModelType);
// Batch
metadata.Add(Options, o => o.DeviceBatchId, r => r.DeviceBatchId);
metadata.Add(Options, o => o.DeviceBatchName, r => r.DeviceBatchName);
metadata.Add(Options, o => o.DeviceBatchPurchaseDate, r => r.DeviceBatchPurchaseDate);
metadata.Add(Options, o => o.DeviceBatchSupplier, r => r.DeviceBatchSupplier);
metadata.Add(Options, o => o.DeviceBatchUnitCost, r => r.DeviceBatchUnitCost);
metadata.Add(Options, o => o.DeviceBatchWarrantyValidUntilDate, r => r.DeviceBatchWarrantyValidUntilDate);
metadata.Add(Options, o => o.DeviceBatchInsuredDate, r => r.DeviceBatchInsuredDate);
metadata.Add(Options, o => o.DeviceBatchInsuranceSupplier, r => r.DeviceBatchInsuranceSupplier);
metadata.Add(Options, o => o.DeviceBatchInsuredUntilDate, r => r.DeviceBatchInsuredUntilDate);
// Profile
metadata.Add(Options, o => o.DeviceProfileId, r => r.DeviceProfileId);
metadata.Add(Options, o => o.DeviceProfileName, r => r.DeviceProfileName);
metadata.Add(Options, o => o.DeviceProfileShortName, r => r.DeviceProfileShortName);
return metadata;
}
}
}
-411
View File
@@ -1,411 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Repository;
using Disco.Models.Services.Exporting;
using Disco.Models.Services.Jobs;
using Disco.Services.Exporting;
using Disco.Services.Jobs.JobQueues;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Disco.Services.Users;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Disco.Services.Jobs
{
using Metadata = ExportFieldMetadata<JobExportRecord>;
public class JobExportContext : IExportContext<JobExportOptions, JobExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public JobExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "JobExport";
public string ExcelWorksheetName { get; } = "JobExport";
public string ExcelTableName { get; } = "Jobs";
[JsonConstructor]
private JobExportContext()
{
}
public JobExportContext(string name, string description, bool timestampSuffix, JobExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public JobExportContext(JobExportOptions options)
: this("Job Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(database, this, status);
private IQueryable<Job> BuildFilteredRecords(DiscoDataContext database)
{
var o = Options;
var q = database.Jobs.Where(j => j.OpenedDate >= o.FilterStartDate);
if (o.FilterEndDate.HasValue)
q = q.Where(j => j.OpenedDate <= o.FilterEndDate);
if (o.FilterJobTypeId != null)
q = q.Where(j => j.JobTypeId == o.FilterJobTypeId);
if (o.FilterJobSubTypeIds?.Any() ?? false)
q = q.Where(j => j.JobSubTypes.Any(st => o.FilterJobSubTypeIds.Contains(st.Id)));
if (o.FilterJobQueueId.HasValue)
q = q.Where(j => j.JobQueues.Any(jq => !jq.RemovedDate.HasValue && jq.JobQueueId == o.FilterJobQueueId));
if (o.FilterJobStatusId != null)
{
if (o.FilterJobStatusId != Job.JobStatusIds.Closed)
q = q.Where(j => j.ClosedDate == null);
switch (o.FilterJobStatusId)
{
case Job.JobStatusIds.Open:
// already filtered
break;
case Job.JobStatusIds.AwaitingAccountingPayment:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.AccountingChargeAddedDate != null && j.JobMetaNonWarranty.AccountingChargePaidDate == null);
break;
case Job.JobStatusIds.AwaitingAccountingCharge:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.AccountingChargeRequiredDate == null && (j.JobMetaNonWarranty.AccountingChargePaidDate != null || j.JobMetaNonWarranty.AccountingChargeAddedDate != null));
break;
case Job.JobStatusIds.AwaitingDeviceReturn:
q = q.Where(j => j.DeviceReadyForReturn != null && j.DeviceReturnedDate == null);
break;
case Job.JobStatusIds.AwaitingInsuranceProcessing:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.IsInsuranceClaim && j.JobMetaInsurance.ClaimFormSentDate == null);
break;
case Job.JobStatusIds.AwaitingRepairs:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HNWar && j.JobMetaNonWarranty.RepairerLoggedDate != null && j.JobMetaNonWarranty.RepairerCompletedDate == null);
break;
case Job.JobStatusIds.AwaitingUserAction:
q = q.Where(j => j.WaitingForUserAction != null);
break;
case Job.JobStatusIds.AwaitingWarrantyRepair:
q = q.Where(j => j.JobTypeId == JobType.JobTypeIds.HWar && j.JobMetaWarranty.ExternalLoggedDate != null && j.JobMetaWarranty.ExternalCompletedDate == null);
break;
case Job.JobStatusIds.Closed:
q = q.Where(j => j.ClosedDate != null);
break;
default:
throw new ArgumentException($"Unknown Job Status Id: {o.FilterJobStatusId}", nameof(o.FilterJobStatusId));
}
}
return q;
}
public List<JobExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
database.Configuration.LazyLoadingEnabled = false;
database.Configuration.ProxyCreationEnabled = false;
var query = BuildFilteredRecords(database);
// Update Users
if (Options.UserDisplayName ||
Options.UserSurname ||
Options.UserGivenName ||
Options.UserPhoneNumber ||
Options.UserEmailAddress)
{
status.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Where(d => d.UserId != null).Select(d => d.UserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database);
}
catch (Exception) { } // Ignore Errors
}
}
// Update Last Network Logon Date
if (Options.DeviceLastNetworkLogon)
{
status.UpdateStatus(15, "Refreshing device last network logon dates from Active Directory");
try
{
Interop.ActiveDirectory.ADNetworkLogonDatesUpdateTask.UpdateLastNetworkLogonDates(database, ScheduledTaskMockStatus.Create("UpdateLastNetworkLogonDates"));
database.SaveChanges();
}
catch (Exception) { } // Ignore Errors
}
status.UpdateStatus(25, "Extracting records from the database");
var records = query.Select(j => new JobExportRecord()
{
Job = j,
JobTypeDescription = j.JobType.Description,
JobSubTypeDescriptions = j.JobSubTypes.Select(st => st.Description),
LogCount = j.JobLogs.Count(),
FirstLog = j.JobLogs.OrderBy(l => l.Id).FirstOrDefault(),
LastLog = j.JobLogs.OrderByDescending(l => l.Id).FirstOrDefault(),
AttachmentsCount = j.JobAttachments.Count(),
QueueCount = j.JobQueues.Count(),
QueueActiveCount = j.JobQueues.Count(q => !q.RemovedDate.HasValue),
QueueLatestActive = j.JobQueues.Where(q => !q.RemovedDate.HasValue).OrderByDescending(q => q.Id).FirstOrDefault(),
JobMetaWarranty = j.JobMetaWarranty,
JobMetaNonWarranty = j.JobMetaNonWarranty,
JobMetaInsurance = j.JobMetaInsurance,
User = j.User,
Device = j.Device,
DeviceModelId = j.Device.DeviceModelId,
DeviceModelDescription = j.Device.DeviceModel.Description,
DeviceModelManufacturer = j.Device.DeviceModel.Manufacturer,
DeviceModelModel = j.Device.DeviceModel.Model,
DeviceModelType = j.Device.DeviceModel.ModelType,
DeviceBatchId = j.Device.DeviceBatchId,
DeviceBatchName = j.Device.DeviceBatch.Name,
DeviceBatchPurchaseDate = j.Device.DeviceBatch.PurchaseDate,
DeviceBatchSupplier = j.Device.DeviceBatch.Supplier,
DeviceBatchUnitCost = j.Device.DeviceBatch.UnitCost,
DeviceBatchWarrantyValidUntilDate = j.Device.DeviceBatch.WarrantyValidUntil,
DeviceBatchInsuredDate = j.Device.DeviceBatch.InsuredDate,
DeviceBatchInsuranceSupplier = j.Device.DeviceBatch.InsuranceSupplier,
DeviceBatchInsuredUntilDate = j.Device.DeviceBatch.InsuredUntil,
DeviceProfileId = j.Device.DeviceProfileId,
DeviceProfileName = j.Device.DeviceProfile.Name,
DeviceProfileShortName = j.Device.DeviceProfile.ShortName,
}).ToList();
records.ForEach(r =>
{
if (Options.JobStatus)
{
r.JobStatus = JobExtensions.CalculateStatusId(
r.Job.ClosedDate,
r.Job.JobTypeId,
r.JobMetaWarranty?.ExternalLoggedDate,
r.JobMetaWarranty?.ExternalCompletedDate,
r.JobMetaNonWarranty?.RepairerLoggedDate,
r.JobMetaNonWarranty?.RepairerCompletedDate,
r.JobMetaNonWarranty?.AccountingChargeRequiredDate,
r.JobMetaNonWarranty?.AccountingChargeAddedDate,
r.JobMetaNonWarranty?.AccountingChargePaidDate,
r.JobMetaNonWarranty?.IsInsuranceClaim,
r.JobMetaInsurance?.ClaimFormSentDate,
r.Job.WaitingForUserAction,
r.Job.DeviceReadyForReturn,
r.Job.DeviceReturnedDate);
}
if (Options.UserDetailCustom && r.User != null)
{
var detailsService = new DetailsProviderService(database);
r.UserCustomDetails = detailsService.GetDetails(r.User);
}
});
return records;
}
public List<Metadata> BuildMetadata(DiscoDataContext database, List<JobExportRecord> records, IScheduledTaskStatus status)
{
IEnumerable<string> userDetailCustomKeys = null;
if (Options.UserDetailCustom)
userDetailCustomKeys = records.Where(r => r.UserCustomDetails != null).SelectMany(r => r.UserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var allAccessors = BuildRecordAccessors(userDetailCustomKeys);
return typeof(JobExportOptions).GetProperties()
.Where(p => p.PropertyType == typeof(bool))
.Select(p => new
{
property = p,
details = (DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault()
})
.Where(p => p.details != null && (bool)p.property.GetValue(Options))
.SelectMany(p =>
{
var fieldMetadata = allAccessors[p.property.Name];
fieldMetadata.ForEach(f =>
{
if (f.ColumnName == null)
f.ColumnName = (p.details.ShortName == "Job" || p.details.ShortName == "Job Details") ? p.details.Name : $"{p.details.ShortName} {p.details.Name}";
});
return fieldMetadata;
}).ToList();
}
private static Dictionary<string, List<Metadata>> BuildRecordAccessors(IEnumerable<string> userDetailCustomKeys)
{
const string DateFormat = "yyyy-MM-dd";
const string DateTimeFormat = DateFormat + " HH:mm:ss";
Func<object, string> csvStringEncoded = (o) => o == null ? null : $"\"{((string)o).Replace("\"", "\"\"")}\"";
Func<object, string> csvToStringEncoded = (o) => o == null ? null : o.ToString();
Func<object, string> csvCurrencyEncoded = (o) => ((decimal?)o).HasValue ? ((decimal?)o).Value.ToString("C") : null;
Func<object, string> csvDateEncoded = (o) => ((DateTime)o).ToString(DateFormat);
Func<object, string> csvDateTimeEncoded = (o) => ((DateTime)o).ToString(DateTimeFormat);
Func<object, string> csvNullableDateEncoded = (o) => ((DateTime?)o).HasValue ? csvDateEncoded(o) : null;
Func<object, string> csvNullableDateTimeEncoded = (o) => ((DateTime?)o).HasValue ? csvDateTimeEncoded(o) : null;
var metadata = new Dictionary<string, List<Metadata>>();
// Job
metadata.Add(nameof(JobExportOptions.JobId), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobId), typeof(int), r => r.Job.Id, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobStatus), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobStatus), typeof(string), r => Job.JobStatusIds.StatusDescriptions.TryGetValue(r.JobStatus, out var status) ? status : "Unknown", csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobType), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobType), typeof(string), r => r.JobTypeDescription, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobSubTypes), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobSubTypes), typeof(string), r => string.Join(", ", r.JobSubTypeDescriptions), csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobOpenedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobOpenedDate), typeof(DateTime), r => r.Job.OpenedDate, csvDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobOpenedUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobOpenedUser), typeof(string), r => r.Job.OpenedTechUserId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobExpectedClosedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobExpectedClosedDate), typeof(DateTime), r => r.Job.ExpectedClosedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobClosedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobClosedDate), typeof(DateTime), r => r.Job.ClosedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobClosedUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobClosedUser), typeof(string), r => r.Job.ClosedTechUserId, csvStringEncoded) });
// Job Details
metadata.Add(nameof(JobExportOptions.JobDeviceHeldDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobDeviceHeldDate), typeof(DateTime), r => r.Job.DeviceHeld, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobDeviceHeldUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobDeviceHeldUser), typeof(string), r => r.Job.DeviceHeldTechUserId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobDeviceHeldLocation), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobDeviceHeldLocation), typeof(string), r => r.Job.DeviceHeldLocation, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobDeviceReadyForReturnDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobDeviceReadyForReturnDate), typeof(DateTime), r => r.Job.DeviceReadyForReturn, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobDeviceReadyForReturnUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobDeviceReadyForReturnUser), typeof(string), r => r.Job.DeviceReadyForReturnTechUserId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobDeviceReturnedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobDeviceReturnedDate), typeof(DateTime), r => r.Job.DeviceReturnedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobDeviceReturnedUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobDeviceReturnedUser), typeof(string), r => r.Job.DeviceReturnedTechUserId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobWaitingForUserActionDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobWaitingForUserActionDate), typeof(DateTime), r => r.Job.WaitingForUserAction, csvNullableDateTimeEncoded) });
// Job Logs
metadata.Add(nameof(JobExportOptions.LogCount), new List<Metadata>() { new Metadata(nameof(JobExportOptions.LogCount), typeof(int), r => r.LogCount, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.LogFirstDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.LogFirstDate), typeof(DateTime), r => r.FirstLog?.Timestamp, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.LogFirstUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.LogFirstUser), typeof(string), r => r.FirstLog?.TechUserId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.LogFirstContent), new List<Metadata>() { new Metadata(nameof(JobExportOptions.LogFirstContent), typeof(string), r => r.FirstLog?.Comments, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.LogLastDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.LogLastDate), typeof(DateTime), r => r.LastLog?.Timestamp, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.LogLastUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.LogLastUser), typeof(string), r => r.LastLog?.TechUserId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.LogLastContent), new List<Metadata>() { new Metadata(nameof(JobExportOptions.LogLastContent), typeof(string), r => r.LastLog?.Comments, csvStringEncoded) });
// Attachments
metadata.Add(nameof(JobExportOptions.AttachmentsCount), new List<Metadata>() { new Metadata(nameof(JobExportOptions.AttachmentsCount), typeof(int), r => r.AttachmentsCount, csvToStringEncoded) });
// Job Queues
metadata.Add(nameof(JobExportOptions.JobQueueCount), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobQueueCount), typeof(int), r => r.QueueCount, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobQueueActiveCount), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobQueueActiveCount), typeof(int), r => r.QueueActiveCount, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobQueueActiveLatest), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobQueueActiveLatest), typeof(DateTime), r => r.QueueLatestActive?.JobQueueId == null ? null : JobQueueService.GetQueue(r.QueueLatestActive.JobQueueId).JobQueue.Name, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobQueueActiveLatestAddedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobQueueActiveLatestAddedDate), typeof(DateTime), r => r.QueueLatestActive?.AddedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobQueueActiveLatestAddedUser), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobQueueActiveLatestAddedUser), typeof(string), r => r.QueueLatestActive?.AddedUserId, csvStringEncoded) });
// Warranty
metadata.Add(nameof(JobExportOptions.JobWarrantyExternalName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobWarrantyExternalName), typeof(string), r => r.JobMetaWarranty?.ExternalName, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobWarrantyExternalReference), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobWarrantyExternalReference), typeof(string), r => r.JobMetaWarranty?.ExternalReference, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobWarrantyExternalLoggedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobWarrantyExternalLoggedDate), typeof(DateTime), r => r.JobMetaWarranty?.ExternalLoggedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobWarrantyExternalCompletedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobWarrantyExternalCompletedDate), typeof(DateTime), r => r.JobMetaWarranty?.ExternalCompletedDate, csvNullableDateTimeEncoded) });
// Non-Warranty
metadata.Add(nameof(JobExportOptions.JobNonWarrantyAccountingChargeRequiredDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyAccountingChargeRequiredDate), typeof(DateTime), r => r.JobMetaNonWarranty?.AccountingChargeRequiredDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyAccountingChargeAddedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyAccountingChargeAddedDate), typeof(DateTime), r => r.JobMetaNonWarranty?.AccountingChargeAddedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyAccountingChargePaidDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyAccountingChargePaidDate), typeof(DateTime), r => r.JobMetaNonWarranty?.AccountingChargePaidDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyPurchaseOrderRaisedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyPurchaseOrderRaisedDate), typeof(DateTime), r => r.JobMetaNonWarranty?.PurchaseOrderRaisedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyPurchaseOrderReference), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyPurchaseOrderReference), typeof(string), r => r.JobMetaNonWarranty?.PurchaseOrderReference, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyPurchaseOrderSentDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyPurchaseOrderSentDate), typeof(DateTime), r => r.JobMetaNonWarranty?.PurchaseOrderSentDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyInvoiceReceivedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyInvoiceReceivedDate), typeof(DateTime), r => r.JobMetaNonWarranty?.InvoiceReceivedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyRepairerName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyRepairerName), typeof(string), r => r.JobMetaNonWarranty?.RepairerName, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyRepairerLoggedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyRepairerLoggedDate), typeof(DateTime), r => r.JobMetaNonWarranty?.RepairerLoggedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyRepairerReference), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyRepairerReference), typeof(string), r => r.JobMetaNonWarranty?.RepairerReference, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobNonWarrantyRepairerCompletedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobNonWarrantyRepairerCompletedDate), typeof(DateTime), r => r.JobMetaNonWarranty?.RepairerCompletedDate, csvNullableDateTimeEncoded) });
// Insurance
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceLossOrDamageDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceLossOrDamageDate), typeof(DateTime), r => r.JobMetaInsurance?.LossOrDamageDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceEventLocation), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceEventLocation), typeof(string), r => r.JobMetaInsurance?.EventLocation, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceDescription), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceDescription), typeof(string), r => r.JobMetaInsurance?.Description, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceThirdPartyCausedName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceThirdPartyCausedName), typeof(string), r => r.JobMetaInsurance?.ThirdPartyCausedName, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceThirdPartyCausedWhy), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceThirdPartyCausedWhy), typeof(string), r => r.JobMetaInsurance?.ThirdPartyCausedWhy, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceWitnessesNamesAddresses), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceWitnessesNamesAddresses), typeof(string), r => r.JobMetaInsurance?.WitnessesNamesAddresses, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceBurglaryTheftMethodOfEntry), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceBurglaryTheftMethodOfEntry), typeof(string), r => r.JobMetaInsurance?.BurglaryTheftMethodOfEntry, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsurancePropertyLastSeenDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsurancePropertyLastSeenDate), typeof(DateTime), r => r.JobMetaInsurance?.PropertyLastSeenDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsurancePoliceNotifiedStation), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsurancePoliceNotifiedStation), typeof(string), r => r.JobMetaInsurance?.PoliceNotifiedStation, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsurancePoliceNotifiedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsurancePoliceNotifiedDate), typeof(DateTime), r => r.JobMetaInsurance?.PoliceNotifiedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsurancePoliceNotifiedCrimeReportNo), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsurancePoliceNotifiedCrimeReportNo), typeof(string), r => r.JobMetaInsurance?.PoliceNotifiedCrimeReportNo, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceRecoverReduceAction), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceRecoverReduceAction), typeof(string), r => r.JobMetaInsurance?.RecoverReduceAction, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceOtherInterestedParties), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceOtherInterestedParties), typeof(string), r => r.JobMetaInsurance?.OtherInterestedParties, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceDateOfPurchase), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceDateOfPurchase), typeof(DateTime), r => r.JobMetaInsurance?.DateOfPurchase, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceClaimFormSentDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceClaimFormSentDate), typeof(DateTime), r => r.JobMetaInsurance?.ClaimFormSentDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceInsurer), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceInsurer), typeof(string), r => r.JobMetaInsurance?.Insurer, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.JobMetaInsuranceInsurerReference), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobMetaInsuranceInsurerReference), typeof(string), r => r.JobMetaInsurance?.InsurerReference, csvStringEncoded) });
// User Management
metadata.Add(nameof(JobExportOptions.JobUserManagementFlags), new List<Metadata>() { new Metadata(nameof(JobExportOptions.JobUserManagementFlags), typeof(string), r => r.Job.Flags, csvToStringEncoded) });
// User
metadata.Add(nameof(JobExportOptions.UserId), new List<Metadata>() { new Metadata(nameof(JobExportOptions.UserId), typeof(string), r => r.User?.UserId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.UserDisplayName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.UserDisplayName), typeof(string), r => r.User?.DisplayName, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.UserSurname), new List<Metadata>() { new Metadata(nameof(JobExportOptions.UserSurname), typeof(string), r => r.User?.Surname, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.UserGivenName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.UserGivenName), typeof(string), r => r.User?.GivenName, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.UserPhoneNumber), new List<Metadata>() { new Metadata(nameof(JobExportOptions.UserPhoneNumber), typeof(string), r => r.User?.PhoneNumber, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.UserEmailAddress), new List<Metadata>() { new Metadata(nameof(JobExportOptions.UserEmailAddress), typeof(string), r => r.User?.EmailAddress, csvStringEncoded) });
if (userDetailCustomKeys != null)
{
var assignedUserDetailCustomFields = new List<Metadata>();
foreach (var detailKey in userDetailCustomKeys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
var key = detailKey;
assignedUserDetailCustomFields.Add(new Metadata(detailKey, detailKey, typeof(string), r => r.UserCustomDetails != null && r.UserCustomDetails.TryGetValue(key, out var value) ? value : null, csvStringEncoded));
}
metadata.Add(nameof(JobExportOptions.UserDetailCustom), assignedUserDetailCustomFields);
}
// Device
metadata.Add(nameof(JobExportOptions.DeviceSerialNumber), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceSerialNumber), typeof(string), r => r.Device?.SerialNumber, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceAssetNumber), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceAssetNumber), typeof(string), r => r.Device?.AssetNumber, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceLocation), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceLocation), typeof(string), r => r.Device?.Location, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceComputerName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceComputerName), typeof(string), r => r.Device?.DeviceDomainId, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceLastNetworkLogon), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceLastNetworkLogon), typeof(DateTime), r => r.Device?.LastNetworkLogonDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceCreatedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceCreatedDate), typeof(DateTime), r => r.Device?.CreatedDate, csvDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceFirstEnrolledDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceFirstEnrolledDate), typeof(DateTime), r => r.Device?.EnrolledDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceLastEnrolledDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceLastEnrolledDate), typeof(DateTime), r => r.Device?.LastEnrolDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceAllowUnauthenticatedEnrol), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceAllowUnauthenticatedEnrol), typeof(bool), r => r.Device?.AllowUnauthenticatedEnrol, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceDecommissionedDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceDecommissionedDate), typeof(DateTime), r => r.Device?.DecommissionedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceDecommissionedReason), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceDecommissionedReason), typeof(string), r => r.Device?.DecommissionReason, csvToStringEncoded) });
// Model
metadata.Add(nameof(JobExportOptions.DeviceModelId), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceModelId), typeof(int), r => r.DeviceModelId, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceModelDescription), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceModelDescription), typeof(string), r => r.DeviceModelDescription, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceModelManufacturer), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceModelManufacturer), typeof(string), r => r.DeviceModelManufacturer, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceModelModel), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceModelModel), typeof(string), r => r.DeviceModelModel, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceModelType), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceModelType), typeof(string), r => r.DeviceModelType, csvStringEncoded) });
// Batch
metadata.Add(nameof(JobExportOptions.DeviceBatchId), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchId), typeof(int), r => r.DeviceBatchId, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchName), typeof(string), r => r.DeviceBatchName, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchPurchaseDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchPurchaseDate), typeof(DateTime), r => r.DeviceBatchPurchaseDate, csvNullableDateEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchSupplier), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchSupplier), typeof(string), r => r.DeviceBatchSupplier, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchUnitCost), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchUnitCost), typeof(decimal), r => r.DeviceBatchUnitCost, csvCurrencyEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchWarrantyValidUntilDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchWarrantyValidUntilDate), typeof(DateTime), r => r.DeviceBatchWarrantyValidUntilDate, csvNullableDateEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchInsuredDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchInsuredDate), typeof(DateTime), r => r.DeviceBatchInsuredDate, csvNullableDateEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchInsuranceSupplier), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchInsuranceSupplier), typeof(string), r => r.DeviceBatchInsuranceSupplier, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceBatchInsuredUntilDate), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceBatchInsuredUntilDate), typeof(DateTime), r => r.DeviceBatchInsuredUntilDate, csvNullableDateEncoded) });
// Profile
metadata.Add(nameof(JobExportOptions.DeviceProfileId), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceProfileId), typeof(int), r => r.DeviceProfileId, csvToStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceProfileName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceProfileName), typeof(string), r => r.DeviceProfileName, csvStringEncoded) });
metadata.Add(nameof(JobExportOptions.DeviceProfileShortName), new List<Metadata>() { new Metadata(nameof(JobExportOptions.DeviceProfileShortName), typeof(string), r => r.DeviceProfileShortName, csvStringEncoded) });
return metadata;
}
}
}
+91
View File
@@ -0,0 +1,91 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Services.Exporting;
using Disco.Models.Services.Logging;
using Disco.Services.Exporting;
using Disco.Services.Logging.Models;
using Disco.Services.Tasks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Disco.Services.Logging
{
public class LogExport : IExport<LogExportOptions, LogLiveEvent>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public LogExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "DiscoIctLogs";
public string ExcelWorksheetName { get; } = "Disco ICT Logs";
public string ExcelTableName { get; } = "DiscoIctLogs";
[JsonConstructor]
private LogExport()
{
}
public LogExport(string name, string description, bool timestampSuffix, LogExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public LogExport(LogExportOptions options)
: this("Log Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(this, database, status);
public List<LogLiveEvent> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
var logRetriever = new ReadLogContext()
{
Start = Options.StartDate,
End = Options.EndDate,
Module = Options.ModuleId,
EventTypes = Options.EventTypeIds,
Take = Options.Take,
};
return logRetriever.Query(database);
}
public ExportMetadata<LogLiveEvent> BuildMetadata(DiscoDataContext database, List<LogLiveEvent> records, IScheduledTaskStatus status)
{
var metadata = new ExportMetadata<LogLiveEvent>
{
{ nameof(LogLiveEvent.Timestamp), r => r.Timestamp },
{ nameof(LogLiveEvent.ModuleId), r => r.ModuleId },
{ nameof(LogLiveEvent.ModuleName), r => r.ModuleName },
{ nameof(LogLiveEvent.ModuleDescription), r => r.ModuleDescription },
{ nameof(LogLiveEvent.EventTypeId), r => r.EventTypeId },
{ nameof(LogLiveEvent.EventTypeName), r => r.EventTypeName },
{ "Severity", r => r.EventTypeSeverity },
{ "Message", r => r.FormattedMessage }
};
if (records.Count > 0)
{
var argCount = records.Max(r => r.Arguments?.Length ?? 0);
for (var i = 0; i < argCount; i++)
{
var index = i;
var name = $"Data{i + 1:00}";
metadata.Add(name, r => (r.Arguments?.Length ?? 0) > index ? (r.Arguments[index] ?? "null") : null);
}
}
return metadata;
}
}
}
-102
View File
@@ -1,102 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Services.Exporting;
using Disco.Models.Services.Logging;
using Disco.Services.Exporting;
using Disco.Services.Logging.Models;
using Disco.Services.Tasks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Disco.Services.Logging
{
using Metadata = ExportFieldMetadata<LogLiveEvent>;
public class LogExportContext : IExportContext<LogExportOptions, LogLiveEvent>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public LogExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "DiscoIctLogs";
public string ExcelWorksheetName { get; } = "Disco ICT Logs";
public string ExcelTableName { get; } = "DiscoIctLogs";
[JsonConstructor]
private LogExportContext()
{
}
public LogExportContext(string name, string description, bool timestampSuffix, LogExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public LogExportContext(LogExportOptions options)
: this("Log Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(database, this, status);
public List<LogLiveEvent> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
var logRetriever = new ReadLogContext()
{
Start = Options.StartDate,
End = Options.EndDate,
Module = Options.ModuleId,
EventTypes = Options.EventTypeIds,
Take = Options.Take,
};
return logRetriever.Query(database);
}
public List<Metadata> BuildMetadata(DiscoDataContext database, List<LogLiveEvent> records, IScheduledTaskStatus status)
{
const string DateFormat = "yyyy-MM-dd";
const string DateTimeFormat = DateFormat + " HH:mm:ss";
Func<object, string> csvStringEncoded = (o) => o == null ? null : $"\"{((string)o).Replace("\"", "\"\"")}\"";
Func<object, string> csvToStringEncoded = (o) => o == null ? null : o.ToString();
Func<object, string> csvCurrencyEncoded = (o) => ((decimal?)o).HasValue ? ((decimal?)o).Value.ToString("C") : null;
Func<object, string> csvDateEncoded = (o) => ((DateTime)o).ToString(DateFormat);
Func<object, string> csvDateTimeEncoded = (o) => ((DateTime)o).ToString(DateTimeFormat);
Func<object, string> csvNullableDateEncoded = (o) => ((DateTime?)o).HasValue ? csvDateEncoded(o) : null;
Func<object, string> csvNullableDateTimeEncoded = (o) => ((DateTime?)o).HasValue ? csvDateTimeEncoded(o) : null;
var metadata = new List<Metadata>
{
new Metadata(nameof(LogLiveEvent.Timestamp), nameof(LogLiveEvent.Timestamp), typeof(DateTime), e => e.Timestamp, csvDateTimeEncoded),
new Metadata(nameof(LogLiveEvent.ModuleId), nameof(LogLiveEvent.ModuleId), typeof(int), e => e.ModuleId, csvToStringEncoded),
new Metadata(nameof(LogLiveEvent.ModuleName), nameof(LogLiveEvent.ModuleName), typeof(string), e => e.ModuleName, csvStringEncoded),
new Metadata(nameof(LogLiveEvent.ModuleDescription), nameof(LogLiveEvent.ModuleDescription), typeof(string), e => e.ModuleDescription, csvStringEncoded),
new Metadata(nameof(LogLiveEvent.EventTypeId), nameof(LogLiveEvent.EventTypeId), typeof(int), e => e.EventTypeId, csvToStringEncoded),
new Metadata(nameof(LogLiveEvent.EventTypeName), nameof(LogLiveEvent.EventTypeName), typeof(string), e => e.EventTypeName, csvStringEncoded),
new Metadata("Severity", "Severity", typeof(string), e => e.EventTypeSeverity, csvToStringEncoded),
new Metadata("Message", "Message", typeof(string), e => e.FormattedMessage, csvStringEncoded),
};
if (records.Count > 0)
{
var argCount = records.Max(r => r.Arguments?.Length ?? 0);
for (var i = 0; i < argCount; i++)
{
var index = i;
var name = $"Data{i + 1:00}";
metadata.Add(new Metadata(name, name, typeof(string), e => (e.Arguments?.Length ?? 0) > index ? (e.Arguments[index] ?? "null") : null, csvStringEncoded));
}
}
return metadata;
}
}
}
@@ -0,0 +1,140 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Services.Exporting;
using Disco.Models.Services.Users.UserFlags;
using Disco.Services.Exporting;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace Disco.Services.Users.UserFlags
{
public class UserFlagExport : IExport<UserFlagExportOptions, UserFlagExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public UserFlagExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "UserFlagExport";
public string ExcelWorksheetName { get; } = "UserFlagExport";
public string ExcelTableName { get; } = "UserFlags";
[JsonConstructor]
private UserFlagExport()
{
}
public UserFlagExport(string name, string description, bool timestampSuffix, UserFlagExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public UserFlagExport(UserFlagExportOptions options)
: this("User Flag Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(this, database, status);
public List<UserFlagExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
var query = database.UserFlagAssignments
.Include(a => a.User.UserDetails)
.Include(a => a.UserFlag)
.Where(a => Options.UserFlagIds.Contains(a.UserFlagId));
if (Options.CurrentOnly)
query = query.Where(a => !a.RemovedDate.HasValue);
// Update Users
if (Options.HasAssignedUserDetails())
{
status.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Select(d => d.UserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database, true);
}
catch (Exception) { } // Ignore Errors
}
}
status.UpdateStatus(15, "Extracting records from the database");
var records = query.Select(a => new UserFlagExportRecord()
{
Assignment = a
}).ToList();
if (Options.UserDetailCustom)
{
status.UpdateStatus(50, "Extracting custom user detail records");
var detailsService = new DetailsProviderService(database);
var cache = new Dictionary<string, Dictionary<string, string>>(StringComparer.Ordinal);
foreach (var record in records)
{
if (!cache.TryGetValue(record.Assignment.UserId, out var details))
details = detailsService.GetDetails(record.Assignment.User);
record.UserCustomDetails = details;
}
}
return records;
}
public ExportMetadata<UserFlagExportRecord> BuildMetadata(DiscoDataContext database, List<UserFlagExportRecord> records, IScheduledTaskStatus status)
{
status.UpdateStatus(80, "Building metadata");
var metadata = new ExportMetadata<UserFlagExportRecord>();
metadata.IgnoreShortNames.Add("User Flag");
// User Flag
metadata.Add(Options, o => o.Id, r => r.Assignment.UserFlagId);
metadata.Add(Options, o => o.Name, r => r.Assignment.UserFlag.Name);
metadata.Add(Options, o => o.Description, r => r.Assignment.UserFlag.Description);
metadata.Add(Options, o => o.Icon, r => r.Assignment.UserFlag.Icon);
metadata.Add(Options, o => o.IconColour, r => r.Assignment.UserFlag.IconColour);
metadata.Add(Options, o => o.AssignmentId, r => r.Assignment.Id);
metadata.Add(Options, o => o.AddedDate, r => r.Assignment.AddedDate);
metadata.Add(Options, o => o.AddedUserId, r => r.Assignment.AddedUserId);
metadata.Add(Options, o => o.RemovedUserId, r => r.Assignment.RemovedUserId);
metadata.Add(Options, o => o.RemovedDate, r => r.Assignment.RemovedDate);
metadata.Add(Options, o => o.Comments, r => r.Assignment.Comments);
// User
metadata.Add(Options, o => o.UserId, r => r.Assignment.User?.UserId);
metadata.Add(Options, o => o.UserDisplayName, r => r.Assignment.User?.DisplayName);
metadata.Add(Options, o => o.UserSurname, r => r.Assignment.User?.Surname);
metadata.Add(Options, o => o.UserGivenName, r => r.Assignment.User?.GivenName);
metadata.Add(Options, o => o.UserPhoneNumber, r => r.Assignment.User?.PhoneNumber);
metadata.Add(Options, o => o.UserEmailAddress, r => r.Assignment.User?.EmailAddress);
// User Custom Details
if (Options.UserDetailCustom)
{
var keys = records.Where(r => r.UserCustomDetails != null).SelectMany(r => r.UserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
foreach (var key in keys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
metadata.Add(key, r => r.UserCustomDetails != null && r.UserCustomDetails.TryGetValue(key, out var value) ? value : null);
}
}
return metadata;
}
}
}
@@ -1,186 +0,0 @@
using Disco.Data.Repository;
using Disco.Models.Exporting;
using Disco.Models.Services.Exporting;
using Disco.Models.Services.Users.UserFlags;
using Disco.Services.Exporting;
using Disco.Services.Plugins.Features.DetailsProvider;
using Disco.Services.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
namespace Disco.Services.Users.UserFlags
{
using Metadata = ExportFieldMetadata<UserFlagExportRecord>;
public class UserFlagExportContext : IExportContext<UserFlagExportOptions, UserFlagExportRecord>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool TimestampSuffix { get; set; }
public UserFlagExportOptions Options { get; set; }
public string SuggestedFilenamePrefix { get; } = "UserFlagExport";
public string ExcelWorksheetName { get; } = "UserFlagExport";
public string ExcelTableName { get; } = "UserFlags";
[JsonConstructor]
private UserFlagExportContext()
{
}
public UserFlagExportContext(string name, string description, bool timestampSuffix, UserFlagExportOptions options)
{
Id = Guid.NewGuid();
Name = name;
Description = description;
TimestampSuffix = timestampSuffix;
Options = options;
}
public UserFlagExportContext(UserFlagExportOptions options)
: this("User Flag Export", null, true, options)
{
}
public ExportResult Export(DiscoDataContext database, IScheduledTaskStatus status)
=> Exporter.Export(database, this, status);
public List<UserFlagExportRecord> BuildRecords(DiscoDataContext database, IScheduledTaskStatus status)
{
var query = database.UserFlagAssignments
.Include(a => a.User.UserDetails)
.Include(a => a.UserFlag)
.Where(a => Options.UserFlagIds.Contains(a.UserFlagId));
if (Options.CurrentOnly)
query = query.Where(a => !a.RemovedDate.HasValue);
// Update Users
if (Options.UserDisplayName ||
Options.UserSurname ||
Options.UserGivenName ||
Options.UserPhoneNumber ||
Options.UserEmailAddress)
{
status.UpdateStatus(5, "Refreshing user details from Active Directory");
var userIds = query.Select(d => d.UserId).Distinct().ToList();
foreach (var userId in userIds)
{
try
{
UserService.GetUser(userId, database);
}
catch (Exception) { } // Ignore Errors
}
}
status.UpdateStatus(15, "Extracting records from the database");
var records = query.Select(a => new UserFlagExportRecord()
{
Assignment = a
}).ToList();
if (Options.UserDetailCustom)
{
status.UpdateStatus(50, "Extracting custom user detail records");
var detailsService = new DetailsProviderService(database);
var cache = new Dictionary<string, Dictionary<string, string>>(StringComparer.Ordinal);
foreach (var record in records)
{
if (!cache.TryGetValue(record.Assignment.UserId, out var details))
details = detailsService.GetDetails(record.Assignment.User);
record.UserCustomDetails = details;
}
}
return records;
}
public List<Metadata> BuildMetadata(DiscoDataContext database, List<UserFlagExportRecord> records, IScheduledTaskStatus status)
{
status.UpdateStatus(80, "Building metadata");
IEnumerable<string> userDetailCustomKeys = null;
if (Options.UserDetailCustom)
userDetailCustomKeys = records.Where(r => r.UserCustomDetails != null).SelectMany(r => r.UserCustomDetails.Keys).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var accessors = BuildAccessors(userDetailCustomKeys);
return typeof(UserFlagExportOptions).GetProperties()
.Where(p => p.PropertyType == typeof(bool))
.Select(p => new
{
property = p,
details = (DisplayAttribute)p.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault()
})
.Where(p => p.details != null && p.property.Name != nameof(Options.CurrentOnly) && (bool)p.property.GetValue(Options))
.SelectMany(p =>
{
var fieldMetadata = accessors[p.property.Name];
fieldMetadata.ForEach(f =>
{
if (f.ColumnName == null)
f.ColumnName = (p.details.ShortName == "User Flag") ? p.details.Name : $"{p.details.ShortName} {p.details.Name}";
});
return fieldMetadata;
}).ToList();
}
private static Dictionary<string, List<Metadata>> BuildAccessors(IEnumerable<string> userDetailsCustomKeys)
{
const string DateFormat = "yyyy-MM-dd";
const string DateTimeFormat = DateFormat + " HH:mm:ss";
Func<object, string> csvStringEncoded = (o) => o == null ? null : $"\"{((string)o).Replace("\"", "\"\"")}\"";
Func<object, string> csvToStringEncoded = (o) => o == null ? null : o.ToString();
Func<object, string> csvCurrencyEncoded = (o) => ((decimal?)o).HasValue ? ((decimal?)o).Value.ToString("C") : null;
Func<object, string> csvDateEncoded = (o) => ((DateTime)o).ToString(DateFormat);
Func<object, string> csvDateTimeEncoded = (o) => ((DateTime)o).ToString(DateTimeFormat);
Func<object, string> csvNullableDateEncoded = (o) => ((DateTime?)o).HasValue ? csvDateEncoded(o) : null;
Func<object, string> csvNullableDateTimeEncoded = (o) => ((DateTime?)o).HasValue ? csvDateTimeEncoded(o) : null;
var metadata = new Dictionary<string, List<Metadata>>();
// User Flag
metadata.Add(nameof(UserFlagExportOptions.Id), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.Id), typeof(string), r => r.Assignment.UserFlagId, csvToStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.Name), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.Name), typeof(string), r => r.Assignment.UserFlag.Name, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.Description), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.Description), typeof(string), r => r.Assignment.UserFlag.Description, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.Icon), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.Icon), typeof(string), r => r.Assignment.UserFlag.Icon, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.IconColour), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.IconColour), typeof(string), r => r.Assignment.UserFlag.IconColour, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.AssignmentId), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.AssignmentId), typeof(string), r => r.Assignment.Id, csvToStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.AddedDate), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.AddedDate), typeof(string), r => r.Assignment.AddedDate, csvDateTimeEncoded) });
metadata.Add(nameof(UserFlagExportOptions.AddedUserId), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.AddedUserId), typeof(string), r => r.Assignment.AddedUserId, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.RemovedUserId), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.RemovedUserId), typeof(string), r => r.Assignment.RemovedUserId, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.RemovedDate), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.RemovedDate), typeof(string), r => r.Assignment.RemovedDate, csvNullableDateTimeEncoded) });
metadata.Add(nameof(UserFlagExportOptions.Comments), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.Comments), typeof(string), r => r.Assignment.Comments, csvStringEncoded) });
// User
metadata.Add(nameof(UserFlagExportOptions.UserId), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.UserId), typeof(string), r => r.Assignment.User?.UserId, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.UserDisplayName), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.UserDisplayName), typeof(string), r => r.Assignment.User?.DisplayName, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.UserSurname), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.UserSurname), typeof(string), r => r.Assignment.User?.Surname, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.UserGivenName), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.UserGivenName), typeof(string), r => r.Assignment.User?.GivenName, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.UserPhoneNumber), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.UserPhoneNumber), typeof(string), r => r.Assignment.User?.PhoneNumber, csvStringEncoded) });
metadata.Add(nameof(UserFlagExportOptions.UserEmailAddress), new List<Metadata>() { new Metadata(nameof(UserFlagExportOptions.UserEmailAddress), typeof(string), r => r.Assignment.User?.EmailAddress, csvStringEncoded) });
if (userDetailsCustomKeys != null)
{
var userDetailCustomFields = new List<Metadata>();
foreach (var detailKey in userDetailsCustomKeys.OrderBy(k => k, StringComparer.OrdinalIgnoreCase))
{
var key = detailKey;
userDetailCustomFields.Add(new Metadata(detailKey, detailKey, typeof(string), r => r.UserCustomDetails != null && r.UserCustomDetails.TryGetValue(key, out var value) ? value : null, csvStringEncoded));
}
metadata.Add(nameof(UserFlagExportOptions.UserDetailCustom), userDetailCustomFields);
}
return metadata;
}
}
}
@@ -697,7 +697,7 @@ namespace Disco.Web.Areas.API.Controllers
Database.SaveChanges(); Database.SaveChanges();
// Start Export // Start Export
var exportContext = new DeviceExportContext(Model.Options); var exportContext = new DeviceExport(Model.Options);
var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Device.Export(id, null, null))); var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Device.Export(id, null, null)));
// Try waiting for completion // Try waiting for completion
@@ -412,7 +412,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new ArgumentNullException(nameof(Model)); throw new ArgumentNullException(nameof(Model));
// Start Export // Start Export
var exportContext = new DeviceFlagExportContext(Model.Options); var exportContext = new DeviceFlagExport(Model.Options);
var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Config.DeviceFlag.Export(id, null, null))); var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Config.DeviceFlag.Export(id, null, null)));
// Try waiting for completion // Try waiting for completion
@@ -2179,7 +2179,7 @@ namespace Disco.Web.Areas.API.Controllers
Database.SaveChanges(); Database.SaveChanges();
// Start Export // Start Export
var exportContext = new JobExportContext(model.Options); var exportContext = new JobExport(model.Options);
var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Job.Export(id))); var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Job.Export(id)));
// Try waiting for completion // Try waiting for completion
@@ -52,7 +52,7 @@ namespace Disco.Web.Areas.API.Controllers
EventTypeIds = EventTypeIds, EventTypeIds = EventTypeIds,
Take = Take, Take = Take,
}; };
var exportContext = new LogExportContext(options); var exportContext = new LogExport(options);
var export = exportContext.Export(Database, ScheduledTaskMockStatus.Create("Log Export")); var export = exportContext.Export(Database, ScheduledTaskMockStatus.Create("Log Export"));
@@ -417,7 +417,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new ArgumentNullException(nameof(Model)); throw new ArgumentNullException(nameof(Model));
// Start Export // Start Export
var exportContext = new UserFlagExportContext(Model.Options); var exportContext = new UserFlagExport(Model.Options);
var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Config.UserFlag.Export(id, null, null))); var taskContext = ExportTask.ScheduleNowCacheResult(exportContext, id => Url.Action(MVC.Config.UserFlag.Export(id, null, null)));
// Try waiting for completion // Try waiting for completion
@@ -191,5 +191,5 @@
<h4><i class="fa fa-lg fa-cog fa-spin" title="Please Wait"></i>Exporting device flags...</h4> <h4><i class="fa fa-lg fa-cog fa-spin" title="Please Wait"></i>Exporting device flags...</h4>
</div> </div>
<div class="actionBar"> <div class="actionBar">
<a id="DeviceFlag_Export_Button" href="#" class="button">Export Device Flags</a> <button type="button" id="DeviceFlag_Export_Button" class="button">Export Device Flags</button>
</div> </div>
@@ -730,15 +730,15 @@ WriteLiteral("></i>Exporting device flags...</h4>\r\n</div>\r\n<div");
WriteLiteral(" class=\"actionBar\""); WriteLiteral(" class=\"actionBar\"");
WriteLiteral(">\r\n <a"); WriteLiteral(">\r\n <button");
WriteLiteral(" type=\"button\"");
WriteLiteral(" id=\"DeviceFlag_Export_Button\""); WriteLiteral(" id=\"DeviceFlag_Export_Button\"");
WriteLiteral(" href=\"#\"");
WriteLiteral(" class=\"button\""); WriteLiteral(" class=\"button\"");
WriteLiteral(">Export Device Flags</a>\r\n</div>\r\n"); WriteLiteral(">Export Device Flags</button>\r\n</div>\r\n");
} }
} }
@@ -191,5 +191,5 @@
<h4><i class="fa fa-lg fa-cog fa-spin" title="Please Wait"></i>Exporting user flags...</h4> <h4><i class="fa fa-lg fa-cog fa-spin" title="Please Wait"></i>Exporting user flags...</h4>
</div> </div>
<div class="actionBar"> <div class="actionBar">
<a id="UserFlag_Export_Button" href="#" class="button">Export User Flags</a> <button type="button" id="UserFlag_Export_Button" class="button">Export User Flags</button>
</div> </div>
@@ -730,15 +730,15 @@ WriteLiteral("></i>Exporting user flags...</h4>\r\n</div>\r\n<div");
WriteLiteral(" class=\"actionBar\""); WriteLiteral(" class=\"actionBar\"");
WriteLiteral(">\r\n <a"); WriteLiteral(">\r\n <button");
WriteLiteral(" type=\"button\"");
WriteLiteral(" id=\"UserFlag_Export_Button\""); WriteLiteral(" id=\"UserFlag_Export_Button\"");
WriteLiteral(" href=\"#\"");
WriteLiteral(" class=\"button\""); WriteLiteral(" class=\"button\"");
WriteLiteral(">Export User Flags</a>\r\n</div>\r\n"); WriteLiteral(">Export User Flags</button>\r\n</div>\r\n");
} }
} }
+1 -1
View File
@@ -123,7 +123,7 @@ namespace Disco.Web.Controllers
DeviceProfiles = Database.DeviceProfiles.OrderBy(dp => dp.Name).Select(dp => new { Key = dp.Id, Value = dp.Name }).ToList().Select(i => new KeyValuePair<int, string>(i.Key, i.Value)) DeviceProfiles = Database.DeviceProfiles.OrderBy(dp => dp.Name).Select(dp => new { Key = dp.Id, Value = dp.Name }).ToList().Select(i => new KeyValuePair<int, string>(i.Key, i.Value))
}; };
if (ExportTask.TryFromCache(exportId.Value, out var context)) if (ExportTask.TryFromCache(exportId, out var context))
{ {
m.ExportId = context.Id; m.ExportId = context.Id;
m.ExportResult = context.Result; m.ExportResult = context.Result;