qol: inline variable declaration

This commit is contained in:
Gary Sharp
2025-07-20 15:12:33 +10:00
parent 5792771ea1
commit 1add4ee0f5
89 changed files with 1229 additions and 1512 deletions
+1 -2
View File
@@ -296,8 +296,7 @@ namespace Disco.BI.Interop.Pdf
} }
else else
{ {
Expression fieldExpression = null; if (expressionCache.TryGetValue(pdfFieldKey, out var fieldExpression))
if (expressionCache.TryGetValue(pdfFieldKey, out fieldExpression))
{ {
if (fieldExpression.IsDynamic) if (fieldExpression.IsDynamic)
{ {
+1 -2
View File
@@ -105,8 +105,7 @@ namespace Disco.Client.Interop
{ {
foreach (var thumbprint in RemoveThumbprints) foreach (var thumbprint in RemoveThumbprints)
{ {
List<X509Certificate2> certificates; if (existingThumbprints.TryGetValue(thumbprint, out var certificates) && !addedThumbprints.Contains(thumbprint))
if (existingThumbprints.TryGetValue(thumbprint, out certificates) && !addedThumbprints.Contains(thumbprint))
{ {
foreach (var certificate in certificates) foreach (var certificate in certificates)
{ {
+1 -2
View File
@@ -539,8 +539,7 @@ namespace Disco.Client.Interop
// if serial number is absent attempt using UUID if valid // if serial number is absent attempt using UUID if valid
if (string.IsNullOrWhiteSpace(deviceHardware.SerialNumber)) if (string.IsNullOrWhiteSpace(deviceHardware.SerialNumber))
{ {
Guid uuidGuid; if (Guid.TryParse(deviceHardware.UUID, out var uuidGuid) && uuidGuid != Guid.Empty)
if (Guid.TryParse(deviceHardware.UUID, out uuidGuid) && uuidGuid != Guid.Empty)
{ {
deviceHardware.SerialNumber = $"UUID{uuidGuid:N}"; deviceHardware.SerialNumber = $"UUID{uuidGuid:N}";
} }
+9 -23
View File
@@ -17,16 +17,13 @@ namespace Disco.Client.Interop
{ {
try try
{ {
IntPtr wlanHandle;
uint wlanServiceVersion;
if (WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanServiceVersion, out wlanHandle) == WlanApi.ERROR_SUCCESS) if (WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out var wlanServiceVersion, out var wlanHandle) == WlanApi.ERROR_SUCCESS)
{ {
try try
{ {
IntPtr wlanInterfacesPtr;
if (WlanApi.WlanEnumInterfaces(wlanHandle, IntPtr.Zero, out wlanInterfacesPtr) == WlanApi.ERROR_SUCCESS) if (WlanApi.WlanEnumInterfaces(wlanHandle, IntPtr.Zero, out var wlanInterfacesPtr) == WlanApi.ERROR_SUCCESS)
{ {
try try
{ {
@@ -69,12 +66,10 @@ namespace Disco.Client.Interop
{ {
try try
{ {
IntPtr wlanHandle;
uint wlanServiceVersion;
uint interopResult; uint interopResult;
// Connect to wireless service // Connect to wireless service
interopResult = WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanServiceVersion, out wlanHandle); interopResult = WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out var wlanServiceVersion, out var wlanHandle);
if (interopResult == WlanApi.ERROR_SERVICE_NOT_ACTIVE) if (interopResult == WlanApi.ERROR_SERVICE_NOT_ACTIVE)
{ {
// Indicates the Wlan service has not been started on the client // Indicates the Wlan service has not been started on the client
@@ -109,10 +104,9 @@ namespace Disco.Client.Interop
private static List<WirelessProfile> GetWirelessProfiles(IntPtr wlanHandle) private static List<WirelessProfile> GetWirelessProfiles(IntPtr wlanHandle)
{ {
uint interopResult; uint interopResult;
IntPtr wlanInterfacesPtr;
// Enumerate wireless interfaces // Enumerate wireless interfaces
interopResult = WlanApi.WlanEnumInterfaces(wlanHandle, IntPtr.Zero, out wlanInterfacesPtr); interopResult = WlanApi.WlanEnumInterfaces(wlanHandle, IntPtr.Zero, out var wlanInterfacesPtr);
if (interopResult != WlanApi.ERROR_SUCCESS) if (interopResult != WlanApi.ERROR_SUCCESS)
{ {
throw new Exception($"Unable to list interfaces with the local wireless service. WlanEnumInterfaces returned: {interopResult}"); throw new Exception($"Unable to list interfaces with the local wireless service. WlanEnumInterfaces returned: {interopResult}");
@@ -124,9 +118,8 @@ namespace Disco.Client.Interop
foreach (var wlanInterface in wlanInterfaces.InterfaceInfo) foreach (var wlanInterface in wlanInterfaces.InterfaceInfo)
{ {
IntPtr wlanProfilesPtr;
// Enumerate wireless profiles for interface // Enumerate wireless profiles for interface
interopResult = WlanApi.WlanGetProfileList(wlanHandle, wlanInterface.InterfaceGuid, IntPtr.Zero, out wlanProfilesPtr); interopResult = WlanApi.WlanGetProfileList(wlanHandle, wlanInterface.InterfaceGuid, IntPtr.Zero, out var wlanProfilesPtr);
if (interopResult != WlanApi.ERROR_SUCCESS) if (interopResult != WlanApi.ERROR_SUCCESS)
{ {
throw new Exception($"Unable to list wireless profiles for the {wlanInterface.InterfaceGuid} interface with the local wireless service. WlanGetProfileList returned: {interopResult}"); throw new Exception($"Unable to list wireless profiles for the {wlanInterface.InterfaceGuid} interface with the local wireless service. WlanGetProfileList returned: {interopResult}");
@@ -165,12 +158,10 @@ namespace Disco.Client.Interop
try try
{ {
IntPtr wlanHandle;
uint wlanServiceVersion;
uint interopResult; uint interopResult;
// Connect to wireless service // Connect to wireless service
interopResult = WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanServiceVersion, out wlanHandle); interopResult = WlanApi.WlanOpenHandle(WlanApi.WLAN_API_VERSION_2_0, IntPtr.Zero, out var wlanServiceVersion, out var wlanHandle);
if (interopResult == WlanApi.ERROR_SERVICE_NOT_ACTIVE) if (interopResult == WlanApi.ERROR_SERVICE_NOT_ACTIVE)
{ {
// Indicates the Wlan service has not been started on the client // Indicates the Wlan service has not been started on the client
@@ -243,9 +234,8 @@ namespace Disco.Client.Interop
} }
else else
{ {
uint pdwReasonCode;
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nAdding Wireless Profile '{addProfile.Name}' on '{adapter.NetConnectionID}'", true, -1, 1000); Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nAdding Wireless Profile '{addProfile.Name}' on '{adapter.NetConnectionID}'", true, -1, 1000);
interopResult = WlanApi.WlanSetProfile(wlanHandle, adapter.ConnectionIdentifier, 0, addProfile.ProfileXml, null, true, IntPtr.Zero, out pdwReasonCode); interopResult = WlanApi.WlanSetProfile(wlanHandle, adapter.ConnectionIdentifier, 0, addProfile.ProfileXml, null, true, IntPtr.Zero, out var pdwReasonCode);
if (interopResult != WlanApi.ERROR_SUCCESS) if (interopResult != WlanApi.ERROR_SUCCESS)
{ {
@@ -285,11 +275,8 @@ namespace Disco.Client.Interop
else else
{ {
// Load profile // Load profile
IntPtr pstrProfileXml;
uint pdwFlags;
IntPtr pdwGrantAccess;
interopResult = WlanApi.WlanGetProfile(wlanHandle, adapter.ConnectionIdentifier, profileName, IntPtr.Zero, out pstrProfileXml, out pdwFlags, out pdwGrantAccess); interopResult = WlanApi.WlanGetProfile(wlanHandle, adapter.ConnectionIdentifier, profileName, IntPtr.Zero, out var pstrProfileXml, out var pdwFlags, out var pdwGrantAccess);
if (interopResult == WlanApi.ERROR_SUCCESS) if (interopResult == WlanApi.ERROR_SUCCESS)
{ {
@@ -312,10 +299,9 @@ namespace Disco.Client.Interop
if (!XNode.DeepEquals(originalProfileXml, transformedProfileXml)) if (!XNode.DeepEquals(originalProfileXml, transformedProfileXml))
{ {
// Set Profile // Set Profile
uint pdwReasonCode;
Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nModifying Wireless Profile '{profileName}' on '{adapter.NetConnectionID}'", true, -1, 1000); Presentation.UpdateStatus("Enrolling Device", $"Configuring Wireless Profiles\r\nModifying Wireless Profile '{profileName}' on '{adapter.NetConnectionID}'", true, -1, 1000);
transformProfileXml = transformedProfileXml.ToString(SaveOptions.None); transformProfileXml = transformedProfileXml.ToString(SaveOptions.None);
interopResult = WlanApi.WlanSetProfile(wlanHandle, adapter.ConnectionIdentifier, 0, transformProfileXml, null, true, IntPtr.Zero, out pdwReasonCode); interopResult = WlanApi.WlanSetProfile(wlanHandle, adapter.ConnectionIdentifier, 0, transformProfileXml, null, true, IntPtr.Zero, out var pdwReasonCode);
if (interopResult != WlanApi.ERROR_SUCCESS) if (interopResult != WlanApi.ERROR_SUCCESS)
{ {
@@ -34,7 +34,7 @@ namespace Disco.ClientBootstrapper.Interop
Name = (string)wmiObject.GetPropertyValue("Name"); Name = (string)wmiObject.GetPropertyValue("Name");
NetConnectionID = (string)wmiObject.GetPropertyValue("NetConnectionID"); NetConnectionID = (string)wmiObject.GetPropertyValue("NetConnectionID");
Speed = (UInt64)wmiObject.GetPropertyValue("Speed"); Speed = (UInt64)wmiObject.GetPropertyValue("Speed");
var connectionStatus = ConnectionStatus; _ = ConnectionStatus;
IsWireless = true; IsWireless = true;
try try
{ {
@@ -53,19 +53,17 @@ namespace Disco.ClientBootstrapper.Interop
if (IsWireless) if (IsWireless)
{ {
IntPtr handle = IntPtr.Zero; IntPtr handle = IntPtr.Zero;
uint negotiatedVersion;
try try
{ {
if (NetworkInterop.WlanOpenHandle(1, IntPtr.Zero, out negotiatedVersion, ref handle) != 0) if (NetworkInterop.WlanOpenHandle(1, IntPtr.Zero, out var negotiatedVersion, ref handle) != 0)
throw new NotSupportedException("This network adapter does not support Wireless"); throw new NotSupportedException("This network adapter does not support Wireless");
IntPtr ptr = new IntPtr(); IntPtr ptr = new IntPtr();
uint dataSize;
var interfaceGuid = Guid; var interfaceGuid = Guid;
if (NetworkInterop.WlanQueryInterface(handle, ref interfaceGuid, NetworkInterop.WLAN_INTF_OPCODE.wlan_intf_opcode_interface_state, IntPtr.Zero, out dataSize, ref ptr, IntPtr.Zero) != 0) if (NetworkInterop.WlanQueryInterface(handle, ref interfaceGuid, NetworkInterop.WLAN_INTF_OPCODE.wlan_intf_opcode_interface_state, IntPtr.Zero, out var dataSize, ref ptr, IntPtr.Zero) != 0)
throw new NotSupportedException("This network adapter does not support Wireless"); throw new NotSupportedException("This network adapter does not support Wireless");
LastWirelessConnectionStatus = Marshal.ReadInt32(ptr); LastWirelessConnectionStatus = Marshal.ReadInt32(ptr);
@@ -196,11 +196,10 @@ namespace Disco.ClientBootstrapper.Interop
{ {
IntPtr wlanHandle = IntPtr.Zero; IntPtr wlanHandle = IntPtr.Zero;
uint negotiatedVersion;
try try
{ {
if (WlanOpenHandle(1, IntPtr.Zero, out negotiatedVersion, ref wlanHandle) != 0) if (WlanOpenHandle(1, IntPtr.Zero, out var negotiatedVersion, ref wlanHandle) != 0)
throw new NotSupportedException("This device does not support Wireless"); throw new NotSupportedException("This device does not support Wireless");
// Add Profile to Each Wireless Adapter // Add Profile to Each Wireless Adapter
@@ -241,8 +240,7 @@ namespace Disco.ClientBootstrapper.Interop
var pInterfaceGuid = interfaceGuid; var pInterfaceGuid = interfaceGuid;
var pProfileXml = ProfileXml; var pProfileXml = ProfileXml;
uint pFlag = 0; uint pFlag = 0;
uint failReason; return WlanSetProfile(WlanHandle, ref pInterfaceGuid, pFlag, pProfileXml, null, true, IntPtr.Zero, out _) == 0;
return (WlanSetProfile(WlanHandle, ref pInterfaceGuid, pFlag, pProfileXml, null, true, IntPtr.Zero, out failReason) == 0);
} }
} }
@@ -58,16 +58,15 @@ namespace Disco.ClientBootstrapper.Interop
public RegistryInterop(RegistryHives hive, string subKey, string filePath) public RegistryInterop(RegistryHives hive, string subKey, string filePath)
{ {
int token = 0; int token = 0;
int retval = 0;
TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES();
TOKEN_PRIVILEGES TP2 = new TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES TP2 = new TOKEN_PRIVILEGES();
LUID RestoreLuid = new LUID(); LUID RestoreLuid = new LUID();
LUID BackupLuid = new LUID(); LUID BackupLuid = new LUID();
retval = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token);
retval = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestoreLuid); LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestoreLuid);
retval = LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackupLuid); LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackupLuid);
TP.PrivilegeCount = 1; TP.PrivilegeCount = 1;
TP.Attributes = SE_PRIVILEGE_ENABLED; TP.Attributes = SE_PRIVILEGE_ENABLED;
TP.Luid = RestoreLuid; TP.Luid = RestoreLuid;
@@ -75,8 +74,8 @@ namespace Disco.ClientBootstrapper.Interop
TP2.Attributes = SE_PRIVILEGE_ENABLED; TP2.Attributes = SE_PRIVILEGE_ENABLED;
TP2.Luid = BackupLuid; TP2.Luid = BackupLuid;
retval = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0); AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0);
retval = AdjustTokenPrivileges(token, 0, ref TP2, 1024, 0, 0); AdjustTokenPrivileges(token, 0, ref TP2, 1024, 0, 0);
uint regHive = (uint)hive; uint regHive = (uint)hive;
@@ -39,21 +39,20 @@ namespace Disco.ClientBootstrapper.Interop
// End Removed 2012-11-23 G# // End Removed 2012-11-23 G#
// Added 2012-11-23 G# - Migrate to Win32 PInvoke Shutdown // Added 2012-11-23 G# - Migrate to Win32 PInvoke Shutdown
bool result;
TokPriv1Luid tp; TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess(); IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero; IntPtr htok = IntPtr.Zero;
result = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1; tp.Count = 1;
tp.Luid = 0; tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED; tp.Attr = SE_PRIVILEGE_ENABLED;
result = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid); LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
result = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
result = ExitWindowsEx(flag, 0); ExitWindowsEx(flag, 0);
// End Added 2012-11-23 G# // End Added 2012-11-23 G#
} }
@@ -684,7 +684,7 @@ namespace Disco.ClientBootstrapper.Interop.WIMInterop
IntPtr windowsImageHandle = IntPtr.Zero; IntPtr windowsImageHandle = IntPtr.Zero;
int rc = -1; int rc = -1;
windowsImageHandle = NativeMethods.WimCreateFile(imageFile, access, mode, 0, 0, out creationResult); windowsImageHandle = NativeMethods.WimCreateFile(imageFile, access, mode, 0, 0, out _);
rc = Marshal.GetLastWin32Error(); rc = Marshal.GetLastWin32Error();
if (windowsImageHandle == IntPtr.Zero) if (windowsImageHandle == IntPtr.Zero)
{ {
@@ -1062,7 +1062,7 @@ namespace Disco.ClientBootstrapper.Interop.WIMInterop
IntPtr info = IntPtr.Zero, sizeOfInfo = IntPtr.Zero; IntPtr info = IntPtr.Zero, sizeOfInfo = IntPtr.Zero;
bool status; bool status;
status = NativeMethods.WimGetImageInformation(handle, out info, out sizeOfInfo); status = NativeMethods.WimGetImageInformation(handle, out info, out _);
int rc = Marshal.GetLastWin32Error(); int rc = Marshal.GetLastWin32Error();
if (status == false) if (status == false)
@@ -1221,7 +1221,7 @@ namespace Disco.ClientBootstrapper.Interop.WIMInterop
void void
RegisterCallback(MessageCallback callback) RegisterCallback(MessageCallback callback)
{ {
uint callbackZeroBasedIndex = NativeMethods.WimRegisterMessageCallback(IntPtr.Zero, callback, IntPtr.Zero); NativeMethods.WimRegisterMessageCallback(IntPtr.Zero, callback, IntPtr.Zero);
int rc = Marshal.GetLastWin32Error(); int rc = Marshal.GetLastWin32Error();
if (rc != 0) if (rc != 0)
{ {
@@ -1254,7 +1254,7 @@ namespace Disco.ClientBootstrapper.Interop.WIMInterop
UnregisterMessageCallback(MessageCallback registeredCallback) UnregisterMessageCallback(MessageCallback registeredCallback)
{ {
bool status = NativeMethods.WimUnregisterMessageCallback(IntPtr.Zero, registeredCallback); bool status = NativeMethods.WimUnregisterMessageCallback(IntPtr.Zero, registeredCallback);
int rc = Marshal.GetLastWin32Error(); _ = Marshal.GetLastWin32Error();
if (status != true) if (status != true)
{ {
// //
+11 -20
View File
@@ -53,11 +53,9 @@ namespace Disco.Data.Configuration
{ {
var cache = Cache(Database); var cache = Cache(Database);
ConfigurationCacheScopeType scopeCache; if (cache.TryGetValue(Scope, out var scopeCache))
if (cache.TryGetValue(Scope, out scopeCache))
{ {
ConfigurationCacheItemType item = default(ConfigurationCacheItemType); if (scopeCache.TryGetValue(Key, out var item))
if (scopeCache.TryGetValue(Key, out item))
return item; return item;
} }
@@ -93,8 +91,7 @@ namespace Disco.Data.Configuration
Database.ConfigurationItems.Add(configItem); Database.ConfigurationItems.Add(configItem);
// Add Item to Cache // Add Item to Cache
ConfigurationCacheScopeType scopeCache; if (!cacheStore.TryGetValue(Scope, out var scopeCache))
if (!cacheStore.TryGetValue(Scope, out scopeCache))
{ {
scopeCache = new ConfigurationCacheScopeType(); scopeCache = new ConfigurationCacheScopeType();
cacheStore.TryAdd(Scope, scopeCache); cacheStore.TryAdd(Scope, scopeCache);
@@ -134,10 +131,9 @@ namespace Disco.Data.Configuration
Database.ConfigurationItems.Remove(configItem); Database.ConfigurationItems.Remove(configItem);
// Remove item from Cache // Remove item from Cache
ConfigurationCacheScopeType scopeCache; if (cacheStore.TryGetValue(Scope, out var scopeCache))
if (cacheStore.TryGetValue(Scope, out scopeCache))
{ {
scopeCache.TryRemove(Key, out item); scopeCache.TryRemove(Key, out _);
} }
return null; return null;
@@ -148,8 +144,7 @@ namespace Disco.Data.Configuration
configItem.Value = Value; configItem.Value = Value;
// Update Cache // Update Cache
ConfigurationCacheScopeType scopeCache; if (cacheStore.TryGetValue(Scope, out var scopeCache))
if (cacheStore.TryGetValue(Scope, out scopeCache))
{ {
scopeCache.TryRemove(Key, out item); scopeCache.TryRemove(Key, out item);
item = new ConfigurationCacheItemType(configItem, ObjectValue); item = new ConfigurationCacheItemType(configItem, ObjectValue);
@@ -167,8 +162,7 @@ namespace Disco.Data.Configuration
{ {
var cache = ConfigurationCache.cacheStore; var cache = ConfigurationCache.cacheStore;
ConfigurationCacheScopeType scopeCache; if (cache.TryGetValue(ExistingItem.Item1.Scope, out var scopeCache))
if (cache.TryGetValue(ExistingItem.Item1.Scope, out scopeCache))
{ {
ConfigurationCacheItemType newItem = new ConfigurationCacheItemType(ExistingItem.Item1, Value); ConfigurationCacheItemType newItem = new ConfigurationCacheItemType(ExistingItem.Item1, Value);
scopeCache.TryUpdate(ExistingItem.Item1.Key, newItem, ExistingItem); scopeCache.TryUpdate(ExistingItem.Item1.Key, newItem, ExistingItem);
@@ -340,8 +334,7 @@ namespace Disco.Data.Configuration
{ {
var cache = Cache(Database); var cache = Cache(Database);
ConfigurationCacheScopeType scopeCache; if (cache.TryGetValue(Scope, out var scopeCache))
if (cache.TryGetValue(Scope, out scopeCache))
{ {
return scopeCache.Keys.ToList(); return scopeCache.Keys.ToList();
} }
@@ -365,8 +358,7 @@ namespace Disco.Data.Configuration
// Remove item from Cache // Remove item from Cache
if (cacheStore != null) if (cacheStore != null)
{ {
ConfigurationCacheScopeType scopeCache; cacheStore.TryRemove(Scope, out var scopeCache);
cacheStore.TryRemove(Scope, out scopeCache);
} }
} }
} }
@@ -406,10 +398,9 @@ namespace Disco.Data.Configuration
// Remove item from Cache // Remove item from Cache
if (cacheItem != null) if (cacheItem != null)
{ {
ConfigurationCacheScopeType scopeCache; if (cacheStore.TryGetValue(Scope, out var scopeCache))
if (cacheStore.TryGetValue(Scope, out scopeCache))
{ {
scopeCache.TryRemove(Key, out cacheItem); scopeCache.TryRemove(Key, out _);
} }
} }
} }
+2 -3
View File
@@ -264,8 +264,7 @@ namespace Disco.Data.Repository
foreach (var configurationItem in configurationItems) foreach (var configurationItem in configurationItems)
{ {
int profileId = int.Parse(configurationItem.Scope.Substring(configurationItem.Scope.IndexOf(":") + 1)); int profileId = int.Parse(configurationItem.Scope.Substring(configurationItem.Scope.IndexOf(":") + 1));
DeviceProfile dp; if (deviceProfiles.TryGetValue(profileId, out var dp))
if (deviceProfiles.TryGetValue(profileId, out dp))
{ {
switch (configurationItem.Key) switch (configurationItem.Key)
{ {
@@ -273,7 +272,7 @@ namespace Disco.Data.Repository
dp.ComputerNameTemplate = configurationItem.Value; dp.ComputerNameTemplate = configurationItem.Value;
break; break;
case "DistributionType": case "DistributionType":
dp.DistributionType = (DeviceProfile.DistributionTypes)(int.Parse(configurationItem.Value)); dp.DistributionType = (DeviceProfile.DistributionTypes)int.Parse(configurationItem.Value);
break; break;
case "OrganisationalUnit": case "OrganisationalUnit":
dp.OrganisationalUnit = configurationItem.Value; dp.OrganisationalUnit = configurationItem.Value;
@@ -49,9 +49,8 @@ namespace Disco.Data.Repository.Monitor
private static Type EntityTypeFromProxy(Type EntityProxyType) private static Type EntityTypeFromProxy(Type EntityProxyType)
{ {
Type EntityType;
if (entityProxyTypeCache.TryGetValue(EntityProxyType, out EntityType)) if (entityProxyTypeCache.TryGetValue(EntityProxyType, out var EntityType))
return EntityType; return EntityType;
EntityType = EntityProxyType; EntityType = EntityProxyType;
@@ -245,8 +245,7 @@ namespace Disco.Services
{ {
string thumbnailFilePath = attachment.RepositoryThumbnailFilename(Database); string thumbnailFilePath = attachment.RepositoryThumbnailFilename(Database);
Image thumbnail; if (attachment.GenerateThumbnail(AttachmentStream, out var thumbnail))
if (attachment.GenerateThumbnail(AttachmentStream, out thumbnail))
{ {
thumbnail.SaveJpg(90, thumbnailFilePath); thumbnail.SaveJpg(90, thumbnailFilePath);
} }
@@ -260,8 +259,7 @@ namespace Disco.Services
using (var attachmentStream = File.OpenRead(attachment.RepositoryFilename(Database))) using (var attachmentStream = File.OpenRead(attachment.RepositoryFilename(Database)))
{ {
Image thumbnail; if (attachment.GenerateThumbnail(attachmentStream, out var thumbnail))
if (attachment.GenerateThumbnail(attachmentStream, out thumbnail))
{ {
thumbnail.SaveJpg(90, thumbnailFilePath); thumbnail.SaveJpg(90, thumbnailFilePath);
} }
@@ -2,6 +2,7 @@
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Models.Services.Authorization; using Disco.Models.Services.Authorization;
using Disco.Services.Users; using Disco.Services.Users;
using System;
namespace Disco.Services namespace Disco.Services
{ {
@@ -10,8 +11,9 @@ namespace Disco.Services
public static void Delete(this IRoleToken roleToken, DiscoDataContext Database) public static void Delete(this IRoleToken roleToken, DiscoDataContext Database)
{ {
var role = Database.AuthorizationRoles.Find(roleToken.Role.Id); var role = Database.AuthorizationRoles.Find(roleToken.Role.Id)
UserService.DeleteAuthorizationRole(Database, roleToken.Role); ?? throw new ArgumentException("Role not found", nameof(roleToken));
UserService.DeleteAuthorizationRole(Database, role);
} }
public static void Delete(this AuthorizationRole role, DiscoDataContext Database) public static void Delete(this AuthorizationRole role, DiscoDataContext Database)
+9 -21
View File
@@ -533,39 +533,27 @@ namespace Disco.Services.Authorization
} }
internal static Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> GetClaimDefinition(string ClaimKey) { internal static Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> GetClaimDefinition(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
return claimDef;
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef)) throw new ArgumentException("Unknown Claim Key", nameof(ClaimKey));
throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return new Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool>(claimDef.Item1, claimDef.Item2, claimDef.Item3, claimDef.Item4, claimDef.Item5);
} }
public static Func<RoleClaims, bool> GetClaimAccessor(string ClaimKey) { public static Func<RoleClaims, bool> GetClaimAccessor(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef))
throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return claimDef.Item1; return claimDef.Item1;
throw new ArgumentException("Unknown Claim Key", nameof(ClaimKey));
} }
public static Action<RoleClaims, bool> GetClaimSetter(string ClaimKey) { public static Action<RoleClaims, bool> GetClaimSetter(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef))
throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return claimDef.Item2; return claimDef.Item2;
throw new ArgumentException("Unknown Claim Key", nameof(ClaimKey));
} }
public static Tuple<string, string, bool> GetClaimDetails(string ClaimKey) { public static Tuple<string, string, bool> GetClaimDetails(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
return Tuple.Create(claimDef.Item3, claimDef.Item4, claimDef.Item5);
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef))
throw new ArgumentException("Unknown Claim Key", "ClaimKey"); throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return new Tuple<string, string, bool>(claimDef.Item3, claimDef.Item4, claimDef.Item5);
} }
public static RoleClaims BuildClaims(IEnumerable<string> ClaimKeys){ public static RoleClaims BuildClaims(IEnumerable<string> ClaimKeys){
+9 -21
View File
@@ -85,39 +85,27 @@ namespace Disco.Services.Authorization
} }
internal static Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> GetClaimDefinition(string ClaimKey) { internal static Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> GetClaimDefinition(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
return claimDef;
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef)) throw new ArgumentException("Unknown Claim Key", nameof(ClaimKey));
throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return new Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool>(claimDef.Item1, claimDef.Item2, claimDef.Item3, claimDef.Item4, claimDef.Item5);
} }
public static Func<RoleClaims, bool> GetClaimAccessor(string ClaimKey) { public static Func<RoleClaims, bool> GetClaimAccessor(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef))
throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return claimDef.Item1; return claimDef.Item1;
throw new ArgumentException("Unknown Claim Key", nameof(ClaimKey));
} }
public static Action<RoleClaims, bool> GetClaimSetter(string ClaimKey) { public static Action<RoleClaims, bool> GetClaimSetter(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef))
throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return claimDef.Item2; return claimDef.Item2;
throw new ArgumentException("Unknown Claim Key", nameof(ClaimKey));
} }
public static Tuple<string, string, bool> GetClaimDetails(string ClaimKey) { public static Tuple<string, string, bool> GetClaimDetails(string ClaimKey) {
Tuple<Func<RoleClaims, bool>, Action<RoleClaims, bool>, string, string, bool> claimDef; if (_roleClaims.TryGetValue(ClaimKey, out var claimDef))
return Tuple.Create(claimDef.Item3, claimDef.Item4, claimDef.Item5);
if (!_roleClaims.TryGetValue(ClaimKey, out claimDef))
throw new ArgumentException("Unknown Claim Key", "ClaimKey"); throw new ArgumentException("Unknown Claim Key", "ClaimKey");
return new Tuple<string, string, bool>(claimDef.Item3, claimDef.Item4, claimDef.Item5);
} }
public static RoleClaims BuildClaims(IEnumerable<string> ClaimKeys){ public static RoleClaims BuildClaims(IEnumerable<string> ClaimKeys){
@@ -88,8 +88,7 @@ namespace Disco.Services
{ {
foreach (var certificateProviderId in dp.CertificateProviders.Split(',')) foreach (var certificateProviderId in dp.CertificateProviders.Split(','))
{ {
PluginFeatureManifest featureManifest = null; if (Plugins.Plugins.TryGetPluginFeature(certificateProviderId.Trim(), typeof(CertificateProviderFeature), out var featureManifest))
if (Plugins.Plugins.TryGetPluginFeature(certificateProviderId.Trim(), typeof(CertificateProviderFeature), out featureManifest))
{ {
yield return featureManifest; yield return featureManifest;
} }
@@ -103,8 +102,7 @@ namespace Disco.Services
{ {
foreach (var certificateAuthorityProviderId in dp.CertificateAuthorityProviders.Split(',')) foreach (var certificateAuthorityProviderId in dp.CertificateAuthorityProviders.Split(','))
{ {
PluginFeatureManifest featureManifest = null; if (Plugins.Plugins.TryGetPluginFeature(certificateAuthorityProviderId.Trim(), typeof(CertificateAuthorityProviderFeature), out var featureManifest))
if (Plugins.Plugins.TryGetPluginFeature(certificateAuthorityProviderId.Trim(), typeof(CertificateAuthorityProviderFeature), out featureManifest))
{ {
yield return featureManifest; yield return featureManifest;
} }
@@ -118,8 +116,7 @@ namespace Disco.Services
{ {
foreach (var wirelessProfileProviderId in dp.WirelessProfileProviders.Split(',')) foreach (var wirelessProfileProviderId in dp.WirelessProfileProviders.Split(','))
{ {
PluginFeatureManifest featureManifest = null; if (Plugins.Plugins.TryGetPluginFeature(wirelessProfileProviderId.Trim(), typeof(WirelessProfileProviderFeature), out var featureManifest))
if (Plugins.Plugins.TryGetPluginFeature(wirelessProfileProviderId.Trim(), typeof(WirelessProfileProviderFeature), out featureManifest))
{ {
yield return featureManifest; yield return featureManifest;
} }
@@ -92,10 +92,9 @@ namespace Disco.Services.Devices.Enrolment
var devices = database.Devices.Include("DeviceDetails").ToList(); var devices = database.Devices.Include("DeviceDetails").ToList();
Tuple<string, string> addressResult;
foreach (var device in devices) foreach (var device in devices)
{ {
if (addresses.TryGetValue(device.SerialNumber.ToLower(), out addressResult)) if (addresses.TryGetValue(device.SerialNumber.ToLower(), out var addressResult))
{ {
if (!string.IsNullOrEmpty(addressResult.Item1)) if (!string.IsNullOrEmpty(addressResult.Item1))
device.DeviceDetails.LanMacAddress(device, addressResult.Item1); device.DeviceDetails.LanMacAddress(device, addressResult.Item1);
@@ -73,9 +73,8 @@ namespace Disco.Services.Devices.Enrolment
foreach (var node in profilerData.OfType<DictionaryNode>()) foreach (var node in profilerData.OfType<DictionaryNode>())
{ {
var nodeItems = ((ArrayNode)node["_items"]); var nodeItems = ((ArrayNode)node["_items"]);
PNode nodeDataType;
if (node.TryGetValue("_dataType", out nodeDataType) && nodeDataType is StringNode) if (node.TryGetValue("_dataType", out var nodeDataType) && nodeDataType is StringNode)
{ {
switch (((StringNode)nodeDataType).Value) switch (((StringNode)nodeDataType).Value)
{ {
@@ -374,11 +374,10 @@ namespace Disco.Services.Devices.Enrolment
else else
device.DeviceDomainId = $@"{domain.NetBiosName}\{Request.ComputerName}"; device.DeviceDomainId = $@"{domain.NetBiosName}\{Request.ComputerName}";
string offlineProvisionDiagnosicInfo;
EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, device.SerialNumber, device.DeviceDomainId); EnrolmentLog.LogSessionTaskProvisioningADAccount(sessionId, device.SerialNumber, device.DeviceDomainId);
adMachineAccount = domainController.Value.RetrieveADMachineAccount(device.DeviceDomainId); adMachineAccount = domainController.Value.RetrieveADMachineAccount(device.DeviceDomainId);
response.OfflineDomainJoinManifest = domainController.Value.OfflineDomainJoinProvision(device.DeviceDomainId, device.DeviceProfile.OrganisationalUnit, ref adMachineAccount, out offlineProvisionDiagnosicInfo); response.OfflineDomainJoinManifest = domainController.Value.OfflineDomainJoinProvision(device.DeviceDomainId, device.DeviceProfile.OrganisationalUnit, ref adMachineAccount, out var offlineProvisionDiagnosicInfo);
EnrolmentLog.LogSessionDiagnosticInformation(sessionId, offlineProvisionDiagnosicInfo); EnrolmentLog.LogSessionDiagnosticInformation(sessionId, offlineProvisionDiagnosicInfo);
@@ -415,8 +414,7 @@ namespace Disco.Services.Devices.Enrolment
domain = ActiveDirectory.Context.GetDomainFromDistinguishedName(device.DeviceProfile.OrganisationalUnit); domain = ActiveDirectory.Context.GetDomainFromDistinguishedName(device.DeviceProfile.OrganisationalUnit);
var calculatedComputerName = device.ComputerNameRender(Database, domain); var calculatedComputerName = device.ComputerNameRender(Database, domain);
string calculatedAccountUsername; ActiveDirectory.ParseDomainAccountId(calculatedComputerName, out string calculatedAccountUsername);
ActiveDirectory.ParseDomainAccountId(calculatedComputerName, out calculatedAccountUsername);
if (!Request.ComputerName.Equals(calculatedAccountUsername, StringComparison.OrdinalIgnoreCase)) if (!Request.ComputerName.Equals(calculatedAccountUsername, StringComparison.OrdinalIgnoreCase))
{ {
@@ -428,9 +426,8 @@ namespace Disco.Services.Devices.Enrolment
response.ComputerName = calculatedAccountUsername; response.ComputerName = calculatedAccountUsername;
// Create New Account // Create New Account
string offlineProvisionDiagnosicInfo;
response.OfflineDomainJoinManifest = domainController.Value.OfflineDomainJoinProvision(device.DeviceDomainId, device.DeviceProfile.OrganisationalUnit, ref adMachineAccount, out offlineProvisionDiagnosicInfo); response.OfflineDomainJoinManifest = domainController.Value.OfflineDomainJoinProvision(device.DeviceDomainId, device.DeviceProfile.OrganisationalUnit, ref adMachineAccount, out var offlineProvisionDiagnosicInfo);
EnrolmentLog.LogSessionDiagnosticInformation(sessionId, offlineProvisionDiagnosicInfo); EnrolmentLog.LogSessionDiagnosticInformation(sessionId, offlineProvisionDiagnosicInfo);
@@ -510,8 +507,7 @@ namespace Disco.Services.Devices.Enrolment
{ {
EnrolmentLog.LogSessionProgress(sessionId, 90, "Provisioning Certificates"); EnrolmentLog.LogSessionProgress(sessionId, 90, "Provisioning Certificates");
List<DeviceCertificate> provisionedCertificates; var provisionResult = device.ProvisionCertificates(Database, Request, out var provisionedCertificates);
var provisionResult = device.ProvisionCertificates(Database, Request, out provisionedCertificates);
if (provisionedCertificates != null && provisionedCertificates.Count > 0) if (provisionedCertificates != null && provisionedCertificates.Count > 0)
{ {
@@ -113,8 +113,7 @@ namespace Disco.Services.Devices.Importing
if (columnsByType == null) if (columnsByType == null)
throw new ArgumentNullException(nameof(columnsByType)); throw new ArgumentNullException(nameof(columnsByType));
DeviceImportColumn column; if (columnsByType.TryGetValue(FieldType, out var column))
if (columnsByType.TryGetValue(FieldType, out column))
{ {
return column.Index; return column.Index;
} }
@@ -102,8 +102,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
int? value; return TryGetNullableInt(c, out var value);
return TryGetNullableInt(c, out value);
}); });
} }
@@ -112,8 +111,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
int? value; return TryGetNullableInt(c, out var value) && value.HasValue;
return TryGetNullableInt(c, out value) && value.HasValue;
}); });
} }
@@ -122,8 +120,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
bool? value; return TryGetNullableBool(c, out var value);
return TryGetNullableBool(c, out value);
}); });
} }
@@ -132,8 +129,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
DateTime? value; return TryGetNullableDateTime(c, out var value);
return TryGetNullableDateTime(c, out value);
}); });
} }
@@ -153,8 +149,7 @@ namespace Disco.Services.Devices.Importing
{ {
content = content.Trim(); content = content.Trim();
DateTime valueDateTime; if (DateTime.TryParse(content, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out var valueDateTime))
if (DateTime.TryParse(content, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out valueDateTime))
{ {
value = valueDateTime; value = valueDateTime;
return true; return true;
@@ -205,8 +200,7 @@ namespace Disco.Services.Devices.Importing
} }
else else
{ {
int intValue; if (int.TryParse(content, out var intValue))
if (int.TryParse(content, out intValue))
{ {
value = intValue; value = intValue;
return true; return true;
@@ -40,8 +40,7 @@ namespace Disco.Services.Devices.Importing.Fields
parsedValue = new DateTime((parsedValue.Value.Ticks / 10000000L) * 10000000L); parsedValue = new DateTime((parsedValue.Value.Ticks / 10000000L) * 10000000L);
} }
string errorMessage; if (parsedValue.HasValue && !CanDecommissionDevice(ExistingDevice, Context, DataReader, out var errorMessage))
if (parsedValue.HasValue && !CanDecommissionDevice(ExistingDevice, Context, DataReader, out errorMessage))
return Error(errorMessage); return Error(errorMessage);
var decommissionReasonIndex = Context.GetColumnByType(DeviceImportFieldTypes.DeviceDecommissionedReason); var decommissionReasonIndex = Context.GetColumnByType(DeviceImportFieldTypes.DeviceDecommissionedReason);
@@ -55,8 +55,7 @@ namespace Disco.Services.Devices.Importing.Fields
} }
else else
{ {
DecommissionReasons valueReason; if (!decommissionReasonsMap.Value.TryGetValue(value.Trim(), out var valueReason))
if (!decommissionReasonsMap.Value.TryGetValue(value.Trim(), out valueReason))
{ {
rawValue = value.Trim(); rawValue = value.Trim();
return Error("Cannot parse the value as a Decommission Reason"); return Error("Cannot parse the value as a Decommission Reason");
@@ -24,8 +24,7 @@ namespace Disco.Services.Devices.Importing.Fields
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, IDeviceImportContext Context, string DeviceSerialNumber, Device ExistingDevice, List<IDeviceImportRecord> PreviousRecords, IDeviceImportDataReader DataReader, int ColumnIndex) public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, IDeviceImportContext Context, string DeviceSerialNumber, Device ExistingDevice, List<IDeviceImportRecord> PreviousRecords, IDeviceImportDataReader DataReader, int ColumnIndex)
{ {
int? intValue; if (DataReader.TryGetNullableInt(ColumnIndex, out var intValue))
if (DataReader.TryGetNullableInt(ColumnIndex, out intValue))
{ {
if (!intValue.HasValue) if (!intValue.HasValue)
{ {
@@ -24,8 +24,7 @@ namespace Disco.Services.Devices.Importing.Fields
public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, IDeviceImportContext Context, string DeviceSerialNumber, Device ExistingDevice, List<IDeviceImportRecord> PreviousRecords, IDeviceImportDataReader DataReader, int ColumnIndex) public override bool Parse(DiscoDataContext Database, IDeviceImportCache Cache, IDeviceImportContext Context, string DeviceSerialNumber, Device ExistingDevice, List<IDeviceImportRecord> PreviousRecords, IDeviceImportDataReader DataReader, int ColumnIndex)
{ {
int? intValue; if (DataReader.TryGetNullableInt(ColumnIndex, out var intValue))
if (DataReader.TryGetNullableInt(ColumnIndex, out intValue))
{ {
if (!intValue.HasValue) if (!intValue.HasValue)
{ {
@@ -102,8 +102,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
int? value; return TryGetNullableInt(c, out var value);
return TryGetNullableInt(c, out value);
}); });
} }
@@ -112,8 +111,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
int? value; return TryGetNullableInt(c, out var value) && value.HasValue;
return TryGetNullableInt(c, out value) && value.HasValue;
}); });
} }
@@ -122,8 +120,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
bool? value; return TryGetNullableBool(c, out var value);
return TryGetNullableBool(c, out value);
}); });
} }
@@ -132,8 +129,7 @@ namespace Disco.Services.Devices.Importing
return rawData.Select(r => r[ColumnIndex]) return rawData.Select(r => r[ColumnIndex])
.All(c => .All(c =>
{ {
DateTime? value; return TryGetNullableDateTime(c, out var value);
return TryGetNullableDateTime(c, out value);
}); });
} }
@@ -167,8 +163,7 @@ namespace Disco.Services.Devices.Importing
{ {
stringValue = stringValue.Trim(); stringValue = stringValue.Trim();
DateTime valueDateTime; if (DateTime.TryParse(stringValue, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out var valueDateTime))
if (DateTime.TryParse(stringValue, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out valueDateTime))
{ {
value = valueDateTime; value = valueDateTime;
return true; return true;
@@ -247,8 +242,7 @@ namespace Disco.Services.Devices.Importing
} }
else else
{ {
int intValue; if (int.TryParse(stringValue, out var intValue))
if (int.TryParse(stringValue, out intValue))
{ {
value = intValue; value = intValue;
return true; return true;
@@ -76,10 +76,9 @@ namespace Disco.Services.Devices.ManagedGroups
public static bool TryGetManagedGroup(DeviceBatch DeviceBatch, out DeviceBatchAssignedUsersManagedGroup ManagedGroup) public static bool TryGetManagedGroup(DeviceBatch DeviceBatch, out DeviceBatchAssignedUsersManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(DeviceBatch); string key = GetKey(DeviceBatch);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (DeviceBatchAssignedUsersManagedGroup)managedGroup; ManagedGroup = (DeviceBatchAssignedUsersManagedGroup)managedGroup;
return true; return true;
@@ -74,10 +74,9 @@ namespace Disco.Services.Devices.ManagedGroups
public static bool TryGetManagedGroup(DeviceBatch DeviceBatch, out DeviceBatchDevicesManagedGroup ManagedGroup) public static bool TryGetManagedGroup(DeviceBatch DeviceBatch, out DeviceBatchDevicesManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(DeviceBatch); string key = GetKey(DeviceBatch);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (DeviceBatchDevicesManagedGroup)managedGroup; ManagedGroup = (DeviceBatchDevicesManagedGroup)managedGroup;
return true; return true;
@@ -76,10 +76,9 @@ namespace Disco.Services.Devices.ManagedGroups
public static bool TryGetManagedGroup(DeviceProfile DeviceProfile, out DeviceProfileAssignedUsersManagedGroup ManagedGroup) public static bool TryGetManagedGroup(DeviceProfile DeviceProfile, out DeviceProfileAssignedUsersManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(DeviceProfile); string key = GetKey(DeviceProfile);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (DeviceProfileAssignedUsersManagedGroup)managedGroup; ManagedGroup = (DeviceProfileAssignedUsersManagedGroup)managedGroup;
return true; return true;
@@ -75,10 +75,9 @@ namespace Disco.Services.Devices.ManagedGroups
public static bool TryGetManagedGroup(DeviceProfile DeviceProfile, out DeviceProfileDevicesManagedGroup ManagedGroup) public static bool TryGetManagedGroup(DeviceProfile DeviceProfile, out DeviceProfileDevicesManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(DeviceProfile); string key = GetKey(DeviceProfile);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (DeviceProfileDevicesManagedGroup)managedGroup; ManagedGroup = (DeviceProfileDevicesManagedGroup)managedGroup;
return true; return true;
@@ -298,8 +298,7 @@ namespace Disco.Services.Documents.AttachmentImport
if (qrCodeResult != null && qrCodeResult.ResultPoints.Length == 4) if (qrCodeResult != null && qrCodeResult.ResultPoints.Length == 4)
{ {
float thumbnailScale; var thumbnailOffset = renderedImage.CalculateResize(renderedThumbnail.Width, renderedThumbnail.Height, out var thumbnailScale);
var thumbnailOffset = renderedImage.CalculateResize(renderedThumbnail.Width, renderedThumbnail.Height, out thumbnailScale);
thumbnailScale = thumbnailScale / qrCodeResultScale; thumbnailScale = thumbnailScale / qrCodeResultScale;
using (Graphics thumbnailGraphics = Graphics.FromImage(renderedThumbnail)) using (Graphics thumbnailGraphics = Graphics.FromImage(renderedThumbnail))
@@ -29,11 +29,10 @@ namespace Disco.Services
try try
{ {
var er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables); var er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables);
if (er is bool) if (er is bool erBool)
{ {
return (bool)er; return erBool;
} }
bool erBool;
if (bool.TryParse(er.ToString(), out erBool)) if (bool.TryParse(er.ToString(), out erBool))
{ {
return erBool; return erBool;
@@ -91,11 +91,10 @@ namespace Disco.Services
try try
{ {
object er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables); object er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables);
if (er is bool) if (er is bool erBool)
{ {
return (bool)er; return erBool;
} }
bool erBool;
if (bool.TryParse(er.ToString(), out erBool)) if (bool.TryParse(er.ToString(), out erBool))
{ {
return erBool; return erBool;
@@ -35,8 +35,7 @@ namespace Disco.Services.Documents
public static DocumentTemplatePackage GetPackage(string Id) public static DocumentTemplatePackage GetPackage(string Id)
{ {
DocumentTemplatePackage package; if (cache.TryGetValue(Id, out var package))
if (cache.TryGetValue(Id, out package))
return package; return package;
else else
return null; return null;
@@ -142,11 +141,10 @@ namespace Disco.Services.Documents
public static DocumentTemplatePackage UpdatePackage(DocumentTemplatePackage Package) public static DocumentTemplatePackage UpdatePackage(DocumentTemplatePackage Package)
{ {
DocumentTemplatePackage existingPackage;
if (string.IsNullOrWhiteSpace(Package.Id)) if (string.IsNullOrWhiteSpace(Package.Id))
throw new ArgumentNullException(nameof(Package), "The Package Id is required"); throw new ArgumentNullException(nameof(Package), "The Package Id is required");
if (!cache.TryGetValue(Package.Id, out existingPackage)) // Name Unique if (!cache.TryGetValue(Package.Id, out var existingPackage)) // Name Unique
throw new ArgumentException("The Package Id does not exist", nameof(Package)); throw new ArgumentException("The Package Id does not exist", nameof(Package));
if (string.IsNullOrWhiteSpace(Package.Description)) if (string.IsNullOrWhiteSpace(Package.Description))
throw new ArgumentNullException(nameof(Package), "The Package Description is required"); throw new ArgumentNullException(nameof(Package), "The Package Description is required");
@@ -162,8 +160,7 @@ namespace Disco.Services.Documents
public static void RemovePackage(string Id) public static void RemovePackage(string Id)
{ {
DocumentTemplatePackage existingPackage; if (cache.TryRemove(Id, out _))
if (cache.TryRemove(Id, out existingPackage))
{ {
PersistCache(); PersistCache();
} }
@@ -312,28 +312,17 @@ namespace Disco.Services.Documents
public static DocumentUniqueIdentifier Parse(DiscoDataContext Database, byte[] UniqueIdentifier) public static DocumentUniqueIdentifier Parse(DiscoDataContext Database, byte[] UniqueIdentifier)
{ {
DocumentUniqueIdentifier identifier; if (TryParse(Database, UniqueIdentifier, out var identifier))
if (TryParse(Database, UniqueIdentifier, out identifier))
{
return identifier; return identifier;
}
else
{
throw new FormatException("Invalid Document Unique Identifier"); throw new FormatException("Invalid Document Unique Identifier");
} }
}
public static DocumentUniqueIdentifier Parse(DiscoDataContext Database, string UniqueIdentifier) public static DocumentUniqueIdentifier Parse(DiscoDataContext Database, string UniqueIdentifier)
{ {
DocumentUniqueIdentifier identifier; if (TryParse(Database, UniqueIdentifier, out var identifier))
if (TryParse(Database, UniqueIdentifier, out identifier))
{
return identifier; return identifier;
}
else
{
throw new FormatException("Invalid Document Unique Identifier"); throw new FormatException("Invalid Document Unique Identifier");
}
} }
public static bool TryParse(DiscoDataContext Database, string UniqueIdentifier, out DocumentUniqueIdentifier Identifier) public static bool TryParse(DiscoDataContext Database, string UniqueIdentifier, out DocumentUniqueIdentifier Identifier)
@@ -417,7 +406,7 @@ namespace Disco.Services.Documents
// Has document template id flag // Has document template id flag
if ((flags & 0x8) == 0x8) if ((flags & 0x8) == 0x8)
{ {
documentTemplateId = DocumentUniqueIdentifierExtensions.BinaryDecode(Data, position, out position); documentTemplateId = DocumentUniqueIdentifierExtensions.BinaryDecode(Data, position, out _);
} }
AttachmentTypes? attachmentType = null; AttachmentTypes? attachmentType = null;
@@ -24,7 +24,6 @@ namespace Disco.Services
if (Data == null) if (Data == null)
throw new ArgumentNullException(nameof(Data)); throw new ArgumentNullException(nameof(Data));
byte[] result;
if (Data.Length == 0) if (Data.Length == 0)
{ {
@@ -33,7 +32,7 @@ namespace Disco.Services
} }
// Try Numeric Encode // Try Numeric Encode
if (TryBinaryNumericEncode(Data, out result)) if (TryBinaryNumericEncode(Data, out var result))
{ {
return result; return result;
} }
@@ -88,8 +87,7 @@ namespace Disco.Services
// Z = number of leading zeros // Z = number of leading zeros
// Y = number component < 0x0FFFFFFF (268,435,455) // Y = number component < 0x0FFFFFFF (268,435,455)
uint number; if (uint.TryParse(Data, out var number) && number <= 0x0FFFFFFF)
if (uint.TryParse(Data, out number) && number <= 0x0FFFFFFF)
{ {
Result = new byte[4]; Result = new byte[4];
int leadingZeros = 0; int leadingZeros = 0;
@@ -250,12 +248,10 @@ namespace Disco.Services
// A,B,C = character component in // A,B,C = character component in
// alpha encoded format // alpha encoded format
short number;
byte[] chars;
if (Data.Length == 7 && if (Data.Length == 7 &&
short.TryParse(Data.Substring(3), out number) && short.TryParse(Data.Substring(3), out var number) &&
number <= 9999 && number <= 9999 &&
TryBinaryAlphaEncode(Data.Substring(0, 3), out chars)) TryBinaryAlphaEncode(Data.Substring(0, 3), out var chars))
{ {
Result = new byte[4]; Result = new byte[4];
Result[0] = (byte)(0x80 | (number >> 8)); Result[0] = (byte)(0x80 | (number >> 8));
@@ -109,10 +109,9 @@ namespace Disco.Services.Documents.ManagedGroups
public static bool TryGetManagedGroup(DocumentTemplate DocumentTemplate, out DocumentTemplateDevicesManagedGroup ManagedGroup) public static bool TryGetManagedGroup(DocumentTemplate DocumentTemplate, out DocumentTemplateDevicesManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(DocumentTemplate); string key = GetKey(DocumentTemplate);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (DocumentTemplateDevicesManagedGroup)managedGroup; ManagedGroup = (DocumentTemplateDevicesManagedGroup)managedGroup;
return true; return true;
@@ -230,8 +229,7 @@ namespace Disco.Services.Documents.ManagedGroups
{ {
var attachment = (DeviceAttachment)e.Entity; var attachment = (DeviceAttachment)e.Entity;
string deviceAccountId; if (DeviceContainsAttachment(e.Database, attachment.DeviceSerialNumber, out var deviceAccountId))
if (DeviceContainsAttachment(e.Database, attachment.DeviceSerialNumber, out deviceAccountId))
AddMember(attachment.DeviceSerialNumber, (database) => new string[] { deviceAccountId }); AddMember(attachment.DeviceSerialNumber, (database) => new string[] { deviceAccountId });
} }
private void ProcessDeviceAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, string> e) private void ProcessDeviceAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, string> e)
@@ -240,8 +238,7 @@ namespace Disco.Services.Documents.ManagedGroups
RemoveMember(deviceSerialNumber, (database) => RemoveMember(deviceSerialNumber, (database) =>
{ {
string deviceAccountId; if (!DeviceContainsAttachment(database, deviceSerialNumber, out var deviceAccountId) && deviceAccountId != null)
if (!DeviceContainsAttachment(database, deviceSerialNumber, out deviceAccountId) && deviceAccountId != null)
return new string[] { deviceAccountId }; return new string[] { deviceAccountId };
else else
return null; return null;
@@ -279,9 +276,7 @@ namespace Disco.Services.Documents.ManagedGroups
{ {
var attachment = (JobAttachment)e.Entity; var attachment = (JobAttachment)e.Entity;
string deviceAccountId; if (JobsContainAttachment(e.Database, attachment.JobId, out var deviceAccountId, out var deviceSerialNumber))
string deviceSerialNumber;
if (JobsContainAttachment(e.Database, attachment.JobId, out deviceAccountId, out deviceSerialNumber))
AddMember(deviceSerialNumber, (database) => new string[] { deviceAccountId }); AddMember(deviceSerialNumber, (database) => new string[] { deviceAccountId });
} }
private void ProcessJobAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, int> e) private void ProcessJobAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, int> e)
@@ -293,8 +288,7 @@ namespace Disco.Services.Documents.ManagedGroups
{ {
RemoveMember(deviceSerialNumber, (database) => RemoveMember(deviceSerialNumber, (database) =>
{ {
string deviceAccountId; if (!JobsContainAttachment(database, jobId, out var deviceAccountId, out deviceSerialNumber) &&
if (!JobsContainAttachment(database, jobId, out deviceAccountId, out deviceSerialNumber) &&
deviceSerialNumber != null && deviceAccountId != null) deviceSerialNumber != null && deviceAccountId != null)
return new string[] { deviceAccountId }; return new string[] { deviceAccountId };
else else
@@ -335,8 +329,7 @@ namespace Disco.Services.Documents.ManagedGroups
{ {
var attachment = (UserAttachment)e.Entity; var attachment = (UserAttachment)e.Entity;
List<Tuple<string, string>> devices; if (DeviceUserContainAttachment(e.Database, attachment.UserId, out var devices) && devices != null)
if (DeviceUserContainAttachment(e.Database, attachment.UserId, out devices) && devices != null)
devices.ForEach(d => AddMember(d.Item2, (database) => new string[] { d.Item1 })); devices.ForEach(d => AddMember(d.Item2, (database) => new string[] { d.Item1 }));
} }
private void ProcessUserAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, string> e) private void ProcessUserAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, string> e)
@@ -345,8 +338,7 @@ namespace Disco.Services.Documents.ManagedGroups
RemoveMember(userId, (database) => RemoveMember(userId, (database) =>
{ {
List<Tuple<string, string>> devices; if (!DeviceUserContainAttachment(database, userId, out var devices) && devices != null)
if (!DeviceUserContainAttachment(database, userId, out devices) && devices != null)
return devices.Select(d => d.Item1); return devices.Select(d => d.Item1);
else else
return null; return null;
@@ -104,10 +104,9 @@ namespace Disco.Services.Documents.ManagedGroups
public static bool TryGetManagedGroup(DocumentTemplate DocumentTemplate, out DocumentTemplateUsersManagedGroup ManagedGroup) public static bool TryGetManagedGroup(DocumentTemplate DocumentTemplate, out DocumentTemplateUsersManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(DocumentTemplate); string key = GetKey(DocumentTemplate);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (DocumentTemplateUsersManagedGroup)managedGroup; ManagedGroup = (DocumentTemplateUsersManagedGroup)managedGroup;
return true; return true;
@@ -217,8 +216,7 @@ namespace Disco.Services.Documents.ManagedGroups
{ {
var attachment = (DeviceAttachment)e.Entity; var attachment = (DeviceAttachment)e.Entity;
string userId; if (DeviceContainsAttachment(e.Database, attachment.DeviceSerialNumber, out var userId) && userId != null)
if (DeviceContainsAttachment(e.Database, attachment.DeviceSerialNumber, out userId) && userId != null)
AddMember(userId, (database) => new string[] { userId }); AddMember(userId, (database) => new string[] { userId });
} }
private void ProcessDeviceAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, string> e) private void ProcessDeviceAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, string> e)
@@ -273,8 +271,7 @@ namespace Disco.Services.Documents.ManagedGroups
{ {
var attachment = (JobAttachment)e.Entity; var attachment = (JobAttachment)e.Entity;
string userId; if (JobsContainAttachment(e.Database, attachment.JobId, out var userId) && userId != null)
if (JobsContainAttachment(e.Database, attachment.JobId, out userId) && userId != null)
AddMember(userId, (database) => new string[] { userId }); AddMember(userId, (database) => new string[] { userId });
} }
private void ProcessJobAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, int> e) private void ProcessJobAttachmentRemoveEvent(Tuple<DiscoDataContext, int, string, int> e)
@@ -11,8 +11,6 @@ namespace Disco.Services.Documents
public static byte[] Encode(string content, ErrorCorrectionLevel ecLevel, out int width, out int height) public static byte[] Encode(string content, ErrorCorrectionLevel ecLevel, out int width, out int height)
{ {
var code = Encoder.encode(content, ecLevel, null); var code = Encoder.encode(content, ecLevel, null);
var array = code.Matrix.Array;
width = code.Matrix.Width; width = code.Matrix.Width;
height = code.Matrix.Height; height = code.Matrix.Height;
@@ -140,11 +138,9 @@ namespace Disco.Services.Documents
for (int i = 0; i < numRSBlocks; ++i) for (int i = 0; i < numRSBlocks; ++i)
{ {
int numDataBytesInBlock;
int numEcBytesInBlock;
getNumDataBytesAndNumECBytesForBlockID( getNumDataBytesAndNumECBytesForBlockID(
numTotalBytes, numDataBytes, numRSBlocks, i, numTotalBytes, numDataBytes, numRSBlocks, i,
out numDataBytesInBlock, out numEcBytesInBlock); out var numDataBytesInBlock, out var numEcBytesInBlock);
byte[] dataBytes = new byte[numDataBytesInBlock]; byte[] dataBytes = new byte[numDataBytesInBlock];
bits.toBytes(8 * dataBytesOffset, dataBytes, 0, numDataBytesInBlock); bits.toBytes(8 * dataBytesOffset, dataBytes, 0, numDataBytesInBlock);
@@ -85,8 +85,7 @@ namespace Disco.Services.Interop.ActiveDirectory
foreach (var domainGroup in devices.GroupBy(d => d.ComputerDomainName).ToList()) foreach (var domainGroup in devices.GroupBy(d => d.ComputerDomainName).ToList())
{ {
ADDomain domain; if (domainGroup.Key != null && ActiveDirectory.Context.TryGetDomainByNetBiosName(domainGroup.Key, out var domain))
if (domainGroup.Key != null && ActiveDirectory.Context.TryGetDomainByNetBiosName(domainGroup.Key, out domain))
{ {
var controller = domain.GetAvailableDomainController(RequireWritable: true); var controller = domain.GetAvailableDomainController(RequireWritable: true);
@@ -311,8 +311,7 @@ namespace Disco.Services.Interop.ActiveDirectory
// Link Children // Link Children
foreach (var ouChildren in indexedChildren) foreach (var ouChildren in indexedChildren)
{ {
ADOrganisationalUnit ouParent; if (indexedOrganisationalUnits.TryGetValue(ouChildren.Key, out var ouParent))
if (indexedOrganisationalUnits.TryGetValue(ouChildren.Key, out ouParent))
{ {
ouParent.Children = ouChildren.Value.OrderBy(o => o.Name).ToList(); ouParent.Children = ouChildren.Value.OrderBy(o => o.Name).ToList();
} }
@@ -121,8 +121,7 @@ namespace Disco.Services.Interop.ActiveDirectory
case "member": case "member":
return Members.OfType<T>(); return Members.OfType<T>();
default: default:
object[] adProperty; if (LoadedProperties.TryGetValue(PropertyName, out var adProperty))
if (LoadedProperties.TryGetValue(PropertyName, out adProperty))
return adProperty.OfType<T>(); return adProperty.OfType<T>();
else else
return Enumerable.Empty<T>(); return Enumerable.Empty<T>();
@@ -195,8 +195,7 @@ namespace Disco.Services.Interop.ActiveDirectory
case "userAccountControl": case "userAccountControl":
return new int[] { (int)UserAccountControl }.OfType<T>(); return new int[] { (int)UserAccountControl }.OfType<T>();
default: default:
object[] adProperty; if (LoadedProperties.TryGetValue(PropertyName, out var adProperty))
if (LoadedProperties.TryGetValue(PropertyName, out adProperty))
return adProperty.OfType<T>(); return adProperty.OfType<T>();
else else
return Enumerable.Empty<T>(); return Enumerable.Empty<T>();
@@ -59,10 +59,8 @@ namespace Disco.Services.Interop.ActiveDirectory
if (!string.IsNullOrEmpty(Device.DeviceDomainId) && Device.DeviceDomainId.Contains('\\')) if (!string.IsNullOrEmpty(Device.DeviceDomainId) && Device.DeviceDomainId.Contains('\\'))
{ {
var context = ActiveDirectory.Context; var context = ActiveDirectory.Context;
string deviceSamAccountName;
ADDomain deviceDomain;
ActiveDirectory.ParseDomainAccountId(Device.DeviceDomainId + "$", out deviceSamAccountName, out deviceDomain); ActiveDirectory.ParseDomainAccountId(Device.DeviceDomainId + "$", out var deviceSamAccountName, out var deviceDomain);
var ldapFilter = string.Format(ldapFilterTemplate, ADHelpers.EscapeLdapQuery(deviceSamAccountName)); var ldapFilter = string.Format(ldapFilterTemplate, ADHelpers.EscapeLdapQuery(deviceSamAccountName));
IEnumerable<ADDomainController> domainControllers; IEnumerable<ADDomainController> domainControllers;
@@ -177,8 +175,7 @@ namespace Disco.Services.Interop.ActiveDirectory
foreach (Device device in Database.Devices.Where(device => device.DeviceDomainId != null)) foreach (Device device in Database.Devices.Where(device => device.DeviceDomainId != null))
{ {
DateTime lastLogonDate; if (queryResults.TryGetValue(device.DeviceDomainId.ToUpper(), out var lastLogonDate))
if (queryResults.TryGetValue(device.DeviceDomainId.ToUpper(), out lastLogonDate))
{ {
if (!device.LastNetworkLogonDate.HasValue) if (!device.LastNetworkLogonDate.HasValue)
device.LastNetworkLogonDate = lastLogonDate; device.LastNetworkLogonDate = lastLogonDate;
@@ -224,8 +224,7 @@ namespace Disco.Services.Interop.ActiveDirectory
case "userAccountControl": case "userAccountControl":
return new int[] { (int)UserAccountControl }.OfType<T>(); return new int[] { (int)UserAccountControl }.OfType<T>();
default: default:
object[] adProperty; if (LoadedProperties.TryGetValue(PropertyName, out var adProperty))
if (LoadedProperties.TryGetValue(PropertyName, out adProperty))
return adProperty.OfType<T>(); return adProperty.OfType<T>();
else else
return Enumerable.Empty<T>(); return Enumerable.Empty<T>();
@@ -79,8 +79,7 @@ namespace Disco.Services.Interop.ActiveDirectory
if (string.IsNullOrWhiteSpace(Term)) if (string.IsNullOrWhiteSpace(Term))
throw new ArgumentNullException("Term"); throw new ArgumentNullException("Term");
ADDomain searchDomain; var term = RelevantSearchTerm(Term, out var searchDomain);
var term = RelevantSearchTerm(Term, out searchDomain);
if (string.IsNullOrWhiteSpace(term)) if (string.IsNullOrWhiteSpace(term))
return Enumerable.Empty<ADUserAccount>(); return Enumerable.Empty<ADUserAccount>();
@@ -139,8 +138,7 @@ namespace Disco.Services.Interop.ActiveDirectory
if (string.IsNullOrWhiteSpace(Term)) if (string.IsNullOrWhiteSpace(Term))
throw new ArgumentNullException("Term"); throw new ArgumentNullException("Term");
ADDomain searchDomain; var term = RelevantSearchTerm(Term, out var searchDomain);
var term = RelevantSearchTerm(Term, out searchDomain);
if (string.IsNullOrWhiteSpace(term)) if (string.IsNullOrWhiteSpace(term))
return Enumerable.Empty<ADGroup>(); return Enumerable.Empty<ADGroup>();
@@ -200,10 +198,8 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public static string ParseDomainAccountId(string AccountId, string AccountDomain) public static string ParseDomainAccountId(string AccountId, string AccountDomain)
{ {
string accountUsername;
ADDomain domain;
return ParseDomainAccountId(AccountId, AccountDomain, out accountUsername, out domain); return ParseDomainAccountId(AccountId, AccountDomain, out _, out _);
} }
public static string ParseDomainAccountId(string AccountId, out string AccountUsername) public static string ParseDomainAccountId(string AccountId, out string AccountUsername)
{ {
@@ -211,9 +207,7 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public static string ParseDomainAccountId(string AccountId, string AccountDomain, out string AccountUsername) public static string ParseDomainAccountId(string AccountId, string AccountDomain, out string AccountUsername)
{ {
ADDomain domain; return ParseDomainAccountId(AccountId, AccountDomain, out AccountUsername, out _);
return ParseDomainAccountId(AccountId, AccountDomain, out AccountUsername, out domain);
} }
public static string ParseDomainAccountId(string AccountId, out ADDomain Domain) public static string ParseDomainAccountId(string AccountId, out ADDomain Domain)
{ {
@@ -221,9 +215,7 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public static string ParseDomainAccountId(string AccountId, string AccountDomain, out ADDomain Domain) public static string ParseDomainAccountId(string AccountId, string AccountDomain, out ADDomain Domain)
{ {
string accountUsername; return ParseDomainAccountId(AccountId, AccountDomain, out _, out Domain);
return ParseDomainAccountId(AccountId, AccountDomain, out accountUsername, out Domain);
} }
public static string ParseDomainAccountId(string AccountId, out string AccountUsername, out ADDomain Domain) public static string ParseDomainAccountId(string AccountId, out string AccountUsername, out ADDomain Domain)
{ {
@@ -258,22 +250,15 @@ namespace Disco.Services.Interop.ActiveDirectory
public static bool IsValidDomainAccountId(string AccountId) public static bool IsValidDomainAccountId(string AccountId)
{ {
string accountUsername; return IsValidDomainAccountId(AccountId, out _, out _);
ADDomain domain;
return IsValidDomainAccountId(AccountId, out accountUsername, out domain);
} }
public static bool IsValidDomainAccountId(string AccountId, out string AccountUsername) public static bool IsValidDomainAccountId(string AccountId, out string AccountUsername)
{ {
ADDomain domain; return IsValidDomainAccountId(AccountId, out AccountUsername, out _);
return IsValidDomainAccountId(AccountId, out AccountUsername, out domain);
} }
public static bool IsValidDomainAccountId(string AccountId, out ADDomain Domain) public static bool IsValidDomainAccountId(string AccountId, out ADDomain Domain)
{ {
string accountUsername; return IsValidDomainAccountId(AccountId, out _, out Domain);
return IsValidDomainAccountId(AccountId, out accountUsername, out Domain);
} }
public static bool IsValidDomainAccountId(string AccountId, out string AccountUsername, out ADDomain Domain) public static bool IsValidDomainAccountId(string AccountId, out string AccountUsername, out ADDomain Domain)
{ {
@@ -137,8 +137,7 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public ADDomain GetDomainFromDistinguishedName(string DistinguishedName) public ADDomain GetDomainFromDistinguishedName(string DistinguishedName)
{ {
ADDomain domain; if (!TryGetDomainFromDistinguishedName(DistinguishedName, out var domain))
if (!TryGetDomainFromDistinguishedName(DistinguishedName, out domain))
throw new ArgumentException($"The distinguished name is from an unknown domain: [{DistinguishedName}]", "DistinguishedName"); throw new ArgumentException($"The distinguished name is from an unknown domain: [{DistinguishedName}]", "DistinguishedName");
return domain; return domain;
} }
@@ -150,8 +149,7 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public ADDomain GetDomainByNetBiosName(string NetBiosName) public ADDomain GetDomainByNetBiosName(string NetBiosName)
{ {
ADDomain domain; if (!TryGetDomainByNetBiosName(NetBiosName, out var domain))
if (!TryGetDomainByNetBiosName(NetBiosName, out domain))
throw new ArgumentException($"The domain for specified NetBios name is unknown [{NetBiosName}]", "NetBiosName"); throw new ArgumentException($"The domain for specified NetBios name is unknown [{NetBiosName}]", "NetBiosName");
return domain; return domain;
} }
@@ -163,8 +161,7 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public ADDomain GetDomainByName(string Name) public ADDomain GetDomainByName(string Name)
{ {
ADDomain domain; if (!TryGetDomainByName(Name, out var domain))
if (!TryGetDomainByName(Name, out domain))
throw new ArgumentException($"The domain for specified DNS name is unknown [{Name}]", "Name"); throw new ArgumentException($"The domain for specified DNS name is unknown [{Name}]", "Name");
return domain; return domain;
} }
@@ -176,8 +173,7 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public ADDomain GetDomainFromSecurityIdentifier(SecurityIdentifier SecurityIdentifier) public ADDomain GetDomainFromSecurityIdentifier(SecurityIdentifier SecurityIdentifier)
{ {
ADDomain domain; if (!TryGetDomainFromSecurityIdentifier(SecurityIdentifier, out var domain))
if (!TryGetDomainFromSecurityIdentifier(SecurityIdentifier, out domain))
throw new ArgumentException($"The domain for specified Security Identifier is unknown [{SecurityIdentifier.ToString()}]", "SecurityIdentifier"); throw new ArgumentException($"The domain for specified Security Identifier is unknown [{SecurityIdentifier.ToString()}]", "SecurityIdentifier");
return domain; return domain;
} }
@@ -328,8 +324,7 @@ namespace Disco.Services.Interop.ActiveDirectory
.Distinct() .Distinct()
.Select(c => .Select(c =>
{ {
ADDomain d; if (TryGetDomainFromDistinguishedName(c, out var d))
if (TryGetDomainFromDistinguishedName(c, out d))
return Tuple.Create(d, c); return Tuple.Create(d, c);
else else
return null; return null;
@@ -104,30 +104,28 @@ namespace Disco.Services.Interop.ActiveDirectory
private Tuple<ADGroup, DateTime> TryDistinguishedNameCache(string DistinguishedName) private Tuple<ADGroup, DateTime> TryDistinguishedNameCache(string DistinguishedName)
{ {
Tuple<ADGroup, DateTime> groupRecord; if (distinguishedNameCache.TryGetValue(DistinguishedName, out var groupRecord))
if (distinguishedNameCache.TryGetValue(DistinguishedName, out groupRecord))
{ {
if (groupRecord.Item2 > DateTime.Now) if (groupRecord.Item2 > DateTime.Now)
return groupRecord; return groupRecord;
else else
{ {
if (distinguishedNameCache.TryRemove(DistinguishedName, out groupRecord)) if (distinguishedNameCache.TryRemove(DistinguishedName, out groupRecord))
securityIdentifierCache.TryRemove(groupRecord.Item1.SecurityIdentifier, out groupRecord); securityIdentifierCache.TryRemove(groupRecord.Item1.SecurityIdentifier, out _);
} }
} }
return null; return null;
} }
private Tuple<ADGroup, DateTime> TrySecurityIdentifierCache(SecurityIdentifier SecurityIdentifier) private Tuple<ADGroup, DateTime> TrySecurityIdentifierCache(SecurityIdentifier SecurityIdentifier)
{ {
Tuple<ADGroup, DateTime> groupRecord; if (securityIdentifierCache.TryGetValue(SecurityIdentifier, out var groupRecord))
if (securityIdentifierCache.TryGetValue(SecurityIdentifier, out groupRecord))
{ {
if (groupRecord.Item2 > DateTime.Now) if (groupRecord.Item2 > DateTime.Now)
return groupRecord; return groupRecord;
else else
{ {
if (securityIdentifierCache.TryRemove(SecurityIdentifier, out groupRecord)) if (securityIdentifierCache.TryRemove(SecurityIdentifier, out groupRecord))
distinguishedNameCache.TryRemove(groupRecord.Item1.DistinguishedName, out groupRecord); distinguishedNameCache.TryRemove(groupRecord.Item1.DistinguishedName, out _);
} }
} }
return null; return null;
@@ -191,12 +189,11 @@ namespace Disco.Services.Interop.ActiveDirectory
var dnKeys = distinguishedNameCache.Keys.ToArray(); var dnKeys = distinguishedNameCache.Keys.ToArray();
foreach (var dnKey in dnKeys) foreach (var dnKey in dnKeys)
{ {
Tuple<ADGroup, DateTime> groupRecord; if (distinguishedNameCache.TryGetValue(dnKey, out var groupRecord))
if (distinguishedNameCache.TryGetValue(dnKey, out groupRecord))
{ {
if (groupRecord.Item2 <= now) if (groupRecord.Item2 <= now)
{ {
distinguishedNameCache.TryRemove(dnKey, out groupRecord); distinguishedNameCache.TryRemove(dnKey, out _);
} }
} }
} }
@@ -205,12 +202,11 @@ namespace Disco.Services.Interop.ActiveDirectory
var siKeys = securityIdentifierCache.Keys.ToArray(); var siKeys = securityIdentifierCache.Keys.ToArray();
foreach (var siKey in siKeys) foreach (var siKey in siKeys)
{ {
Tuple<ADGroup, DateTime> groupRecord; if (securityIdentifierCache.TryGetValue(siKey, out var groupRecord))
if (securityIdentifierCache.TryGetValue(siKey, out groupRecord))
{ {
if (groupRecord.Item2 <= now) if (groupRecord.Item2 <= now)
{ {
securityIdentifierCache.TryRemove(siKey, out groupRecord); securityIdentifierCache.TryRemove(siKey, out _);
} }
} }
} }
@@ -51,9 +51,8 @@ namespace Disco.Services.Interop.ActiveDirectory
} }
public bool Remove(string Key) public bool Remove(string Key)
{ {
ADManagedGroup item;
if (managedGroups.TryRemove(Key, out item)) if (managedGroups.TryRemove(Key, out var item))
{ {
item.Dispose(); item.Dispose();
return true; return true;
@@ -123,8 +122,7 @@ namespace Disco.Services.Interop.ActiveDirectory
.GroupBy(a => a.ManagedGroup) .GroupBy(a => a.ManagedGroup)
.Where(g => .Where(g =>
{ {
ADManagedGroup item; if (managedGroups.TryGetValue(g.Key.Key, out var item))
if (managedGroups.TryGetValue(g.Key.Key, out item))
return item == g.Key; return item == g.Key;
else else
return false; return false;
@@ -171,12 +169,9 @@ namespace Disco.Services.Interop.ActiveDirectory
// Discard non-existent users // Discard non-existent users
var actionItems = actionGroup.Item2.Select(a => var actionItems = actionGroup.Item2.Select(a =>
{ {
string distinguishedName; if (!accountDNCache.TryGetValue(a.MemberId, out var distinguishedName))
if (!accountDNCache.TryGetValue(a.MemberId, out distinguishedName))
{ {
string memberUsername; if (!ActiveDirectory.IsValidDomainAccountId(a.MemberId, out var memberUsername, out var memberDomain))
ADDomain memberDomain;
if (!ActiveDirectory.IsValidDomainAccountId(a.MemberId, out memberUsername, out memberDomain))
{ {
accountDNCache[a.MemberId] = null; // Add to cache (avoid retries) accountDNCache[a.MemberId] = null; // Add to cache (avoid retries)
return null; return null;
@@ -333,12 +328,9 @@ namespace Disco.Services.Interop.ActiveDirectory
g.Item1, g.Item1,
g.Item2.Select(a => g.Item2.Select(a =>
{ {
Tuple<string, string> definition; if (!accountDNCache.TryGetValue(a.MemberId, out var definition))
if (!accountDNCache.TryGetValue(a.MemberId, out definition))
{ {
string memberUsername; if (!ActiveDirectory.IsValidDomainAccountId(a.MemberId, out var memberUsername, out var memberDomain))
ADDomain memberDomain;
if (!ActiveDirectory.IsValidDomainAccountId(a.MemberId, out memberUsername, out memberDomain))
{ {
accountDNCache[a.MemberId] = null; // Add to cache (avoid retries) accountDNCache[a.MemberId] = null; // Add to cache (avoid retries)
return null; return null;
@@ -122,9 +122,7 @@ namespace Disco.Services.Interop.DiscoServices
public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, PluginLibraryItemReleaseV2 Release) public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, PluginLibraryItemReleaseV2 Release)
{ {
PluginIncompatibility incompatibility; return IsCompatible(IncompatibilityLibrary, Release, out _);
return IsCompatible(IncompatibilityLibrary, Release, out incompatibility);
} }
public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, PluginLibraryItemReleaseV2 Release, out PluginIncompatibility Incompatibility) public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, PluginLibraryItemReleaseV2 Release, out PluginIncompatibility Incompatibility)
@@ -134,9 +132,7 @@ namespace Disco.Services.Interop.DiscoServices
public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, string PluginId, Version Version) public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, string PluginId, Version Version)
{ {
PluginIncompatibility incompatibility; return IsCompatible(IncompatibilityLibrary, PluginId, Version, out _);
return IsCompatible(IncompatibilityLibrary, PluginId, Version, out incompatibility);
} }
public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, string PluginId, Version Version, out PluginIncompatibility Incompatibility) public static bool IsCompatible(this PluginLibraryIncompatibility IncompatibilityLibrary, string PluginId, Version Version, out PluginIncompatibility Incompatibility)
+1 -3
View File
@@ -705,9 +705,7 @@ namespace Disco.Services
#region Force Close #region Force Close
public static bool CanCloseForced(this Job j) public static bool CanCloseForced(this Job j)
{ {
List<string> reasons; return CanCloseForced(j, out _);
return CanCloseForced(j, out reasons);
} }
public static bool CanCloseForced(this Job j, out List<string> Reasons) public static bool CanCloseForced(this Job j, out List<string> Reasons)
{ {
+4 -8
View File
@@ -76,9 +76,8 @@ namespace Disco.Services.Jobs.JobQueues
public JobQueueToken UpdateQueue(JobQueue JobQueue) public JobQueueToken UpdateQueue(JobQueue JobQueue)
{ {
var token = JobQueueToken.FromJobQueue(JobQueue); var token = JobQueueToken.FromJobQueue(JobQueue);
JobQueueToken existingToken;
if (_Cache.TryGetValue(JobQueue.Id, out existingToken)) if (_Cache.TryGetValue(JobQueue.Id, out var existingToken))
{ {
if (_Cache.TryUpdate(JobQueue.Id, token, existingToken)) if (_Cache.TryUpdate(JobQueue.Id, token, existingToken))
{ {
@@ -103,8 +102,7 @@ namespace Disco.Services.Jobs.JobQueues
} }
public bool RemoveQueue(int JobQueueId) public bool RemoveQueue(int JobQueueId)
{ {
JobQueueToken token; if (_Cache.TryRemove(JobQueueId, out _))
if (_Cache.TryRemove(JobQueueId, out token))
{ {
CalculateSubjectCache(); CalculateSubjectCache();
return true; return true;
@@ -116,8 +114,7 @@ namespace Disco.Services.Jobs.JobQueues
} }
public JobQueueToken GetQueue(int JobQueueId) public JobQueueToken GetQueue(int JobQueueId)
{ {
JobQueueToken token; if (_Cache.TryGetValue(JobQueueId, out var token))
if (_Cache.TryGetValue(JobQueueId, out token))
return token; return token;
else else
return null; return null;
@@ -128,8 +125,7 @@ namespace Disco.Services.Jobs.JobQueues
} }
private IEnumerable<JobQueueToken> GetQueuesForSubject(string SubjectId) private IEnumerable<JobQueueToken> GetQueuesForSubject(string SubjectId)
{ {
List<JobQueueToken> tokens; if (_SubjectCache.TryGetValue(SubjectId, out var tokens))
if (_SubjectCache.TryGetValue(SubjectId, out tokens))
return tokens; return tokens;
else else
return Enumerable.Empty<JobQueueToken>(); return Enumerable.Empty<JobQueueToken>();
@@ -14,7 +14,7 @@ namespace Disco.Services.Jobs.JobQueues
{ {
public static class JobQueueService public static class JobQueueService
{ {
private const string _cacheHttpRequestKey = "Disco_UserQueuesToken_{0}"; private const string _cacheHttpRequestKey = "Disco_UserQueuesToken";
private static Cache _cache; private static Cache _cache;
public static void Initialize(DiscoDataContext Database) public static void Initialize(DiscoDataContext Database)
@@ -168,20 +168,18 @@ namespace Disco.Services.Jobs.JobQueues
} }
public static ReadOnlyCollection<JobQueueToken> UsersQueues(AuthorizationToken UserAuthorization) public static ReadOnlyCollection<JobQueueToken> UsersQueues(AuthorizationToken UserAuthorization)
{ {
string cacheKey = string.Format(_cacheHttpRequestKey, UserAuthorization.User.UserId);
ReadOnlyCollection<JobQueueToken> tokens = null; ReadOnlyCollection<JobQueueToken> tokens = null;
// Check for ASP.NET // Check for ASP.NET
if (HttpContext.Current != null) if (HttpContext.Current != null)
{
tokens = (ReadOnlyCollection<JobQueueToken>)HttpContext.Current.Items[_cacheHttpRequestKey]; tokens = (ReadOnlyCollection<JobQueueToken>)HttpContext.Current.Items[_cacheHttpRequestKey];
}
if (tokens == null) if (tokens == null)
{ {
var subjectIds = (new string[] { UserAuthorization.User.UserId }).Concat(UserAuthorization.GroupMembership); var subjectIds = (new string[] { UserAuthorization.User.UserId }).Concat(UserAuthorization.GroupMembership);
tokens = _cache.GetQueuesForSubject(subjectIds); tokens = _cache.GetQueuesForSubject(subjectIds);
if (HttpContext.Current != null)
HttpContext.Current.Items[_cacheHttpRequestKey] = tokens; HttpContext.Current.Items[_cacheHttpRequestKey] = tokens;
} }
+1 -2
View File
@@ -53,14 +53,13 @@ namespace Disco.Services.Jobs
public override Task OnConnected() public override Task OnConnected()
{ {
int jobId;
string jobIdParam; string jobIdParam;
jobIdParam = Context.QueryString["JobId"]; jobIdParam = Context.QueryString["JobId"];
if (string.IsNullOrWhiteSpace(jobIdParam)) if (string.IsNullOrWhiteSpace(jobIdParam))
throw new ArgumentNullException("JobId"); throw new ArgumentNullException("JobId");
if (!int.TryParse(jobIdParam, out jobId)) if (!int.TryParse(jobIdParam, out var jobId))
throw new ArgumentException("An integer was expected", "JobId"); throw new ArgumentException("An integer was expected", "JobId");
var userAuth = UserService.GetAuthorization(Context.User.Identity.Name); var userAuth = UserService.GetAuthorization(Context.User.Identity.Name);
@@ -198,8 +198,7 @@ namespace Disco.Services.Jobs.Noticeboards
.ToDictionary(dsn => dsn, .ToDictionary(dsn => dsn,
dsn => dsn =>
{ {
IHeldDeviceItem item; items.TryGetValue(dsn, out var item);
items.TryGetValue(dsn, out item);
return item; return item;
}); });
@@ -27,8 +27,7 @@ namespace Disco.Services.Jobs.Noticeboards
.ToDictionary(userId => userId, .ToDictionary(userId => userId,
userId => userId =>
{ {
IHeldDeviceItem item; items.TryGetValue(userId, out var item);
items.TryGetValue(userId, out item);
return item; return item;
}); });
+4 -8
View File
@@ -72,8 +72,7 @@ namespace Disco.Services.Logging
foreach (var module in LogModules) foreach (var module in LogModules)
{ {
// Update/Insert Module // Update/Insert Module
Models.LogModule dbModule; if (existingModules.TryGetValue(module.Key, out var dbModule))
if (existingModules.TryGetValue(module.Key, out dbModule))
{ {
// Update // Update
if (dbModule.Name != module.Value.ModuleName) if (dbModule.Name != module.Value.ModuleName)
@@ -96,8 +95,7 @@ namespace Disco.Services.Logging
Dictionary<int, Models.LogEventType> existingEventTypes = (dbModule.EventTypes == null) ? new Dictionary<int, Models.LogEventType>() : dbModule.EventTypes.ToDictionary(et => et.Id); Dictionary<int, Models.LogEventType> existingEventTypes = (dbModule.EventTypes == null) ? new Dictionary<int, Models.LogEventType>() : dbModule.EventTypes.ToDictionary(et => et.Id);
foreach (var eventType in module.Value.EventTypes) foreach (var eventType in module.Value.EventTypes)
{ {
Models.LogEventType dbEventType; if (existingEventTypes.TryGetValue(eventType.Key, out var dbEventType))
if (existingEventTypes.TryGetValue(eventType.Key, out dbEventType))
{ {
// Update // Update
if (dbEventType.Name != eventType.Value.Name) if (dbEventType.Name != eventType.Value.Name)
@@ -253,11 +251,9 @@ namespace Disco.Services.Logging
public void Log(int ModuleId, int EventTypeId, params object[] Args) public void Log(int ModuleId, int EventTypeId, params object[] Args)
{ {
LogBase logModule; if (LogModules.TryGetValue(ModuleId, out var logModule))
if (LogModules.TryGetValue(ModuleId, out logModule))
{ {
Models.LogEventType eventType; if (logModule.EventTypes.TryGetValue(EventTypeId, out var eventType))
if (logModule.EventTypes.TryGetValue(EventTypeId, out eventType))
{ {
var eventTimestamp = DateTime.Now; var eventTimestamp = DateTime.Now;
if (eventType.UseLive) if (eventType.UseLive)
+1 -2
View File
@@ -103,8 +103,7 @@ namespace Disco.Services.Logging
List<string> logYears = new List<string>(); List<string> logYears = new List<string>();
foreach (var directoryName in logDirectoryBaseInfo.GetDirectories()) foreach (var directoryName in logDirectoryBaseInfo.GetDirectories())
{ {
int directoryYear; if (int.TryParse(directoryName.Name, out _))
if (int.TryParse(directoryName.Name, out directoryYear))
{ {
logYears.Add(directoryName.Name); logYears.Add(directoryName.Name);
} }
@@ -17,8 +17,7 @@ namespace Disco.Services.Plugins.Features.UIExtension
private static List<PluginFeatureManifest> GetUIModelRegistrations<UIModel>() where UIModel : BaseUIModel private static List<PluginFeatureManifest> GetUIModelRegistrations<UIModel>() where UIModel : BaseUIModel
{ {
Type uiModelType = typeof(UIModel); Type uiModelType = typeof(UIModel);
List<PluginFeatureManifest> modelRegistrations; if (!_registrations.TryGetValue(uiModelType, out var modelRegistrations))
if (!_registrations.TryGetValue(uiModelType, out modelRegistrations))
{ {
lock (_registrations) lock (_registrations)
{ {
+1 -2
View File
@@ -88,8 +88,7 @@ namespace Disco.Services.Plugins
// Check for Compatibility // Check for Compatibility
var libraryIncompatibility = PluginLibrary.LoadManifest(database).LoadIncompatibilityData(); var libraryIncompatibility = PluginLibrary.LoadManifest(database).LoadIncompatibilityData();
PluginIncompatibility incompatibility; if (!libraryIncompatibility.IsCompatible(packageManifest.Id, packageManifest.Version, out var incompatibility))
if (!libraryIncompatibility.IsCompatible(packageManifest.Id, packageManifest.Version, out incompatibility))
throw new InvalidOperationException($"The plugin [{packageManifest.Id} v{packageManifest.VersionFormatted}] is not compatible: {incompatibility.Reason}"); throw new InvalidOperationException($"The plugin [{packageManifest.Id} v{packageManifest.VersionFormatted}] is not compatible: {incompatibility.Reason}");
// Force Delete of Existing Folder // Force Delete of Existing Folder
+1 -2
View File
@@ -512,9 +512,8 @@ namespace Disco.Services.Plugins
var resourcePath = Path.Combine(PluginLocation, "WebResources", Resource.Replace(@"/", @"\")); var resourcePath = Path.Combine(PluginLocation, "WebResources", Resource.Replace(@"/", @"\"));
Tuple<string, DateTime> resourceHash;
string resourceKey = $"{Name}://{Resource}"; string resourceKey = $"{Name}://{Resource}";
if (WebResourceHashes.TryGetValue(resourceKey, out resourceHash)) if (WebResourceHashes.TryGetValue(resourceKey, out var resourceHash))
{ {
#if DEBUG #if DEBUG
var fileDateCheck = System.IO.File.GetLastWriteTime(resourcePath); var fileDateCheck = System.IO.File.GetLastWriteTime(resourcePath);
+7 -18
View File
@@ -49,9 +49,7 @@ namespace Disco.Services.Plugins
{ {
if (_PluginManifests == null) if (_PluginManifests == null)
throw new InvalidOperationException("Plugins have not been initialized"); throw new InvalidOperationException("Plugins have not been initialized");
return _PluginManifests.TryGetValue(PluginId, out _);
PluginManifest manifest;
return _PluginManifests.TryGetValue(PluginId, out manifest);
} }
public static PluginManifest GetPlugin(string PluginId, Type ContainsCategoryType) public static PluginManifest GetPlugin(string PluginId, Type ContainsCategoryType)
@@ -59,8 +57,7 @@ namespace Disco.Services.Plugins
if (_PluginManifests == null) if (_PluginManifests == null)
throw new InvalidOperationException("Plugins have not been initialized"); throw new InvalidOperationException("Plugins have not been initialized");
PluginManifest manifest; if (_PluginManifests.TryGetValue(PluginId, out var manifest))
if (_PluginManifests.TryGetValue(PluginId, out manifest))
{ {
if (ContainsCategoryType == null) if (ContainsCategoryType == null)
return manifest; return manifest;
@@ -87,8 +84,7 @@ namespace Disco.Services.Plugins
if (_PluginManifests == null) if (_PluginManifests == null)
return false; return false;
PluginManifest manifest; if (_PluginManifests.TryGetValue(PluginId, out var manifest))
if (_PluginManifests.TryGetValue(PluginId, out manifest))
{ {
if (ContainsCategoryType == null) if (ContainsCategoryType == null)
{ {
@@ -123,8 +119,7 @@ namespace Disco.Services.Plugins
if (_PluginAssemblyManifests == null) if (_PluginAssemblyManifests == null)
throw new InvalidOperationException("Plugins have not been initialized"); throw new InvalidOperationException("Plugins have not been initialized");
PluginManifest manifest; if (_PluginAssemblyManifests.TryGetValue(PluginAssembly, out var manifest))
if (_PluginAssemblyManifests.TryGetValue(PluginAssembly, out manifest))
{ {
return manifest; return manifest;
} }
@@ -135,19 +130,14 @@ namespace Disco.Services.Plugins
} }
public static bool TryGetPlugin(Assembly PluginAssembly, out PluginManifest PluginManifest) public static bool TryGetPlugin(Assembly PluginAssembly, out PluginManifest PluginManifest)
{ {
PluginManifest = null; if (_PluginAssemblyManifests?.TryGetValue(PluginAssembly, out var manifest) ?? false)
if (_PluginAssemblyManifests == null)
return false;
PluginManifest manifest;
if (_PluginAssemblyManifests.TryGetValue(PluginAssembly, out manifest))
{ {
PluginManifest = manifest; PluginManifest = manifest;
return true; return true;
} }
else else
{ {
PluginManifest = null;
return false; return false;
} }
} }
@@ -252,8 +242,7 @@ namespace Disco.Services.Plugins
if (FeatureCategoryType == null) if (FeatureCategoryType == null)
throw new ArgumentNullException("FeatureType"); throw new ArgumentNullException("FeatureType");
string displayName; if (FeatureCategoryDisplayNames.TryGetValue(FeatureCategoryType, out var displayName))
if (FeatureCategoryDisplayNames.TryGetValue(FeatureCategoryType, out displayName))
return displayName; return displayName;
else else
throw new InvalidOperationException($"Unknown Plugin Feature Category Type: [{FeatureCategoryType.Name}]"); throw new InvalidOperationException($"Unknown Plugin Feature Category Type: [{FeatureCategoryType.Name}]");
+1 -3
View File
@@ -96,7 +96,6 @@ namespace Disco.Services.Plugins
public static List<PluginManifest> OfflineInstalledPlugins(DiscoDataContext Database) public static List<PluginManifest> OfflineInstalledPlugins(DiscoDataContext Database)
{ {
string pluginsLocation = Database.DiscoConfiguration.PluginsLocation; string pluginsLocation = Database.DiscoConfiguration.PluginsLocation;
string pluginsStorageLocation = Database.DiscoConfiguration.PluginStorageLocation;
List<PluginManifest> installedPluginManifests = new List<PluginManifest>(); List<PluginManifest> installedPluginManifests = new List<PluginManifest>();
@@ -245,8 +244,7 @@ namespace Disco.Services.Plugins
{ {
// Check for Compatibility // Check for Compatibility
var incompatibilityLibrary = PluginLibrary.LoadManifest(database).LoadIncompatibilityData(); var incompatibilityLibrary = PluginLibrary.LoadManifest(database).LoadIncompatibilityData();
PluginIncompatibility incompatibility; if (!incompatibilityLibrary.IsCompatible(updateManifest.Id, updateManifest.Version, out var incompatibility))
if (!incompatibilityLibrary.IsCompatible(updateManifest.Id, updateManifest.Version, out incompatibility))
throw new InvalidOperationException($"The plugin [{updateManifest.Id} v{updateManifest.VersionFormatted}] is not compatible: {incompatibility.Reason}"); throw new InvalidOperationException($"The plugin [{updateManifest.Id} v{updateManifest.VersionFormatted}] is not compatible: {incompatibility.Reason}");
var updatePluginPath = Path.Combine(database.DiscoConfiguration.PluginsLocation, $"{updateManifest.Id}.discoPlugin"); var updatePluginPath = Path.Combine(database.DiscoConfiguration.PluginsLocation, $"{updateManifest.Id}.discoPlugin");
+2 -4
View File
@@ -17,13 +17,12 @@ namespace Disco.Services.Searching
#region Jobs #region Jobs
public static List<JobSearchResultItem> SearchJobs(DiscoDataContext Database, string Term, int? LimitCount = ActiveDirectory.DefaultSearchResultLimit) public static List<JobSearchResultItem> SearchJobs(DiscoDataContext Database, string Term, int? LimitCount = ActiveDirectory.DefaultSearchResultLimit)
{ {
int termInt = default(int);
IQueryable<Job> query = default(IQueryable<Job>); IQueryable<Job> query = default(IQueryable<Job>);
string userIdTerm = Term.Contains('\\') ? Term : ActiveDirectory.ParseDomainAccountId(Term); string userIdTerm = Term.Contains('\\') ? Term : ActiveDirectory.ParseDomainAccountId(Term);
if (int.TryParse(Term, out termInt)) if (int.TryParse(Term, out var termInt))
{ {
// Term is a Number (int) // Term is a Number (int)
query = Database.Jobs.Where(j => query = Database.Jobs.Where(j =>
@@ -198,8 +197,7 @@ namespace Disco.Services.Searching
// Update DB Results // Update DB Results
dbResults.ForEach(u => dbResults.ForEach(u =>
{ {
UserSearchResultItem adResult; if (adResultsIndexed.TryGetValue(u.Id, out var adResult))
if (adResultsIndexed.TryGetValue(u.Id, out adResult))
{ {
u.Surname = adResult.Surname; u.Surname = adResult.Surname;
u.GivenName = adResult.GivenName; u.GivenName = adResult.GivenName;
+7 -11
View File
@@ -143,13 +143,12 @@ namespace Disco.Services.Users
{ {
var cache = _Cache; var cache = _Cache;
Tuple<User, AuthorizationToken, DateTime> record; if (cache.TryGetValue(UserId, out var record))
if (cache.TryGetValue(UserId, out record))
{ {
if (record.Item3 > DateTime.Now) if (record.Item3 > DateTime.Now)
return record; return record;
else else
cache.TryRemove(UserId, out record); cache.TryRemove(UserId, out _);
} }
return null; return null;
} }
@@ -158,11 +157,10 @@ namespace Disco.Services.Users
{ {
var cache = _Cache; var cache = _Cache;
Tuple<User, AuthorizationToken, DateTime> record = new Tuple<User, AuthorizationToken, DateTime>(Record.Item1, Record.Item2, DateTime.Now.AddTicks(CacheTimeoutTicks)); var record = new Tuple<User, AuthorizationToken, DateTime>(Record.Item1, Record.Item2, DateTime.Now.AddTicks(CacheTimeoutTicks));
if (cache.ContainsKey(UserId)) if (cache.ContainsKey(UserId))
{ {
Tuple<User, AuthorizationToken, DateTime> oldRecord; if (cache.TryGetValue(UserId, out var oldRecord))
if (cache.TryGetValue(UserId, out oldRecord))
{ {
cache.TryUpdate(UserId, record, oldRecord); cache.TryUpdate(UserId, record, oldRecord);
return record; return record;
@@ -174,8 +172,7 @@ namespace Disco.Services.Users
internal static bool InvalidateRecord(string UserId) internal static bool InvalidateRecord(string UserId)
{ {
Tuple<User, AuthorizationToken, DateTime> userRecord; return _Cache.TryRemove(UserId, out _);
return _Cache.TryRemove(UserId, out userRecord);
} }
internal static void CleanStaleCache() internal static void CleanStaleCache()
@@ -185,11 +182,10 @@ namespace Disco.Services.Users
var userIds = cache.Keys.ToArray(); var userIds = cache.Keys.ToArray();
foreach (string userId in userIds) foreach (string userId in userIds)
{ {
Tuple<User, AuthorizationToken, DateTime> record; if (cache.TryGetValue(userId, out var record))
if (cache.TryGetValue(userId, out record))
{ {
if (record.Item3 <= DateTime.Now) if (record.Item3 <= DateTime.Now)
cache.TryRemove(userId, out record); cache.TryRemove(userId, out _);
} }
} }
} }
+2 -4
View File
@@ -31,8 +31,7 @@ namespace Disco.Services.Users.UserFlags
public UserFlag GetUserFlag(int UserFlagId) public UserFlag GetUserFlag(int UserFlagId)
{ {
UserFlag item; if (_Cache.TryGetValue(UserFlagId, out var item))
if (_Cache.TryGetValue(UserFlagId, out item))
return item; return item;
else else
return null; return null;
@@ -49,8 +48,7 @@ namespace Disco.Services.Users.UserFlags
public UserFlag Remove(int UserFlagId) public UserFlag Remove(int UserFlagId)
{ {
UserFlag item; if (_Cache.TryRemove(UserFlagId, out var item))
if (_Cache.TryRemove(UserFlagId, out item))
return item; return item;
else else
return null; return null;
@@ -57,10 +57,9 @@ namespace Disco.Services.Users.UserFlags
public static bool TryGetManagedGroup(UserFlag UserFlag, out UserFlagUserDevicesManagedGroup ManagedGroup) public static bool TryGetManagedGroup(UserFlag UserFlag, out UserFlagUserDevicesManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(UserFlag); string key = GetKey(UserFlag);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (UserFlagUserDevicesManagedGroup)managedGroup; ManagedGroup = (UserFlagUserDevicesManagedGroup)managedGroup;
return true; return true;
@@ -57,10 +57,9 @@ namespace Disco.Services.Users.UserFlags
public static bool TryGetManagedGroup(UserFlag UserFlag, out UserFlagUsersManagedGroup ManagedGroup) public static bool TryGetManagedGroup(UserFlag UserFlag, out UserFlagUsersManagedGroup ManagedGroup)
{ {
ADManagedGroup managedGroup;
string key = GetKey(UserFlag); string key = GetKey(UserFlag);
if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out managedGroup)) if (ActiveDirectory.Context.ManagedGroups.TryGetValue(key, out var managedGroup))
{ {
ManagedGroup = (UserFlagUsersManagedGroup)managedGroup; ManagedGroup = (UserFlagUsersManagedGroup)managedGroup;
return true; return true;
+1 -3
View File
@@ -43,9 +43,7 @@ namespace Disco.Services.Web.Bundles
throw new ArgumentNullException("Url"); throw new ArgumentNullException("Url");
if (string.IsNullOrWhiteSpace(File)) if (string.IsNullOrWhiteSpace(File))
throw new ArgumentNullException("File"); throw new ArgumentNullException("File");
if (!Uri.TryCreate(File, UriKind.Absolute, out _))
Uri fileUri;
if (!Uri.TryCreate(File, UriKind.Absolute, out fileUri))
{ {
File = HttpContext.Current.Server.MapPath(File); File = HttpContext.Current.Server.MapPath(File);
} }
@@ -295,8 +295,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new ArgumentNullException("PurchaseDate", "A Device Batch Purchase Date is required"); throw new ArgumentNullException("PurchaseDate", "A Device Batch Purchase Date is required");
else else
{ {
DateTime ecd; if (DateTime.TryParse(PurchaseDate, out var ecd))
if (DateTime.TryParse(PurchaseDate, out ecd))
{ {
deviceBatch.PurchaseDate = ecd.Date; deviceBatch.PurchaseDate = ecd.Date;
} }
@@ -329,8 +328,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.UnitCost = null; deviceBatch.UnitCost = null;
else else
{ {
decimal unitCost; if (decimal.TryParse(UnitCost, out var unitCost))
if (decimal.TryParse(UnitCost, out unitCost))
{ {
deviceBatch.UnitCost = unitCost; deviceBatch.UnitCost = unitCost;
} }
@@ -347,8 +345,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.UnitQuantity = null; deviceBatch.UnitQuantity = null;
else else
{ {
int unitQuantity; if (int.TryParse(UnitQuantity, out var unitQuantity))
if (int.TryParse(UnitQuantity, out unitQuantity))
{ {
deviceBatch.UnitQuantity = unitQuantity; deviceBatch.UnitQuantity = unitQuantity;
} }
@@ -363,8 +360,7 @@ namespace Disco.Web.Areas.API.Controllers
{ {
if (!string.IsNullOrEmpty(DefaultDeviceModelId)) if (!string.IsNullOrEmpty(DefaultDeviceModelId))
{ {
int bId; if (int.TryParse(DefaultDeviceModelId, out var bId))
if (int.TryParse(DefaultDeviceModelId, out bId))
{ {
var dm = Database.DeviceModels.Find(bId); var dm = Database.DeviceModels.Find(bId);
if (dm != null) if (dm != null)
@@ -394,8 +390,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.WarrantyValidUntil = null; deviceBatch.WarrantyValidUntil = null;
else else
{ {
DateTime ecd; if (DateTime.TryParse(WarrantyValidUntil, out var ecd))
if (DateTime.TryParse(WarrantyValidUntil, out ecd))
{ {
deviceBatch.WarrantyValidUntil = ecd.Date; deviceBatch.WarrantyValidUntil = ecd.Date;
} }
@@ -420,8 +415,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.InsuredDate = null; deviceBatch.InsuredDate = null;
else else
{ {
DateTime ecd; if (DateTime.TryParse(InsuredDate, out var ecd))
if (DateTime.TryParse(InsuredDate, out ecd))
{ {
deviceBatch.InsuredDate = ecd.Date; deviceBatch.InsuredDate = ecd.Date;
} }
@@ -446,8 +440,7 @@ namespace Disco.Web.Areas.API.Controllers
deviceBatch.InsuredUntil = null; deviceBatch.InsuredUntil = null;
else else
{ {
DateTime ecd; if (DateTime.TryParse(InsuredUntil, out var ecd))
if (DateTime.TryParse(InsuredUntil, out ecd))
{ {
deviceBatch.InsuredUntil = ecd.Date; deviceBatch.InsuredUntil = ecd.Date;
} }
@@ -220,8 +220,7 @@ namespace Disco.Web.Areas.API.Controllers
{ {
if (!string.IsNullOrEmpty(DeviceProfileId)) if (!string.IsNullOrEmpty(DeviceProfileId))
{ {
int pId; if (int.TryParse(DeviceProfileId, out var pId))
if (int.TryParse(DeviceProfileId, out pId))
{ {
var p = Database.DeviceProfiles.Find(pId); var p = Database.DeviceProfiles.Find(pId);
if (p != null) if (p != null)
@@ -248,8 +247,7 @@ namespace Disco.Web.Areas.API.Controllers
{ {
if (!string.IsNullOrEmpty(DeviceBatchId)) if (!string.IsNullOrEmpty(DeviceBatchId))
{ {
int bId; if (int.TryParse(DeviceBatchId, out var bId))
if (int.TryParse(DeviceBatchId, out bId))
{ {
var b = Database.DeviceBatches.Find(bId); var b = Database.DeviceBatches.Find(bId);
if (b != null) if (b != null)
@@ -306,8 +304,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
private void UpdateAllowUnauthenticatedEnrol(Device device, string AllowUnauthenticatedEnrol) private void UpdateAllowUnauthenticatedEnrol(Device device, string AllowUnauthenticatedEnrol)
{ {
bool bAllowUnauthenticatedEnrol; if (string.IsNullOrEmpty(AllowUnauthenticatedEnrol) || !bool.TryParse(AllowUnauthenticatedEnrol, out var bAllowUnauthenticatedEnrol))
if (string.IsNullOrEmpty(AllowUnauthenticatedEnrol) || !bool.TryParse(AllowUnauthenticatedEnrol, out bAllowUnauthenticatedEnrol))
{ {
throw new Exception("Invalid AllowUnauthenticatedEnrol Value"); throw new Exception("Invalid AllowUnauthenticatedEnrol Value");
} }
@@ -158,8 +158,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(DefaultPurchaseDate, out var d))
if (DateTime.TryParse(DefaultPurchaseDate, out d))
{ {
deviceModel.DefaultPurchaseDate = d; deviceModel.DefaultPurchaseDate = d;
} }
@@ -327,12 +326,11 @@ namespace Disco.Web.Areas.API.Controllers
} }
} }
decimal cost = 0;
if (string.IsNullOrEmpty(Description)) if (string.IsNullOrEmpty(Description))
Description = "?"; Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$")) if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1); Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out cost); decimal.TryParse(Cost, out var cost);
var dc = new DeviceComponent() var dc = new DeviceComponent()
{ {
@@ -381,13 +379,12 @@ namespace Disco.Web.Areas.API.Controllers
var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault(); var dc = Database.DeviceComponents.Include("JobSubTypes").Where(i => i.Id == id).FirstOrDefault();
if (dc != null) if (dc != null)
{ {
decimal cost = 0;
if (string.IsNullOrEmpty(Description)) if (string.IsNullOrEmpty(Description))
Description = "?"; Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$")) if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1); Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out cost); decimal.TryParse(Cost, out var cost);
dc.Description = Description; dc.Description = Description;
dc.Cost = cost; dc.Cost = cost;
@@ -442,8 +442,7 @@ namespace Disco.Web.Areas.API.Controllers
private void UpdateDistributionType(DeviceProfile deviceProfile, string DistributionType) private void UpdateDistributionType(DeviceProfile deviceProfile, string DistributionType)
{ {
int iDt; if (int.TryParse(DistributionType, out var iDt))
if (int.TryParse(DistributionType, out iDt))
{ {
deviceProfile.DistributionType = (DeviceProfile.DistributionTypes)iDt; deviceProfile.DistributionType = (DeviceProfile.DistributionTypes)iDt;
Database.SaveChanges(); Database.SaveChanges();
@@ -581,8 +580,7 @@ namespace Disco.Web.Areas.API.Controllers
else else
{ {
// Validate // Validate
int daoId; if (int.TryParse(DefaultOrganisationAddress, out var daoId))
if (int.TryParse(DefaultOrganisationAddress, out daoId))
{ {
var oa = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(daoId); var oa = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(daoId);
if (oa != null) if (oa != null)
@@ -606,8 +604,7 @@ namespace Disco.Web.Areas.API.Controllers
private void UpdateEnforceComputerNameConvention(DeviceProfile deviceProfile, string EnforceComputerNameConvention) private void UpdateEnforceComputerNameConvention(DeviceProfile deviceProfile, string EnforceComputerNameConvention)
{ {
bool bValue; if (bool.TryParse(EnforceComputerNameConvention, out var bValue))
if (bool.TryParse(EnforceComputerNameConvention, out bValue))
{ {
deviceProfile.EnforceComputerNameConvention = bValue; deviceProfile.EnforceComputerNameConvention = bValue;
@@ -619,8 +616,7 @@ namespace Disco.Web.Areas.API.Controllers
private void UpdateEnforceOrganisationalUnit(DeviceProfile deviceProfile, string EnforceOrganisationalUnit) private void UpdateEnforceOrganisationalUnit(DeviceProfile deviceProfile, string EnforceOrganisationalUnit)
{ {
bool bValue; if (bool.TryParse(EnforceOrganisationalUnit, out var bValue))
if (bool.TryParse(EnforceOrganisationalUnit, out bValue))
{ {
deviceProfile.EnforceOrganisationalUnit = bValue; deviceProfile.EnforceOrganisationalUnit = bValue;
@@ -632,8 +628,7 @@ namespace Disco.Web.Areas.API.Controllers
private void UpdateProvisionADAccount(DeviceProfile deviceProfile, string ProvisionADAccount) private void UpdateProvisionADAccount(DeviceProfile deviceProfile, string ProvisionADAccount)
{ {
bool bValue; if (bool.TryParse(ProvisionADAccount, out var bValue))
if (bool.TryParse(ProvisionADAccount, out bValue))
{ {
deviceProfile.ProvisionADAccount = bValue; deviceProfile.ProvisionADAccount = bValue;
@@ -645,8 +640,7 @@ namespace Disco.Web.Areas.API.Controllers
private void UpdateAssignedUserLocalAdmin(DeviceProfile deviceProfile, string AssignedUserLocalAdmin) private void UpdateAssignedUserLocalAdmin(DeviceProfile deviceProfile, string AssignedUserLocalAdmin)
{ {
bool bValue; if (bool.TryParse(AssignedUserLocalAdmin, out var bValue))
if (bool.TryParse(AssignedUserLocalAdmin, out bValue))
{ {
deviceProfile.AssignedUserLocalAdmin = bValue; deviceProfile.AssignedUserLocalAdmin = bValue;
@@ -658,8 +652,7 @@ namespace Disco.Web.Areas.API.Controllers
private void UpdateAllowUntrustedReimageJobEnrolment(DeviceProfile deviceProfile, string AllowUntrustedReimageJobEnrolment) private void UpdateAllowUntrustedReimageJobEnrolment(DeviceProfile deviceProfile, string AllowUntrustedReimageJobEnrolment)
{ {
bool bValue; if (bool.TryParse(AllowUntrustedReimageJobEnrolment, out var bValue))
if (bool.TryParse(AllowUntrustedReimageJobEnrolment, out bValue))
{ {
deviceProfile.AllowUntrustedReimageJobEnrolment = bValue; deviceProfile.AllowUntrustedReimageJobEnrolment = bValue;
@@ -404,8 +404,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
bool ff = default(bool); if (bool.TryParse(FlattenForm, out var ff))
if (bool.TryParse(FlattenForm, out ff))
documentTemplate.FlattenForm = ff; documentTemplate.FlattenForm = ff;
else else
throw new Exception("Invalid Boolean Format"); throw new Exception("Invalid Boolean Format");
@@ -421,8 +420,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
bool value = default(bool); if (bool.TryParse(IsHidden, out var value))
if (bool.TryParse(IsHidden, out value))
documentTemplate.IsHidden = value; documentTemplate.IsHidden = value;
else else
throw new Exception("Invalid Boolean Format"); throw new Exception("Invalid Boolean Format");
@@ -235,8 +235,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
private void UpdateScope(DocumentTemplatePackage Package, string Scope) private void UpdateScope(DocumentTemplatePackage Package, string Scope)
{ {
AttachmentTypes scope; if (!Enum.TryParse<AttachmentTypes>(Scope, true, out var scope))
if (!Enum.TryParse(Scope, true, out scope))
throw new ArgumentException("Invalid Scope", nameof(Scope)); throw new ArgumentException("Invalid Scope", nameof(Scope));
if (Package.Scope != scope) if (Package.Scope != scope)
@@ -514,8 +514,7 @@ namespace Disco.Web.Areas.API.Controllers
{ {
if (!string.IsNullOrEmpty(ExpectedClosedDate)) if (!string.IsNullOrEmpty(ExpectedClosedDate))
{ {
DateTime ecd; if (DateTime.TryParse(ExpectedClosedDate, out var ecd))
if (DateTime.TryParse(ExpectedClosedDate, out ecd))
{ {
ecd = job.ValidateDateAfterOpened(ecd); ecd = job.ValidateDateAfterOpened(ecd);
job.ExpectedClosedDate = ecd; job.ExpectedClosedDate = ecd;
@@ -574,8 +573,7 @@ namespace Disco.Web.Areas.API.Controllers
flags = 0; flags = 0;
foreach (var fs in Flags.Split(',')) foreach (var fs in Flags.Split(','))
{ {
long fi; if (!long.TryParse(fs, out var fi))
if (!long.TryParse(fs, out fi))
throw new Exception("Invalid Int64 Format"); throw new Exception("Invalid Int64 Format");
else else
flags = flags | fi; flags = flags | fi;
@@ -614,8 +612,7 @@ namespace Disco.Web.Areas.API.Controllers
{ {
throw new Exception("This property can only be set for Hardware NonWarranty Jobs"); throw new Exception("This property can only be set for Hardware NonWarranty Jobs");
} }
bool bIsInsuranceClaim; if (string.IsNullOrEmpty(IsInsuranceClaim) || !bool.TryParse(IsInsuranceClaim, out var bIsInsuranceClaim))
if (string.IsNullOrEmpty(IsInsuranceClaim) || !bool.TryParse(IsInsuranceClaim, out bIsInsuranceClaim))
{ {
throw new Exception("Invalid IsInsuranceClaim Value"); throw new Exception("Invalid IsInsuranceClaim Value");
} }
@@ -660,8 +657,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(AccountingChargeRequiredDate, out var d))
if (DateTime.TryParse(AccountingChargeRequiredDate, out d))
{ {
d = job.ValidateDateAfterOpened(d); d = job.ValidateDateAfterOpened(d);
job.JobMetaNonWarranty.AccountingChargeRequiredDate = d; job.JobMetaNonWarranty.AccountingChargeRequiredDate = d;
@@ -694,8 +690,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(AccountingChargeAddedDate, out var d))
if (DateTime.TryParse(AccountingChargeAddedDate, out d))
{ {
d = job.ValidateDateAfterOpened(d); d = job.ValidateDateAfterOpened(d);
job.JobMetaNonWarranty.AccountingChargeAddedDate = d; job.JobMetaNonWarranty.AccountingChargeAddedDate = d;
@@ -728,8 +723,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(AccountingChargePaidDate, out var d))
if (DateTime.TryParse(AccountingChargePaidDate, out d))
{ {
d = job.ValidateDateAfterOpened(d); d = job.ValidateDateAfterOpened(d);
job.JobMetaNonWarranty.AccountingChargePaidDate = d; job.JobMetaNonWarranty.AccountingChargePaidDate = d;
@@ -762,8 +756,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(PurchaseOrderRaisedDate, out var d))
if (DateTime.TryParse(PurchaseOrderRaisedDate, out d))
{ {
d = job.ValidateDateAfterOpened(d); d = job.ValidateDateAfterOpened(d);
job.JobMetaNonWarranty.PurchaseOrderRaisedDate = d; job.JobMetaNonWarranty.PurchaseOrderRaisedDate = d;
@@ -805,8 +798,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(PurchaseOrderSentDate, out var d))
if (DateTime.TryParse(PurchaseOrderSentDate, out d))
{ {
d = job.ValidateDateAfterOpened(d); d = job.ValidateDateAfterOpened(d);
job.JobMetaNonWarranty.PurchaseOrderSentDate = d; job.JobMetaNonWarranty.PurchaseOrderSentDate = d;
@@ -839,8 +831,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(InvoiceReceivedDate, out var d))
if (DateTime.TryParse(InvoiceReceivedDate, out d))
{ {
d = job.ValidateDateAfterOpened(d); d = job.ValidateDateAfterOpened(d);
job.JobMetaNonWarranty.InvoiceReceivedDate = d; job.JobMetaNonWarranty.InvoiceReceivedDate = d;
@@ -898,8 +889,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(RepairerLoggedDate, out var d))
if (DateTime.TryParse(RepairerLoggedDate, out d))
{ {
job.JobMetaNonWarranty.RepairerLoggedDate = d; job.JobMetaNonWarranty.RepairerLoggedDate = d;
} }
@@ -949,8 +939,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(RepairerCompletedDate, out var d))
if (DateTime.TryParse(RepairerCompletedDate, out d))
{ {
job.JobMetaNonWarranty.RepairerCompletedDate = d; job.JobMetaNonWarranty.RepairerCompletedDate = d;
} }
@@ -987,8 +976,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(ClaimFormSentDate, out var d))
if (DateTime.TryParse(ClaimFormSentDate, out d))
{ {
d = job.ValidateDateAfterOpened(d); d = job.ValidateDateAfterOpened(d);
job.JobMetaInsurance.ClaimFormSentDate = d; job.JobMetaInsurance.ClaimFormSentDate = d;
@@ -1023,8 +1011,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime dt; if (!DateTime.TryParse(DateOfPurchase, out var dt))
if (!DateTime.TryParse(DateOfPurchase, out dt))
{ {
throw new Exception("Invalid DateTime Value"); throw new Exception("Invalid DateTime Value");
} }
@@ -1104,8 +1091,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime dt; if (!DateTime.TryParse(PoliceNotifiedDate, out var dt))
if (!DateTime.TryParse(PoliceNotifiedDate, out dt))
{ {
throw new Exception("Invalid DateTime Value"); throw new Exception("Invalid DateTime Value");
} }
@@ -1141,8 +1127,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("This property can only be set for Hardware NonWarranty Jobs"); throw new Exception("This property can only be set for Hardware NonWarranty Jobs");
} }
bool b; if (string.IsNullOrEmpty(PoliceNotified) || !bool.TryParse(PoliceNotified, out var b))
if (string.IsNullOrEmpty(PoliceNotified) || !bool.TryParse(PoliceNotified, out b))
{ {
throw new Exception("Invalid Boolean Value"); throw new Exception("Invalid Boolean Value");
} }
@@ -1165,8 +1150,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(PropertyLastSeenDate, out var d))
if (DateTime.TryParse(PropertyLastSeenDate, out d))
{ {
job.JobMetaInsurance.PropertyLastSeenDate = d; job.JobMetaInsurance.PropertyLastSeenDate = d;
} }
@@ -1262,8 +1246,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("This property can only be set for Hardware NonWarranty Jobs"); throw new Exception("This property can only be set for Hardware NonWarranty Jobs");
} }
bool b; if (string.IsNullOrEmpty(ThirdPartyCaused) || !bool.TryParse(ThirdPartyCaused, out var b))
if (string.IsNullOrEmpty(ThirdPartyCaused) || !bool.TryParse(ThirdPartyCaused, out b))
{ {
throw new Exception("Invalid Boolean Value"); throw new Exception("Invalid Boolean Value");
} }
@@ -1324,8 +1307,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(LossOrDamageDate, out var d))
if (DateTime.TryParse(LossOrDamageDate, out d))
{ {
job.JobMetaInsurance.LossOrDamageDate = d; job.JobMetaInsurance.LossOrDamageDate = d;
} }
@@ -1372,8 +1354,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(ExternalLoggedDate, out var d))
if (DateTime.TryParse(ExternalLoggedDate, out d))
{ {
job.JobMetaWarranty.ExternalLoggedDate = d; job.JobMetaWarranty.ExternalLoggedDate = d;
} }
@@ -1424,8 +1405,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
else else
{ {
DateTime d; if (DateTime.TryParse(ExternalCompletedDate, out var d))
if (DateTime.TryParse(ExternalCompletedDate, out d))
{ {
job.JobMetaWarranty.ExternalCompletedDate = d; job.JobMetaWarranty.ExternalCompletedDate = d;
} }
@@ -1495,8 +1475,7 @@ namespace Disco.Web.Areas.API.Controllers
var flag = Flag.Value; var flag = Flag.Value;
var validFlags = job.ValidFlags(); var validFlags = job.ValidFlags();
Tuple<string, bool> flagStatus; if (validFlags.TryGetValue(flag < 0 ? flag * -1 : flag, out var flagStatus))
if (validFlags.TryGetValue((flag < 0 ? flag * -1 : flag), out flagStatus))
{ {
if (flag < 0) if (flag < 0)
{ // Remove Flag { // Remove Flag
@@ -2067,12 +2046,11 @@ namespace Disco.Web.Areas.API.Controllers
var j = Database.Jobs.Find(id); var j = Database.Jobs.Find(id);
if (j != null) if (j != null)
{ {
decimal cost = 0;
if (string.IsNullOrEmpty(Description)) if (string.IsNullOrEmpty(Description))
Description = "?"; Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$")) if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1); Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out cost); decimal.TryParse(Cost, out var cost);
var jc = new JobComponent() var jc = new JobComponent()
{ {
@@ -2095,13 +2073,12 @@ namespace Disco.Web.Areas.API.Controllers
var jc = Database.JobComponents.Find(id); var jc = Database.JobComponents.Find(id);
if (jc != null) if (jc != null)
{ {
decimal cost = 0;
if (string.IsNullOrEmpty(Description)) if (string.IsNullOrEmpty(Description))
Description = "?"; Description = "?";
if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$")) if (!string.IsNullOrEmpty(Cost) && Cost.Contains("$"))
Cost = Cost.Substring(Cost.IndexOf("$") + 1); Cost = Cost.Substring(Cost.IndexOf("$") + 1);
decimal.TryParse(Cost, out cost); decimal.TryParse(Cost, out var cost);
jc.Description = Description; jc.Description = Description;
jc.Cost = cost; jc.Cost = cost;
@@ -247,9 +247,8 @@ namespace Disco.Web.Areas.API.Controllers
private void UpdatePriority(JobQueue jobQueue, string Priority) private void UpdatePriority(JobQueue jobQueue, string Priority)
{ {
JobQueuePriority priority;
if (!Enum.TryParse(Priority, out priority)) if (!Enum.TryParse<JobQueuePriority>(Priority, out var priority))
throw new ArgumentException("Invalid Priority Value", "Priority"); throw new ArgumentException("Invalid Priority Value", "Priority");
jobQueue.Priority = priority; jobQueue.Priority = priority;
@@ -262,9 +261,8 @@ namespace Disco.Web.Areas.API.Controllers
if (!string.IsNullOrEmpty(DefaultSLAExpiry)) if (!string.IsNullOrEmpty(DefaultSLAExpiry))
{ {
int intValue;
if (!int.TryParse(DefaultSLAExpiry, out intValue)) if (!int.TryParse(DefaultSLAExpiry, out var intValue))
throw new ArgumentException("Invalid Default SLA Expiry Value", "DefaultSLAPriority"); throw new ArgumentException("Invalid Default SLA Expiry Value", "DefaultSLAPriority");
if (intValue < 0) if (intValue < 0)
@@ -142,8 +142,7 @@ namespace Disco.Web.Areas.API.Controllers
if (!string.IsNullOrEmpty(Sla)) if (!string.IsNullOrEmpty(Sla))
{ {
DateTime SLADate; if (DateTime.TryParse(Sla, out var SLADate))
if (DateTime.TryParse(Sla, out SLADate))
{ {
jobQueueJob.OnEditSla(SLADate); jobQueueJob.OnEditSla(SLADate);
Database.SaveChanges(); Database.SaveChanges();
@@ -164,9 +163,8 @@ namespace Disco.Web.Areas.API.Controllers
if (!jobQueueJob.CanEditPriority()) if (!jobQueueJob.CanEditPriority())
throw new InvalidOperationException("Editing Priority for job queue job is Denied"); throw new InvalidOperationException("Editing Priority for job queue job is Denied");
JobQueuePriority priority;
if (!Enum.TryParse(Priority, out priority)) if (!Enum.TryParse<JobQueuePriority>(Priority, out var priority))
throw new ArgumentException("Invalid Priority Value", "Priority"); throw new ArgumentException("Invalid Priority Value", "Priority");
jobQueueJob.OnEditPriority(priority); jobQueueJob.OnEditPriority(priority);
@@ -344,9 +344,8 @@ namespace Disco.Web.Areas.API.Controllers
[DiscoAuthorizeAny(Claims.Config.UserFlag.Configure)] [DiscoAuthorizeAny(Claims.Config.UserFlag.Configure)]
public virtual ActionResult SyncActiveDirectoryManagedGroup(string id, string redirectUrl = null) public virtual ActionResult SyncActiveDirectoryManagedGroup(string id, string redirectUrl = null)
{ {
ADManagedGroup managedGroup;
if (!ActiveDirectory.Context.ManagedGroups.TryGetValue(id, out managedGroup)) if (!ActiveDirectory.Context.ManagedGroups.TryGetValue(id, out var managedGroup))
throw new ArgumentException("Unknown Managed Group Key"); throw new ArgumentException("Unknown Managed Group Key");
var taskStatus = ADManagedGroupsSyncTask.ScheduleSync(managedGroup); var taskStatus = ADManagedGroupsSyncTask.ScheduleSync(managedGroup);
@@ -313,8 +313,7 @@ namespace Disco.Web.Areas.API.Controllers
if (UserFlag.UsersLinkedGroup != null) if (UserFlag.UsersLinkedGroup != null)
{ {
// Sync Group // Sync Group
UserFlagUsersManagedGroup managedGroup; if (UserFlagUsersManagedGroup.TryGetManagedGroup(UserFlag, out var managedGroup))
if (UserFlagUsersManagedGroup.TryGetManagedGroup(UserFlag, out managedGroup))
{ {
return ADManagedGroupsSyncTask.ScheduleSync(managedGroup); return ADManagedGroupsSyncTask.ScheduleSync(managedGroup);
} }
@@ -335,8 +334,7 @@ namespace Disco.Web.Areas.API.Controllers
if (UserFlag.UserDevicesLinkedGroup != null) if (UserFlag.UserDevicesLinkedGroup != null)
{ {
// Sync Group // Sync Group
UserFlagUserDevicesManagedGroup managedGroup; if (UserFlagUserDevicesManagedGroup.TryGetManagedGroup(UserFlag, out var managedGroup))
if (UserFlagUserDevicesManagedGroup.TryGetManagedGroup(UserFlag, out managedGroup))
{ {
return ADManagedGroupsSyncTask.ScheduleSync(managedGroup); return ADManagedGroupsSyncTask.ScheduleSync(managedGroup);
} }
@@ -41,11 +41,9 @@ namespace Disco.Web.Areas.Config.Controllers
DeviceDecommissionedCount = dG.Count(d => d.DecommissionedDate.HasValue) DeviceDecommissionedCount = dG.Count(d => d.DecommissionedDate.HasValue)
}).ToArray().Cast<ConfigDeviceBatchShowModelMembership>().ToList(); }).ToArray().Cast<ConfigDeviceBatchShowModelMembership>().ToList();
DeviceBatchAssignedUsersManagedGroup assignedUsersManagedGroup; if (DeviceBatchAssignedUsersManagedGroup.TryGetManagedGroup(m.DeviceBatch, out var assignedUsersManagedGroup))
if (DeviceBatchAssignedUsersManagedGroup.TryGetManagedGroup(m.DeviceBatch, out assignedUsersManagedGroup))
m.AssignedUsersLinkedGroup = assignedUsersManagedGroup; m.AssignedUsersLinkedGroup = assignedUsersManagedGroup;
DeviceBatchDevicesManagedGroup devicesManagedGroup; if (DeviceBatchDevicesManagedGroup.TryGetManagedGroup(m.DeviceBatch, out var devicesManagedGroup))
if (DeviceBatchDevicesManagedGroup.TryGetManagedGroup(m.DeviceBatch, out devicesManagedGroup))
m.DevicesLinkedGroup = devicesManagedGroup; m.DevicesLinkedGroup = devicesManagedGroup;
m.CanDelete = m.DeviceBatch.CanDelete(Database); m.CanDelete = m.DeviceBatch.CanDelete(Database);
@@ -39,11 +39,9 @@ namespace Disco.Web.Areas.Config.Controllers
if (m.DeviceProfile.DefaultOrganisationAddress.HasValue) if (m.DeviceProfile.DefaultOrganisationAddress.HasValue)
m.DefaultOrganisationAddress = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(m.DeviceProfile.DefaultOrganisationAddress.Value); m.DefaultOrganisationAddress = Database.DiscoConfiguration.OrganisationAddresses.GetAddress(m.DeviceProfile.DefaultOrganisationAddress.Value);
DeviceProfileAssignedUsersManagedGroup assignedUsersManagedGroup; if (DeviceProfileAssignedUsersManagedGroup.TryGetManagedGroup(m.DeviceProfile, out var assignedUsersManagedGroup))
if (DeviceProfileAssignedUsersManagedGroup.TryGetManagedGroup(m.DeviceProfile, out assignedUsersManagedGroup))
m.AssignedUsersLinkedGroup = assignedUsersManagedGroup; m.AssignedUsersLinkedGroup = assignedUsersManagedGroup;
DeviceProfileDevicesManagedGroup devicesManagedGroup; if (DeviceProfileDevicesManagedGroup.TryGetManagedGroup(m.DeviceProfile, out var devicesManagedGroup))
if (DeviceProfileDevicesManagedGroup.TryGetManagedGroup(m.DeviceProfile, out devicesManagedGroup))
m.DevicesLinkedGroup = devicesManagedGroup; m.DevicesLinkedGroup = devicesManagedGroup;
// Ensure Specified OU Exists // Ensure Specified OU Exists
@@ -61,11 +61,9 @@ namespace Disco.Web.Areas.Config.Controllers
m.TemplateExpressions = m.DocumentTemplate.ExtractPdfExpressions(Database); m.TemplateExpressions = m.DocumentTemplate.ExtractPdfExpressions(Database);
m.UpdateModel(Database); m.UpdateModel(Database);
DocumentTemplateDevicesManagedGroup devicesManagedGroup; if (DocumentTemplateDevicesManagedGroup.TryGetManagedGroup(m.DocumentTemplate, out var devicesManagedGroup))
if (DocumentTemplateDevicesManagedGroup.TryGetManagedGroup(m.DocumentTemplate, out devicesManagedGroup))
m.DevicesLinkedGroup = devicesManagedGroup; m.DevicesLinkedGroup = devicesManagedGroup;
DocumentTemplateUsersManagedGroup usersManagedGroup; if (DocumentTemplateUsersManagedGroup.TryGetManagedGroup(m.DocumentTemplate, out var usersManagedGroup))
if (DocumentTemplateUsersManagedGroup.TryGetManagedGroup(m.DocumentTemplate, out usersManagedGroup))
m.UsersLinkedGroup = usersManagedGroup; m.UsersLinkedGroup = usersManagedGroup;
m.BulkGenerateDownloadId = bulkGenerateId; m.BulkGenerateDownloadId = bulkGenerateId;
@@ -36,11 +36,9 @@ namespace Disco.Web.Areas.Config.Controllers
if (m == null) if (m == null)
throw new ArgumentException("Invalid User Flag Id"); throw new ArgumentException("Invalid User Flag Id");
UserFlagUsersManagedGroup assignedUsersManagedGroup; if (UserFlagUsersManagedGroup.TryGetManagedGroup(m.UserFlag, out var assignedUsersManagedGroup))
if (UserFlagUsersManagedGroup.TryGetManagedGroup(m.UserFlag, out assignedUsersManagedGroup))
m.UsersLinkedGroup = assignedUsersManagedGroup; m.UsersLinkedGroup = assignedUsersManagedGroup;
UserFlagUserDevicesManagedGroup assignedUserDevicesManagedGroup; if (UserFlagUserDevicesManagedGroup.TryGetManagedGroup(m.UserFlag, out var assignedUserDevicesManagedGroup))
if (UserFlagUserDevicesManagedGroup.TryGetManagedGroup(m.UserFlag, out assignedUserDevicesManagedGroup))
m.UserDevicesLinkedGroup = assignedUserDevicesManagedGroup; m.UserDevicesLinkedGroup = assignedUserDevicesManagedGroup;
if (Authorization.Has(Claims.Config.UserFlag.Configure)) if (Authorization.Has(Claims.Config.UserFlag.Configure))
@@ -37,8 +37,7 @@ namespace Disco.Web.Areas.Services.Controllers
// Ensure supported version // Ensure supported version
if (Request.UserAgent.StartsWith(@"Disco-Client/", StringComparison.OrdinalIgnoreCase)) if (Request.UserAgent.StartsWith(@"Disco-Client/", StringComparison.OrdinalIgnoreCase))
{ {
Version clientVersion; if (Version.TryParse(Request.UserAgent.Substring(13), out var clientVersion))
if (Version.TryParse(Request.UserAgent.Substring(13), out clientVersion))
{ {
if (clientVersion < new Version(2, 2)) if (clientVersion < new Version(2, 2))
{ {
@@ -110,8 +109,7 @@ namespace Disco.Web.Areas.Services.Controllers
// Ensure supported version // Ensure supported version
if (Request.UserAgent.StartsWith(@"Disco-Client/", StringComparison.OrdinalIgnoreCase)) if (Request.UserAgent.StartsWith(@"Disco-Client/", StringComparison.OrdinalIgnoreCase))
{ {
Version clientVersion; if (Version.TryParse(Request.UserAgent.Substring(13), out var clientVersion))
if (Version.TryParse(Request.UserAgent.Substring(13), out clientVersion))
{ {
if (clientVersion < new Version(2, 2)) if (clientVersion < new Version(2, 2))
{ {
+6 -12
View File
@@ -17,8 +17,7 @@ namespace Disco.Web.Controllers
public virtual ActionResult Query(string term, string limit = null, bool searchDetails = false, bool includeDecommissioned = false) public virtual ActionResult Query(string term, string limit = null, bool searchDetails = false, bool includeDecommissioned = false)
{ {
term = term.Trim(); term = term.Trim();
int termInt; if (!int.TryParse(term, out var termInt))
if (!int.TryParse(term, out termInt))
termInt = -1; termInt = -1;
var m = new Models.Search.QueryModel() { Term = term }; var m = new Models.Search.QueryModel() { Term = term };
@@ -77,8 +76,7 @@ namespace Disco.Web.Controllers
{ {
case "devicemodel": case "devicemodel":
Authorization.Require(Claims.Device.Search); Authorization.Require(Claims.Device.Search);
int deviceModelId; if (int.TryParse(term, out var deviceModelId))
if (int.TryParse(term, out deviceModelId))
{ {
var vm = Database.DeviceModels.Find(deviceModelId); var vm = Database.DeviceModels.Find(deviceModelId);
if (vm != null) if (vm != null)
@@ -94,8 +92,7 @@ namespace Disco.Web.Controllers
break; break;
case "deviceprofile": case "deviceprofile":
Authorization.Require(Claims.Device.Search); Authorization.Require(Claims.Device.Search);
int deviceProfileId; if (int.TryParse(term, out var deviceProfileId))
if (int.TryParse(term, out deviceProfileId))
{ {
var dp = Database.DeviceProfiles.Find(deviceProfileId); var dp = Database.DeviceProfiles.Find(deviceProfileId);
if (dp != null) if (dp != null)
@@ -111,8 +108,7 @@ namespace Disco.Web.Controllers
break; break;
case "devicebatch": case "devicebatch":
Authorization.Require(Claims.Device.Search); Authorization.Require(Claims.Device.Search);
int deviceBatchId; if (int.TryParse(term, out var deviceBatchId))
if (int.TryParse(term, out deviceBatchId))
{ {
var db = Database.DeviceBatches.Find(deviceBatchId); var db = Database.DeviceBatches.Find(deviceBatchId);
if (db != null) if (db != null)
@@ -233,8 +229,7 @@ namespace Disco.Web.Controllers
} }
case "userflag": case "userflag":
Authorization.RequireAll(Claims.User.Search, Claims.User.ShowFlagAssignments); Authorization.RequireAll(Claims.User.Search, Claims.User.ShowFlagAssignments);
int userFlagId; if (int.TryParse(term, out var userFlagId))
if (int.TryParse(term, out userFlagId))
{ {
var flag = Database.UserFlags.Find(userFlagId); var flag = Database.UserFlags.Find(userFlagId);
if (flag != null) if (flag != null)
@@ -250,8 +245,7 @@ namespace Disco.Web.Controllers
break; break;
case "deviceflag": case "deviceflag":
Authorization.RequireAll(Claims.Device.Search, Claims.Device.ShowFlagAssignments); Authorization.RequireAll(Claims.Device.Search, Claims.Device.ShowFlagAssignments);
int deviceFlagId; if (int.TryParse(term, out var deviceFlagId))
if (int.TryParse(term, out deviceFlagId))
{ {
var flag = Database.DeviceFlags.Find(deviceFlagId); var flag = Database.DeviceFlags.Find(deviceFlagId);
if (flag != null) if (flag != null)
+1 -2
View File
@@ -124,8 +124,7 @@ namespace Disco.Web
// Job Matches // Job Matches
markdown = htmlCommentJobRegex.Value.Replace(markdown, match => markdown = htmlCommentJobRegex.Value.Replace(markdown, match =>
{ {
int jobId; if (int.TryParse(match.Groups[2].Value, out var jobId))
if (int.TryParse(match.Groups[2].Value, out jobId))
return $"<a href=\"{urlHelper.Action(MVC.Job.Show(jobId))}\" title=\"Job {jobId}\">{match.Value}</a>"; return $"<a href=\"{urlHelper.Action(MVC.Job.Show(jobId))}\" title=\"Job {jobId}\">{match.Value}</a>";
else else
return match.Value; return match.Value;
@@ -23,12 +23,11 @@ namespace Disco.Web.Models.InitialConfig
{ {
var branches = FileStoreLocation.ToUpper().Split(Path.DirectorySeparatorChar); var branches = FileStoreLocation.ToUpper().Split(Path.DirectorySeparatorChar);
var branchesCase = FileStoreLocation.Split(Path.DirectorySeparatorChar); var branchesCase = FileStoreLocation.Split(Path.DirectorySeparatorChar);
FileStoreDirectoryModel branchModel;
FileStoreDirectoryModel branchParent = DirectoryModel; FileStoreDirectoryModel branchParent = DirectoryModel;
for (int i = 0; i < branches.Length; i++) for (int i = 0; i < branches.Length; i++)
{ {
var branch = branches[i]; var branch = branches[i];
if (branchParent.SubDirectories.TryGetValue(branch, out branchModel)) if (branchParent.SubDirectories.TryGetValue(branch, out var branchModel))
{ {
branchModel.ExpandSubDirectories(); branchModel.ExpandSubDirectories();
} }