qol: interpolated strings

This commit is contained in:
Gary Sharp
2025-07-20 11:56:34 +10:00
parent 4e518d6684
commit 7faebe56a8
108 changed files with 342 additions and 350 deletions
+1 -1
View File
@@ -397,7 +397,7 @@ namespace Disco.BI.Interop.Pdf
TechUserId = CreatorUser.UserId, TechUserId = CreatorUser.UserId,
Timestamp = DateTime.Now Timestamp = DateTime.Now
}; };
jl.Comments = string.Format("# Document Generated\r\n**{0}** [{1}]", dt.Description, dt.Id); jl.Comments = $"# Document Generated\r\n**{dt.Description}** [{dt.Id}]";
Database.JobLogs.Add(jl); Database.JobLogs.Add(jl);
} }
+2 -2
View File
@@ -26,7 +26,7 @@ namespace Disco.Client
} }
public static void UpdateStatus(string SubHeading, string Message, bool ShowProgress, int Progress) public static void UpdateStatus(string SubHeading, string Message, bool ShowProgress, int Progress)
{ {
Console.WriteLine("#{0},{1},{2},{3}", SubHeading.EscapeMessage(), Message.EscapeMessage(), ShowProgress.ToString(), Progress.ToString()); Console.WriteLine($"#{SubHeading.EscapeMessage()},{Message.EscapeMessage()},{ShowProgress.ToString()},{Progress.ToString()}");
} }
public static void TryDelay(int Milliseconds) public static void TryDelay(int Milliseconds)
{ {
@@ -90,7 +90,7 @@ namespace Disco.Client
public static void RegisterBootstrapperPostActions(ShutdownActions ShutdownAction, bool Uninstall) public static void RegisterBootstrapperPostActions(ShutdownActions ShutdownAction, bool Uninstall)
{ {
Console.WriteLine("!{0},{1}", Enum.GetName(typeof(ShutdownActions), ShutdownAction), Uninstall ? "UninstallBootstrapper" : "DontUninstallBootstrapper"); Console.WriteLine($"!{Enum.GetName(typeof(ShutdownActions), ShutdownAction)},{(Uninstall ? "UninstallBootstrapper" : "DontUninstallBootstrapper")}");
} }
public enum ShutdownActions public enum ShutdownActions
{ {
+3 -3
View File
@@ -217,11 +217,11 @@ namespace Disco.ClientBootstrapper
{ {
if (na.IsWireless) if (na.IsWireless)
{ {
info.AppendLine(string.Format("{0}: {1}", na.NetConnectionID, na.WirelessConnectionStatusMeaning(na.WirelessConnectionStatus))); info.AppendLine($"{na.NetConnectionID}: {na.WirelessConnectionStatusMeaning(na.WirelessConnectionStatus)}");
} }
else else
{ {
info.AppendLine(string.Format("{0}: {1}", na.NetConnectionID, na.ConnectionStatusMeaning(na.ConnectionStatus))); info.AppendLine($"{na.NetConnectionID}: {na.ConnectionStatusMeaning(na.ConnectionStatus)}");
} }
} }
statusUI.UpdateStatus(null, null, info.ToString()); statusUI.UpdateStatus(null, null, info.ToString());
@@ -232,7 +232,7 @@ namespace Disco.ClientBootstrapper
{ {
if (!string.IsNullOrWhiteSpace(e.Data)) if (!string.IsNullOrWhiteSpace(e.Data))
{ {
System.Diagnostics.Debug.WriteLine(string.Format("OUTPUT: {0}", e.Data)); System.Diagnostics.Debug.WriteLine($"OUTPUT: {e.Data}");
var data = e.Data.Substring(1).Split(new char[] { ',' }); var data = e.Data.Substring(1).Split(new char[] { ',' });
switch (e.Data[0]) switch (e.Data[0])
{ {
+1 -1
View File
@@ -14,7 +14,7 @@ namespace Disco.ClientBootstrapper
InitializeComponent(); InitializeComponent();
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
this.labelVersion.Text = string.Format("v{0}", version.ToString(3)); this.labelVersion.Text = $"v{version.ToString(3)}";
this.FormClosed += new FormClosedEventHandler(FormStatus_FormClosed); this.FormClosed += new FormClosedEventHandler(FormStatus_FormClosed);
@@ -41,7 +41,7 @@ namespace Disco.ClientBootstrapper.Interop
{ {
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber); _tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Root Certificate: {0}", cert.ShortSubjectName())); Program.Status.UpdateStatus(null, null, $"Added Root Certificate: {cert.ShortSubjectName()}");
Program.SleepThread(500, false); Program.SleepThread(500, false);
} }
} }
@@ -66,7 +66,7 @@ namespace Disco.ClientBootstrapper.Interop
{ {
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber); _tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Intermediate Certificate: {0}", cert.ShortSubjectName())); Program.Status.UpdateStatus(null, null, $"Added Intermediate Certificate: {cert.ShortSubjectName()}");
Program.SleepThread(500, false); Program.SleepThread(500, false);
} }
} }
@@ -91,7 +91,7 @@ namespace Disco.ClientBootstrapper.Interop
{ {
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber); _tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Host Certificate: {0}", cert.ShortSubjectName())); Program.Status.UpdateStatus(null, null, $"Added Host Certificate: {cert.ShortSubjectName()}");
Program.SleepThread(500, false); Program.SleepThread(500, false);
} }
} }
@@ -105,7 +105,7 @@ namespace Disco.ClientBootstrapper.Interop
{ {
using (var scriptsIniStreamWriter = new StreamWriter(scriptsIniStream, Encoding.Unicode)) using (var scriptsIniStreamWriter = new StreamWriter(scriptsIniStream, Encoding.Unicode))
{ {
scriptsIniStreamWriter.Write(string.Format("[Startup]{0}0CmdLine={1}{0}0Parameters=/AllowUninstall", Environment.NewLine, BootstrapperCmdLinePath)); scriptsIniStreamWriter.Write($"[Startup]{Environment.NewLine}0CmdLine={BootstrapperCmdLinePath}{Environment.NewLine}0Parameters=/AllowUninstall");
scriptsIniStreamWriter.Flush(); scriptsIniStreamWriter.Flush();
} }
} }
@@ -193,7 +193,7 @@ namespace Disco.ClientBootstrapper.Interop
if (InstallLocation.EndsWith(".wim", StringComparison.OrdinalIgnoreCase)) if (InstallLocation.EndsWith(".wim", StringComparison.OrdinalIgnoreCase))
{ {
// Offline File System (WIM) // Offline File System (WIM)
Program.Status.UpdateStatus("Installing Bootstrapper (Offline)", "Installing", string.Format("Install Location: {0}", InstallLocation)); Program.Status.UpdateStatus("Installing Bootstrapper (Offline)", "Installing", $"Install Location: {InstallLocation}");
Program.SleepThread(1000, false); Program.SleepThread(1000, false);
// Mount WIM // Mount WIM
@@ -204,7 +204,7 @@ namespace Disco.ClientBootstrapper.Interop
WimImageId = "1"; WimImageId = "1";
if (!int.TryParse(WimImageId, out wimImageIndex)) if (!int.TryParse(WimImageId, out wimImageIndex))
{ {
Program.Status.UpdateStatus(null, "Analysing WIM", string.Format("Looking for Image Name: {0}", WimImageId)); Program.Status.UpdateStatus(null, "Analysing WIM", $"Looking for Image Name: {WimImageId}");
Program.SleepThread(500, false); Program.SleepThread(500, false);
for (int i = 0; i < wim.ImageCount; i++) for (int i = 0; i < wim.ImageCount; i++)
{ {
@@ -215,7 +215,7 @@ namespace Disco.ClientBootstrapper.Interop
if (wimImageInfoName != null && wimImageInfoName.InnerText.Equals(WimImageId, StringComparison.OrdinalIgnoreCase)) if (wimImageInfoName != null && wimImageInfoName.InnerText.Equals(WimImageId, StringComparison.OrdinalIgnoreCase))
{ {
wimImageIndex = i + 1; wimImageIndex = i + 1;
Program.Status.UpdateStatus(null, "Analysing WIM", string.Format("Found Image Id '{0}' at Index {1}", WimImageId, wimImageIndex)); Program.Status.UpdateStatus(null, "Analysing WIM", $"Found Image Id '{WimImageId}' at Index {wimImageIndex}");
Program.SleepThread(500, false); Program.SleepThread(500, false);
break; break;
} }
@@ -224,7 +224,7 @@ namespace Disco.ClientBootstrapper.Interop
} }
if (wimImageIndex == 0) if (wimImageIndex == 0)
{ {
Program.Status.UpdateStatus(null, "Error", string.Format("Unable to load WIM Image Id: {0}", WimImageId)); Program.Status.UpdateStatus(null, "Error", $"Unable to load WIM Image Id: {WimImageId}");
Program.SleepThread(5000, false); Program.SleepThread(5000, false);
return; return;
} }
@@ -245,7 +245,7 @@ namespace Disco.ClientBootstrapper.Interop
try try
{ {
// Mount WIM // Mount WIM
Program.Status.UpdateStatus(null, "Mounting WIM", string.Format("Mounting WIM Image to '{0}'", wimMountPath)); Program.Status.UpdateStatus(null, "Mounting WIM", $"Mounting WIM Image to '{wimMountPath}'");
Program.SleepThread(500, false); Program.SleepThread(500, false);
m_MessageCallback = new WIMInterop.WindowsImageContainer.NativeMethods.MessageCallback(WimImageEventMessagePump); m_MessageCallback = new WIMInterop.WindowsImageContainer.NativeMethods.MessageCallback(WimImageEventMessagePump);
Interop.WIMInterop.WindowsImageContainer.NativeMethods.RegisterCallback(m_MessageCallback); Interop.WIMInterop.WindowsImageContainer.NativeMethods.RegisterCallback(m_MessageCallback);
@@ -254,7 +254,7 @@ namespace Disco.ClientBootstrapper.Interop
// Load Local Machine Registry // Load Local Machine Registry
var wimHivePath = Path.Combine(wimMountPath, "Windows\\System32\\config\\SOFTWARE"); var wimHivePath = Path.Combine(wimMountPath, "Windows\\System32\\config\\SOFTWARE");
Program.Status.UpdateStatus(null, "Mounting Offline Registry Hive", string.Format("Mounting Offline Registry Hive at '{0}'", wimHivePath)); Program.Status.UpdateStatus(null, "Mounting Offline Registry Hive", $"Mounting Offline Registry Hive at '{wimHivePath}'");
Program.SleepThread(500, false); Program.SleepThread(500, false);
using (var wimReg = new RegistryInterop(RegistryInterop.RegistryHives.HKEY_LOCAL_MACHINE, "DiscoClientBootstrapperWimHive", wimHivePath)) using (var wimReg = new RegistryInterop(RegistryInterop.RegistryHives.HKEY_LOCAL_MACHINE, "DiscoClientBootstrapperWimHive", wimHivePath))
{ {
@@ -268,7 +268,7 @@ namespace Disco.ClientBootstrapper.Interop
} }
// Unload Local Machine Registry // Unload Local Machine Registry
Program.Status.UpdateStatus(null, "Unmounting Offline Registry Hive", string.Format("Unmounting Offline Registry Hive at '{0}'", wimHivePath)); Program.Status.UpdateStatus(null, "Unmounting Offline Registry Hive", $"Unmounting Offline Registry Hive at '{wimHivePath}'");
Program.SleepThread(500, false); Program.SleepThread(500, false);
wimReg.Unload(); wimReg.Unload();
} }
@@ -281,7 +281,7 @@ namespace Disco.ClientBootstrapper.Interop
finally finally
{ {
// Unmount WIM // Unmount WIM
Program.Status.UpdateStatus(null, "Unmounting WIM", string.Format("Unmounting WIM Image at '{0}'", wimMountPath)); Program.Status.UpdateStatus(null, "Unmounting WIM", $"Unmounting WIM Image at '{wimMountPath}'");
Program.SleepThread(500, false); Program.SleepThread(500, false);
Interop.WIMInterop.WindowsImageContainer.NativeMethods.DismountImage(wimMountPath, InstallLocation, wimImageIndex, wimCommitChanges); Interop.WIMInterop.WindowsImageContainer.NativeMethods.DismountImage(wimMountPath, InstallLocation, wimImageIndex, wimCommitChanges);
@@ -300,7 +300,7 @@ namespace Disco.ClientBootstrapper.Interop
else else
{ {
// Online File System // Online File System
Program.Status.UpdateStatus("Installing Bootstrapper (Online)", "Installing", string.Format("Install Location: {0}", InstallLocation), true, -1); Program.Status.UpdateStatus("Installing Bootstrapper (Online)", "Installing", $"Install Location: {InstallLocation}", true, -1);
Program.SleepThread(1000, false); Program.SleepThread(1000, false);
string rootFileSystemLocation = Path.GetPathRoot(InstallLocation); string rootFileSystemLocation = Path.GetPathRoot(InstallLocation);
RegistryKey rootRegistryLocation = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); RegistryKey rootRegistryLocation = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
@@ -339,7 +339,7 @@ namespace Disco.ClientBootstrapper.Interop
timeRemainingMessage = "Calculating, please wait..."; timeRemainingMessage = "Calculating, please wait...";
var progress = eventArgs.WideParameter.ToInt32(); var progress = eventArgs.WideParameter.ToInt32();
Program.Status.UpdateStatus(null, null, string.Format("Time remaining: {0}", timeRemainingMessage), true, progress); Program.Status.UpdateStatus(null, null, $"Time remaining: {timeRemainingMessage}", true, progress);
break; break;
default: default:
@@ -211,12 +211,12 @@ namespace Disco.ClientBootstrapper.Interop
{ {
if (inlineWirelessProfile.AddProfile(wlanHandle, na.Guid)) if (inlineWirelessProfile.AddProfile(wlanHandle, na.Guid))
{ {
Program.Status.UpdateStatus(null, null, string.Format("Added Wireless Profile: {0}", inlineWirelessProfile.ProfileName)); Program.Status.UpdateStatus(null, null, $"Added Wireless Profile: {inlineWirelessProfile.ProfileName}");
Program.SleepThread(500, false); Program.SleepThread(500, false);
} }
else else
{ {
Program.Status.UpdateStatus(null, null, string.Format("Unable to add Wireless Profile: {0}", inlineWirelessProfile.ProfileName)); Program.Status.UpdateStatus(null, null, $"Unable to add Wireless Profile: {inlineWirelessProfile.ProfileName}");
Program.SleepThread(5000, false); Program.SleepThread(5000, false);
} }
} }
+5 -5
View File
@@ -86,15 +86,15 @@ namespace Disco.ClientBootstrapper
{ {
try try
{ {
string AppErrorPath = string.Format("{0}{1}", System.Reflection.Assembly.GetExecutingAssembly().Location, ".errors.txt"); string AppErrorPath = $"{System.Reflection.Assembly.GetExecutingAssembly().Location}.errors.txt";
System.Text.StringBuilder ErrorMessage = new System.Text.StringBuilder(); System.Text.StringBuilder ErrorMessage = new System.Text.StringBuilder();
ErrorMessage.AppendLine(); ErrorMessage.AppendLine();
ErrorMessage.AppendLine(DateTime.Now.ToLongDateString()); ErrorMessage.AppendLine(DateTime.Now.ToLongDateString());
ErrorMessage.AppendLine(DateTime.Now.ToLongTimeString()); ErrorMessage.AppendLine(DateTime.Now.ToLongTimeString());
ErrorMessage.AppendLine(string.Format("Type: {0}", ex.GetType().FullName)); ErrorMessage.AppendLine($"Type: {ex.GetType().FullName}");
ErrorMessage.AppendLine(string.Format("Message: {0}", ex.Message)); ErrorMessage.AppendLine($"Message: {ex.Message}");
ErrorMessage.AppendLine(string.Format("Source: {0}", ex.Source)); ErrorMessage.AppendLine($"Source: {ex.Source}");
ErrorMessage.AppendLine(string.Format("Stack: {0}", ex.StackTrace)); ErrorMessage.AppendLine($"Stack: {ex.StackTrace}");
System.IO.File.AppendAllText(AppErrorPath, ErrorMessage.ToString()); System.IO.File.AppendAllText(AppErrorPath, ErrorMessage.ToString());
} }
catch (Exception) { } catch (Exception) { }
+4 -4
View File
@@ -296,7 +296,7 @@ namespace Disco.Data.Repository
private static void UpdateDeviceModelDuplicates(this DiscoDataContext Database) private static void UpdateDeviceModelDuplicates(this DiscoDataContext Database)
{ {
var deviceModels = Database.DeviceModels.ToList(); var deviceModels = Database.DeviceModels.ToList();
var duplicateModels = deviceModels.GroupBy(g => string.Format("{0}|{1}", g.Manufacturer, g.Model)).Where(g => g.Count() > 1); var duplicateModels = deviceModels.GroupBy(g => $"{g.Manufacturer}|{g.Model}").Where(g => g.Count() > 1);
foreach (var duplicateModel in duplicateModels) foreach (var duplicateModel in duplicateModels)
{ {
var primaryModel = duplicateModel.OrderBy(dm => dm.Id).First(); var primaryModel = duplicateModel.OrderBy(dm => dm.Id).First();
@@ -310,9 +310,9 @@ namespace Disco.Data.Repository
if (!redundantModel.Description.EndsWith("** REDUNDANT **")) if (!redundantModel.Description.EndsWith("** REDUNDANT **"))
{ {
if (redundantModel.Description.Length > 484) if (redundantModel.Description.Length > 484)
redundantModel.Description = string.Format("{0} ** REDUNDANT **", redundantModel.Description.Substring(0, 484)); redundantModel.Description = $"{redundantModel.Description.Substring(0, 484)} ** REDUNDANT **";
else else
redundantModel.Description = string.Format("{0} ** REDUNDANT **", redundantModel.Description); redundantModel.Description = $"{redundantModel.Description} ** REDUNDANT **";
} }
} }
} }
@@ -425,7 +425,7 @@ DELETE [Users] WHERE [Id]=@IdExisting;";
var dataStoreLocation = Database.ConfigurationItems.Where(ci => ci.Scope == "System" && ci.Key == "DataStoreLocation").Select(ci => ci.Value).FirstOrDefault(); var dataStoreLocation = Database.ConfigurationItems.Where(ci => ci.Scope == "System" && ci.Key == "DataStoreLocation").Select(ci => ci.Value).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(dataStoreLocation) && System.IO.Directory.Exists(dataStoreLocation)) if (!string.IsNullOrWhiteSpace(dataStoreLocation) && System.IO.Directory.Exists(dataStoreLocation))
{ {
string filePrefix = string.Format("{0}_", netBiosName); string filePrefix = $"{netBiosName}_";
var userAttachmentsDirectory = System.IO.Path.Combine(dataStoreLocation, "UserAttachments"); var userAttachmentsDirectory = System.IO.Path.Combine(dataStoreLocation, "UserAttachments");
if (System.IO.Directory.Exists(userAttachmentsDirectory)) if (System.IO.Directory.Exists(userAttachmentsDirectory))
@@ -48,7 +48,7 @@ namespace Disco.Data.Repository
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
throw new SecurityException(string.Format("Unable to write to the Registry Location: HKML\\{0}[DatabaseConnectionString]", DiscoRegistryKey), ex); throw new SecurityException($"Unable to write to the Registry Location: HKML\\{DiscoRegistryKey}[DatabaseConnectionString]", ex);
} }
} }
} }
@@ -110,7 +110,7 @@ namespace Disco.Data.Repository.Monitor
eventType = RepositoryMonitorEventType.Unchanged; eventType = RepositoryMonitorEventType.Unchanged;
break; break;
default: default:
throw new NotSupportedException(string.Format("Database Entry State not supported: {0}", entryState.State.ToString())); throw new NotSupportedException($"Database Entry State not supported: {entryState.State.ToString()}");
} }
entityType = EntityTypeFromProxy(entryState.Entity.GetType()); entityType = EntityTypeFromProxy(entryState.Entity.GetType());
+1 -1
View File
@@ -73,7 +73,7 @@ namespace Disco.Models.Repository
public override string ToString() public override string ToString()
{ {
if (DeviceModel != null) if (DeviceModel != null)
return string.Format("{0} - {1}", DeviceModel, SerialNumber); return $"{DeviceModel} - {SerialNumber}";
else else
return SerialNumber; return SerialNumber;
} }
@@ -55,7 +55,7 @@ namespace Disco.Models.Repository
{ {
if (string.IsNullOrWhiteSpace(Name)) if (string.IsNullOrWhiteSpace(Name))
{ {
return string.Format("{0}: {1}", Id, PurchaseDate.ToLongDateString()); return $"{Id}: {PurchaseDate.ToLongDateString()}";
} }
return Name; return Name;
} }
@@ -52,7 +52,7 @@ namespace Disco.Models.Repository
{ {
return Name; return Name;
} }
return string.Format("{0} ({1})", Name, ShortName); return $"{Name} ({ShortName})";
} }
[StringLength(200)] [StringLength(200)]
@@ -38,7 +38,7 @@ namespace Disco.Models.Repository
public override string ToString() public override string ToString()
{ {
return string.Format("User Flag Id: {0}; User Id: {1}; Added: {2:s}", UserFlagId, UserId, AddedDate); return $"User Flag Id: {UserFlagId}; User Id: {UserId}; Added: {AddedDate:s}";
} }
} }
} }
@@ -16,7 +16,7 @@ namespace Disco.Models.Services.Searching
public string Id { get; set; } public string Id { get; set; }
public string Type { get { return type; } } public string Type { get { return type; } }
public string Description { get { return string.Format("{0} ({1})", Id, ComputerName); } } public string Description { get { return $"{Id} ({ComputerName})"; } }
public string[] ScoreValues { get { return LazyScoreValue.Value; } } public string[] ScoreValues { get { return LazyScoreValue.Value; } }
public string AssetNumber { get; set; } public string AssetNumber { get; set; }
@@ -27,7 +27,7 @@ namespace Disco.Models.Services.Searching
if (AssignedUserId != null) if (AssignedUserId != null)
{ {
if (AssignedUserDisplayName != null) if (AssignedUserDisplayName != null)
return string.Format("{0} ({1})", AssignedUserDisplayName, AssignedUserId); return $"{AssignedUserDisplayName} ({AssignedUserId})";
else else
return AssignedUserId; return AssignedUserId;
} }
@@ -14,7 +14,7 @@ namespace Disco.Models.Services.Searching
public virtual string Id { get; set; } public virtual string Id { get; set; }
public string Type { get { return type; } } public string Type { get { return type; } }
public string Description { get { return string.Format("{0} ({1}; {2})", Id, UserId, DeviceSerialNumber); } } public string Description { get { return $"{Id} ({UserId}; {DeviceSerialNumber})"; } }
public string[] ScoreValues { get { return LazyScoreValue.Value; } } public string[] ScoreValues { get { return LazyScoreValue.Value; } }
public string DeviceSerialNumber { get; set; } public string DeviceSerialNumber { get; set; }
@@ -17,7 +17,7 @@ namespace Disco.Models.Services.Searching
public string Id { get; set; } public string Id { get; set; }
public string FriendlyId { get; set; } public string FriendlyId { get; set; }
public string Type { get { return type; } } public string Type { get { return type; } }
public string Description { get { return string.Format("{0} ({1})", DisplayName, Id); } } public string Description { get { return $"{DisplayName} ({Id})"; } }
public string[] ScoreValues { get { return LazyScoreValue.Value; } } public string[] ScoreValues { get { return LazyScoreValue.Value; } }
public string DisplayName { get; set; } public string DisplayName { get; set; }
@@ -101,7 +101,7 @@ namespace Disco.Services.Plugins.ManifestGenerator
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{ {
Console.WriteLine("CurrentDomain_AssemblyResolve: {0} - {1}", args.Name, args.RequestingAssembly.FullName); Console.WriteLine($"CurrentDomain_AssemblyResolve: {args.Name} - {args.RequestingAssembly.FullName}");
foreach (var loadedAssembly in AppDomain.CurrentDomain.GetAssemblies()) foreach (var loadedAssembly in AppDomain.CurrentDomain.GetAssemblies())
{ {
@@ -114,7 +114,7 @@ namespace Disco.Services.Plugins.ManifestGenerator
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{ {
Console.WriteLine("CurrentDomain_AssemblyLoad: {0} - {1}", args.LoadedAssembly.FullName, args.LoadedAssembly.Location); Console.WriteLine($"CurrentDomain_AssemblyLoad: {args.LoadedAssembly.FullName} - {args.LoadedAssembly.Location}");
} }
static void BuildZipPackage(ZipArchive package, string relativePath, DirectoryInfo directory, List<string> excludedFiles) static void BuildZipPackage(ZipArchive package, string relativePath, DirectoryInfo directory, List<string> excludedFiles)
@@ -169,9 +169,9 @@ namespace Disco.Services.Authorization
filename = filename.Substring(filename.IndexOf("\\Disco\\Disco.") + 7); filename = filename.Substring(filename.IndexOf("\\Disco\\Disco.") + 7);
var method = frame.GetMethod(); var method = frame.GetMethod();
var resource = string.Format("{0}::{1}", method.DeclaringType.FullName, method.Name); var resource = $"{method.DeclaringType.FullName}::{method.Name}";
if (!string.IsNullOrEmpty(filename)) if (!string.IsNullOrEmpty(filename))
resource = string.Format("{0} [{1}]", resource, filename); resource = $"{resource} [{filename}]";
return resource; return resource;
} }
@@ -76,7 +76,7 @@ namespace Disco.Services.Authorization
public override string ToString() public override string ToString()
{ {
return string.Format("{0}: {1}={2}", Name, Key, Value); return $"{Name}: {Key}={Value}";
} }
} }
} }
@@ -65,10 +65,10 @@ namespace Disco.Services.Authorization
var controllerName = FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName; var controllerName = FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = FilterContext.ActionDescriptor.ActionName; var actionName = FilterContext.ActionDescriptor.ActionName;
authResource = string.Format("{0}::{1}", controllerName, actionName); authResource = $"{controllerName}::{actionName}";
} }
return string.Format("{0} [{1}]", authResource, url); return $"{authResource} [{url}]";
} }
} }
} }
@@ -156,7 +156,7 @@ namespace Disco.Services
if (j.CanDelete()) if (j.CanDelete())
j.OnDelete(Database); j.OnDelete(Database);
else else
throw new InvalidOperationException(string.Format("Deletion of Device is Denied (See Job# {0})", j.Id)); throw new InvalidOperationException($"Deletion of Device is Denied (See Job# {j.Id})");
} }
else else
{ {
@@ -169,8 +169,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = UserService.CurrentUser.UserId, TechUserId = UserService.CurrentUser.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Device Deleted\r\n\r\nSerial Number: **{0}**\r\nComputer Name: **{1}**\r\nModel: **{2}**\r\nProfile: **{3}**", Comments = $"# Device Deleted\r\n\r\nSerial Number: **{d.SerialNumber}**\r\nComputer Name: **{d.DeviceDomainId}**\r\nModel: **{d.DeviceModel}**\r\nProfile: **{d.DeviceProfile}**"
d.SerialNumber, d.DeviceDomainId, d.DeviceModel, d.DeviceProfile)
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
@@ -55,7 +55,7 @@ namespace Disco.Services
var deviceModelImagesDataStore = DataStore.CreateLocation(configCache, "DeviceModelImages"); var deviceModelImagesDataStore = DataStore.CreateLocation(configCache, "DeviceModelImages");
return Path.Combine(deviceModelImagesDataStore, string.Format("{0}.png", deviceModel.Id)); return Path.Combine(deviceModelImagesDataStore, $"{deviceModel.Id}.png");
} }
public static string ImageHash(this DeviceModel deviceModel) public static string ImageHash(this DeviceModel deviceModel)
+3 -3
View File
@@ -32,14 +32,14 @@ namespace Disco.Services
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new InvalidOperationException(string.Format("An error occurred rendering the computer name: [{0}] {1}", ex.GetType().Name, ex.Message), ex.InnerException); throw new InvalidOperationException($"An error occurred rendering the computer name: [{ex.GetType().Name}] {ex.Message}", ex.InnerException);
} }
if (rendered == null || rendered.Length > 24) if (rendered == null || rendered.Length > 24)
{ {
throw new InvalidOperationException("The rendered computer name would be invalid or longer than 24 characters"); throw new InvalidOperationException("The rendered computer name would be invalid or longer than 24 characters");
} }
return string.Format(@"{0}\{1}", Domain.NetBiosName, rendered); return $@"{Domain.NetBiosName}\{rendered}";
} }
public static List<DocumentTemplate> AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, DateTime TimeStamp) public static List<DocumentTemplate> AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, DateTime TimeStamp)
{ {
@@ -250,7 +250,7 @@ namespace Disco.Services
public static string Status(this Device Device) public static string Status(this Device Device)
{ {
if (Device.DecommissionedDate.HasValue) if (Device.DecommissionedDate.HasValue)
return string.Format("Decommissioned ({0})", Device.DecommissionReason.ReasonMessage()); return $"Decommissioned ({Device.DecommissionReason.ReasonMessage()})";
if (!Device.EnrolledDate.HasValue) if (!Device.EnrolledDate.HasValue)
return "Not Enrolled"; return "Not Enrolled";
@@ -32,7 +32,7 @@ namespace Disco.Services.Devices.DeviceFlags
if (flag == null) if (flag == null)
throw new Exception("Invalid Device Flag Id"); throw new Exception("Invalid Device Flag Id");
Status.UpdateStatus(0, string.Format("Bulk Assigning Devices to Device Flag: {0}", flag.Name), "Preparing to start"); Status.UpdateStatus(0, $"Bulk Assigning Devices to Device Flag: {flag.Name}", "Preparing to start");
// Load Technician // Load Technician
var technician = Database.Users.FirstOrDefault(user => user.UserId == technicianUserId); var technician = Database.Users.FirstOrDefault(user => user.UserId == technicianUserId);
@@ -48,7 +48,7 @@ namespace Disco.Services.Devices.DeviceFlags
var missingDevices = deviceSerialNumbers.Where(sn => !devices.Any(u => string.Equals(sn, u.SerialNumber, StringComparison.OrdinalIgnoreCase))).ToList(); var missingDevices = deviceSerialNumbers.Where(sn => !devices.Any(u => string.Equals(sn, u.SerialNumber, StringComparison.OrdinalIgnoreCase))).ToList();
if (missingDevices.Count > 0) if (missingDevices.Count > 0)
{ {
throw new InvalidOperationException(string.Format("Bulk assignment aborted, invalid Serial Numbers: {0}", string.Join(", ", missingDevices))); throw new InvalidOperationException($"Bulk assignment aborted, invalid Serial Numbers: {string.Join(", ", missingDevices)}");
} }
devices = devices.OrderBy(d => d.SerialNumber).ToList(); devices = devices.OrderBy(d => d.SerialNumber).ToList();
@@ -81,14 +81,14 @@ namespace Disco.Services.Devices.Enrolment
}; };
var results = logRetriever.Query(database); var results = logRetriever.Query(database);
Status.UpdateStatus(50, string.Format("Passing {0} logs", results.Count)); Status.UpdateStatus(50, $"Passing {results.Count} logs");
Dictionary<string, Tuple<string, string>> addresses = new Dictionary<string, Tuple<string, string>>(); Dictionary<string, Tuple<string, string>> addresses = new Dictionary<string, Tuple<string, string>>();
foreach (var result in results.OrderBy(r => r.Timestamp)) foreach (var result in results.OrderBy(r => r.Timestamp))
addresses[((string)result.Arguments[1]).ToLower()] = new Tuple<string, string>((string)result.Arguments[4], (string)result.Arguments[5]); addresses[((string)result.Arguments[1]).ToLower()] = new Tuple<string, string>((string)result.Arguments[4], (string)result.Arguments[5]);
Status.UpdateStatus(75, string.Format("Importing {0} details", addresses.Count)); Status.UpdateStatus(75, $"Importing {addresses.Count} details");
var devices = database.Devices.Include("DeviceDetails").ToList(); var devices = database.Devices.Include("DeviceDetails").ToList();
@@ -118,7 +118,7 @@ namespace Disco.Services.Devices.Importing
{ {
string deviceSerialNumber = DeviceSerialNumberImportField.ParseRawDeviceSerialNumber(dataReader.GetString(deviceSerialNumberIndex)); string deviceSerialNumber = DeviceSerialNumberImportField.ParseRawDeviceSerialNumber(dataReader.GetString(deviceSerialNumberIndex));
Status.UpdateStatus(((double)dataReader.Index / Context.RecordCount) * 100, string.Format("Parsing: {0}", deviceSerialNumber)); Status.UpdateStatus(((double)dataReader.Index / Context.RecordCount) * 100, $"Parsing: {deviceSerialNumber}");
Device existingDevice = null; Device existingDevice = null;
if (DeviceSerialNumberImportField.IsDeviceSerialNumberValid(deviceSerialNumber)) if (DeviceSerialNumberImportField.IsDeviceSerialNumberValid(deviceSerialNumber))
@@ -22,7 +22,7 @@ namespace Disco.Services.Documents.AttachmentImport
if (!File.Exists(Filename)) if (!File.Exists(Filename))
{ {
DocumentsLog.LogImportWarning(SessionId, string.Format("File not found: {0}", Filename)); DocumentsLog.LogImportWarning(SessionId, $"File not found: {Filename}");
throw new FileNotFoundException("Document Not Found", Filename); throw new FileNotFoundException("Document Not Found", Filename);
} }
@@ -135,7 +135,7 @@ namespace Disco.Services.Documents.AttachmentImport
foreach (var documentPage in unassignedPages) foreach (var documentPage in unassignedPages)
{ {
DocumentsLog.LogImportProgress(SessionId, (int)(90 + (unassignedPages.IndexOf(documentPage) * progressInterval)), string.Format("Processing Undetected Pages {0} of {1}", unassignedPages.IndexOf(documentPage) + 1, unassignedPages.Count)); DocumentsLog.LogImportProgress(SessionId, (int)(90 + (unassignedPages.IndexOf(documentPage) * progressInterval)), $"Processing Undetected Pages {unassignedPages.IndexOf(documentPage) + 1} of {unassignedPages.Count}");
using (var pdfSharpDocumentOutput = new PdfDocument()) using (var pdfSharpDocumentOutput = new PdfDocument())
{ {
@@ -52,7 +52,7 @@ namespace Disco.Services.Documents.AttachmentImport
if (retryCount < 18) if (retryCount < 18)
{ {
context.JobDetail.JobDataMap["RetryCount"] = ++retryCount; context.JobDetail.JobDataMap["RetryCount"] = ++retryCount;
DocumentsLog.LogImportWarning(sessionId, string.Format("{0}; Will try again in 10 Seconds", ex.Message)); DocumentsLog.LogImportWarning(sessionId, $"{ex.Message}; Will try again in 10 Seconds");
// Reschedule Job for 10 seconds // Reschedule Job for 10 seconds
var trig = new SimpleTriggerImpl(Guid.NewGuid().ToString(), new DateTimeOffset(DateTime.Now.AddSeconds(10))); var trig = new SimpleTriggerImpl(Guid.NewGuid().ToString(), new DateTimeOffset(DateTime.Now.AddSeconds(10)));
context.Scheduler.RescheduleJob(context.Trigger.Key, trig); context.Scheduler.RescheduleJob(context.Trigger.Key, trig);
@@ -59,7 +59,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var dc = Domain.FindDomainController(); var dc = Domain.FindDomainController();
string ldapPath = string.Format("LDAP://{0}/", dc.Name); string ldapPath = $"LDAP://{dc.Name}/";
using (var adRootDSE = new DirectoryEntry(ldapPath + "RootDSE")) using (var adRootDSE = new DirectoryEntry(ldapPath + "RootDSE"))
{ {
@@ -74,7 +74,7 @@ namespace Disco.Services.Interop.ActiveDirectory
using (var configSearchRoot = new DirectoryEntry(ldapPath + "CN=Partitions," + ConfigurationNamingContext)) using (var configSearchRoot = new DirectoryEntry(ldapPath + "CN=Partitions," + ConfigurationNamingContext))
{ {
var configSearchFilter = string.Format("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", Name); var configSearchFilter = $"(&(objectcategory=Crossref)(dnsRoot={Name})(netBIOSName=*))";
using (var configSearcher = new DirectorySearcher(configSearchRoot, configSearchFilter, new string[] { "NetBIOSName" }, System.DirectoryServices.SearchScope.OneLevel)) using (var configSearcher = new DirectorySearcher(configSearchRoot, configSearchFilter, new string[] { "NetBIOSName" }, System.DirectoryServices.SearchScope.OneLevel))
{ {
@@ -233,7 +233,7 @@ namespace Disco.Services.Interop.ActiveDirectory
throw new ArgumentNullException("DistinguishedName"); throw new ArgumentNullException("DistinguishedName");
if (!DistinguishedName.EndsWith(this.DistinguishedName, StringComparison.OrdinalIgnoreCase)) if (!DistinguishedName.EndsWith(this.DistinguishedName, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(string.Format("The Distinguished Name ({0}) isn't a member of this domain [{1}]", DistinguishedName, Name), "DistinguishedName"); throw new ArgumentException($"The Distinguished Name ({DistinguishedName}) isn't a member of this domain [{Name}]", "DistinguishedName");
var dc = GetAvailableDomainController(); var dc = GetAvailableDomainController();
@@ -309,12 +309,12 @@ namespace Disco.Services.Interop.ActiveDirectory
// Set offline for DomainControllerUnavailableMinutes // Set offline for DomainControllerUnavailableMinutes
domainController.IsAvailable = false; domainController.IsAvailable = false;
SystemLog.LogWarning(string.Format("A domain controller [{0}] is offline. It will be retried after {1}. Error: {2} [{3}]", domainController.Name, domainController.AvailableWhen.Value.ToShortTimeString(), ex.Message, ex.GetType().Name)); SystemLog.LogWarning($"A domain controller [{domainController.Name}] is offline. It will be retried after {domainController.AvailableWhen.Value.ToShortTimeString()}. Error: {ex.Message} [{ex.GetType().Name}]");
} }
} while (exceptionCount < SearchExceptionRetryMax); } while (exceptionCount < SearchExceptionRetryMax);
throw new AggregateException( throw new AggregateException(
new Exception[] { new Exception(string.Format("Unable to perform Active Directory Search after {0} attempts", exceptionCount)) } new Exception[] { new Exception($"Unable to perform Active Directory Search after {exceptionCount} attempts") }
.Concat(exceptions)); .Concat(exceptions));
} }
@@ -335,14 +335,14 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
get get
{ {
return string.Format("CN=Computers,{0}", DistinguishedName); return $"CN=Computers,{DistinguishedName}";
} }
} }
public string FriendlyDistinguishedNamePath(string DistinguishedName) public string FriendlyDistinguishedNamePath(string DistinguishedName)
{ {
if (!DistinguishedName.EndsWith(this.DistinguishedName, StringComparison.OrdinalIgnoreCase)) if (!DistinguishedName.EndsWith(this.DistinguishedName, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(string.Format("The Distinguished Name [{0}] doesn't exist within this domain [{1}]", DistinguishedName, this.DistinguishedName)); throw new ArgumentException($"The Distinguished Name [{DistinguishedName}] doesn't exist within this domain [{this.DistinguishedName}]");
StringBuilder name = new StringBuilder(); StringBuilder name = new StringBuilder();
@@ -365,7 +365,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public override string ToString() public override string ToString()
{ {
return string.Format("{0} [{1}]", Name, NetBiosName); return $"{Name} [{NetBiosName}]";
} }
public override bool Equals(object obj) public override bool Equals(object obj)
@@ -65,7 +65,7 @@ namespace Disco.Services.Interop.ActiveDirectory
throw new ArgumentNullException("DistinguishedName"); throw new ArgumentNullException("DistinguishedName");
if (!DistinguishedName.EndsWith(Domain.DistinguishedName, StringComparison.OrdinalIgnoreCase)) if (!DistinguishedName.EndsWith(Domain.DistinguishedName, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(string.Format("The Distinguished Name ({0}) isn't a member of this domain [{1}]", DistinguishedName, Domain.Name), "DistinguishedName"); throw new ArgumentException($"The Distinguished Name ({DistinguishedName}) isn't a member of this domain [{Domain.Name}]", "DistinguishedName");
var entry = new DirectoryEntry(string.Format(LdapPathTemplate, Name, ADHelpers.EscapeDistinguishedName(DistinguishedName))); var entry = new DirectoryEntry(string.Format(LdapPathTemplate, Name, ADHelpers.EscapeDistinguishedName(DistinguishedName)));
@@ -225,7 +225,7 @@ namespace Disco.Services.Interop.ActiveDirectory
if (SecurityIdentifier == null) if (SecurityIdentifier == null)
throw new ArgumentNullException("SecurityIdentifier"); throw new ArgumentNullException("SecurityIdentifier");
if (!SecurityIdentifier.IsEqualDomainSid(Domain.SecurityIdentifier)) if (!SecurityIdentifier.IsEqualDomainSid(Domain.SecurityIdentifier))
throw new ArgumentException(string.Format("The specified Security Identifier [{0}] does not belong to this domain [{1}]", SecurityIdentifier.ToString(), Domain.Name), "SecurityIdentifier"); throw new ArgumentException($"The specified Security Identifier [{SecurityIdentifier.ToString()}] does not belong to this domain [{Domain.Name}]", "SecurityIdentifier");
var sidBinaryString = SecurityIdentifier.ToBinaryString(); var sidBinaryString = SecurityIdentifier.ToBinaryString();
@@ -373,12 +373,12 @@ namespace Disco.Services.Interop.ActiveDirectory
using (var deOU = RetrieveDirectoryEntry(OrganisationalUnit, new string[] { "distinguishedName" })) using (var deOU = RetrieveDirectoryEntry(OrganisationalUnit, new string[] { "distinguishedName" }))
{ {
if (deOU == null) if (deOU == null)
throw new Exception(string.Format("OU's Directory Entry couldn't be found at [{0}]", OrganisationalUnit)); throw new Exception($"OU's Directory Entry couldn't be found at [{OrganisationalUnit}]");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new ArgumentException(string.Format("An error occurred while trying to locate the specified OU: {0}", OrganisationalUnit), "OrganisationalUnit", ex); throw new ArgumentException($"An error occurred while trying to locate the specified OU: {OrganisationalUnit}", "OrganisationalUnit", ex);
} }
} }
@@ -386,14 +386,8 @@ namespace Disco.Services.Interop.ActiveDirectory
MachineAccount.DeleteAccount(this); MachineAccount.DeleteAccount(this);
string tempFileName = System.IO.Path.GetTempFileName(); string tempFileName = System.IO.Path.GetTempFileName();
string argumentOU = (!string.IsNullOrWhiteSpace(OrganisationalUnit)) ? string.Format(" /MACHINEOU \"{0}\"", OrganisationalUnit) : string.Empty; string argumentOU = (!string.IsNullOrWhiteSpace(OrganisationalUnit)) ? $" /MACHINEOU \"{OrganisationalUnit}\"" : string.Empty;
string arguments = string.Format("/PROVISION /DOMAIN \"{0}\" /DCNAME \"{1}\" /MACHINE \"{2}\"{3} /REUSE /SAVEFILE \"{4}\"", string arguments = $"/PROVISION /DOMAIN \"{Domain.Name}\" /DCNAME \"{Name}\" /MACHINE \"{ComputerSamAccountName}\"{argumentOU} /REUSE /SAVEFILE \"{tempFileName}\"";
Domain.Name,
Name,
ComputerSamAccountName,
argumentOU,
tempFileName
);
ProcessStartInfo commandStarter = new ProcessStartInfo("DJOIN.EXE", arguments) ProcessStartInfo commandStarter = new ProcessStartInfo("DJOIN.EXE", arguments)
{ {
CreateNoWindow = true, CreateNoWindow = true,
@@ -403,7 +397,7 @@ namespace Disco.Services.Interop.ActiveDirectory
RedirectStandardError = true, RedirectStandardError = true,
UseShellExecute = false UseShellExecute = false
}; };
diagnosticInfo.AppendFormat("{0} {1}", "DJOIN.EXE", arguments); diagnosticInfo.AppendFormat($"DJOIN.EXE {arguments}");
diagnosticInfo.AppendLine(); diagnosticInfo.AppendLine();
string stdOutput; string stdOutput;
@@ -17,7 +17,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public string DistinguishedName { get; private set; } public string DistinguishedName { get; private set; }
public SecurityIdentifier SecurityIdentifier { get; private set; } public SecurityIdentifier SecurityIdentifier { get; private set; }
public string Id { get { return string.Format(@"{0}\{1}", Domain.NetBiosName, SamAccountName); } } public string Id { get { return $@"{Domain.NetBiosName}\{SamAccountName}"; } }
public string SamAccountName { get; private set; } public string SamAccountName { get; private set; }
public string Name { get; private set; } public string Name { get; private set; }
@@ -73,7 +73,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var dNSName = SearchResult.Value<string>("dNSHostName"); var dNSName = SearchResult.Value<string>("dNSHostName");
if (dNSName == null) if (dNSName == null)
dNSName = string.Format("{0}.{1}", sAMAccountName.TrimEnd('$'), SearchResult.Domain.Name); dNSName = $"{sAMAccountName.TrimEnd('$')}.{SearchResult.Domain.Name}";
var userAccountControl = (ADUserAccountControlFlags)SearchResult.Value<int>("userAccountControl"); var userAccountControl = (ADUserAccountControlFlags)SearchResult.Value<int>("userAccountControl");
var isCriticalSystemObject = SearchResult.Value<bool>("isCriticalSystemObject"); var isCriticalSystemObject = SearchResult.Value<bool>("isCriticalSystemObject");
@@ -123,7 +123,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var dNSName = properties.Value<string>("dNSHostName"); var dNSName = properties.Value<string>("dNSHostName");
if (dNSName == null) if (dNSName == null)
dNSName = string.Format("{0}.{1}", sAMAccountName.TrimEnd('$'), directoryEntry.Domain.Name); dNSName = $"{sAMAccountName.TrimEnd('$')}.{directoryEntry.Domain.Name}";
var userAccountControl = (ADUserAccountControlFlags)properties.Value<int>("userAccountControl"); var userAccountControl = (ADUserAccountControlFlags)properties.Value<int>("userAccountControl");
var isCriticalSystemObject = properties.Value<bool>("isCriticalSystemObject"); var isCriticalSystemObject = properties.Value<bool>("isCriticalSystemObject");
@@ -208,10 +208,10 @@ namespace Disco.Services.Interop.ActiveDirectory
public void DeleteAccount(ADDomainController WritableDomainController) public void DeleteAccount(ADDomainController WritableDomainController)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account [{DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (!WritableDomainController.IsWritable) if (!WritableDomainController.IsWritable)
throw new InvalidOperationException(string.Format("The domain controller [{0}] is not writable. This action (Delete Account) requires a writable domain controller.", Name)); throw new InvalidOperationException($"The domain controller [{Name}] is not writable. This action (Delete Account) requires a writable domain controller.");
using (ADDirectoryEntry entry = WritableDomainController.RetrieveDirectoryEntry(DistinguishedName)) using (ADDirectoryEntry entry = WritableDomainController.RetrieveDirectoryEntry(DistinguishedName))
{ {
@@ -226,7 +226,7 @@ namespace Disco.Services.Interop.ActiveDirectory
private void SetNetbootGUID(ADDomainController WritableDomainController, Guid updatedNetbootGUID) private void SetNetbootGUID(ADDomainController WritableDomainController, Guid updatedNetbootGUID)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (NetbootGUID != updatedNetbootGUID) if (NetbootGUID != updatedNetbootGUID)
{ {
@@ -247,7 +247,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void SetDescription(ADDomainController WritableDomainController, string Description) public void SetDescription(ADDomainController WritableDomainController, string Description)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (this.Description != Description) if (this.Description != Description)
{ {
@@ -320,7 +320,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void DisableAccount(ADDomainController WritableDomainController) public void DisableAccount(ADDomainController WritableDomainController)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (!IsDisabled) if (!IsDisabled)
{ {
@@ -348,7 +348,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void EnableAccount(ADDomainController WritableDomainController) public void EnableAccount(ADDomainController WritableDomainController)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (IsDisabled) if (IsDisabled)
{ {
@@ -376,7 +376,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public bool UpdateNetbootGUID(ADDomainController WritableDomainController, string UUID, string MACAddress) public bool UpdateNetbootGUID(ADDomainController WritableDomainController, string UUID, string MACAddress)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
Guid netbootGUID = Guid.Empty; Guid netbootGUID = Guid.Empty;
@@ -414,7 +414,7 @@ namespace Disco.Services.Interop.ActiveDirectory
Guid NetbootGUIDFromMACAddress; Guid NetbootGUIDFromMACAddress;
if (flag) if (flag)
{ {
Guid guid = new Guid(string.Format("00000000-0000-0000-0000-{0}", strippedMACAddress)); Guid guid = new Guid($"00000000-0000-0000-0000-{strippedMACAddress}");
NetbootGUIDFromMACAddress = guid; NetbootGUIDFromMACAddress = guid;
} }
else else
@@ -427,7 +427,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void MoveOrganisationalUnit(ADDomainController WritableDomainController, string NewOrganisationUnit) public void MoveOrganisationalUnit(ADDomainController WritableDomainController, string NewOrganisationUnit)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
var parentDistinguishedName = ParentDistinguishedName; var parentDistinguishedName = ParentDistinguishedName;
@@ -438,7 +438,7 @@ namespace Disco.Services.Interop.ActiveDirectory
NewOrganisationUnit = Domain.DefaultComputerContainer; NewOrganisationUnit = Domain.DefaultComputerContainer;
if (!NewOrganisationUnit.EndsWith(Domain.DistinguishedName, StringComparison.OrdinalIgnoreCase)) if (!NewOrganisationUnit.EndsWith(Domain.DistinguishedName, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(string.Format("Unable to move AD Account from one domain [{0}] to another [{1}].", DistinguishedName, NewOrganisationUnit)); throw new InvalidOperationException($"Unable to move AD Account from one domain [{DistinguishedName}] to another [{NewOrganisationUnit}].");
using (ADDirectoryEntry ou = WritableDomainController.RetrieveDirectoryEntry(NewOrganisationUnit)) using (ADDirectoryEntry ou = WritableDomainController.RetrieveDirectoryEntry(NewOrganisationUnit))
{ {
@@ -35,7 +35,7 @@ namespace Disco.Services.Interop.ActiveDirectory
changeCount = ActiveDirectory.Context.ManagedGroups.SyncManagedGroups(managedGroups, Status); changeCount = ActiveDirectory.Context.ManagedGroups.SyncManagedGroups(managedGroups, Status);
Status.LogInformation($"Synchronised Active Directory Managed Groups, {changeCount:N0} changes made"); Status.LogInformation($"Synchronised Active Directory Managed Groups, {changeCount:N0} changes made");
Status.SetFinishedMessage(string.Format("Made {0} Changes to Active Directory Groups", changeCount)); Status.SetFinishedMessage($"Made {changeCount} Changes to Active Directory Groups");
} }
public static ScheduledTaskStatus ScheduleSync(ADManagedGroup ManagedGroup) public static ScheduledTaskStatus ScheduleSync(ADManagedGroup ManagedGroup)
@@ -33,7 +33,7 @@ namespace Disco.Services.Interop.ActiveDirectory
UpdateLastNetworkLogonDates(database, Status); UpdateLastNetworkLogonDates(database, Status);
Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database"); Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database");
changeCount = database.SaveChanges(); changeCount = database.SaveChanges();
Status.Finished(string.Format("{0} Device last network logon dates updated", changeCount), "/Config/SystemConfig"); Status.Finished($"{changeCount} Device last network logon dates updated", "/Config/SystemConfig");
} }
Status.LogInformation($"Updated LastNetworkLogon Device Property for Device/s, {changeCount:N0} changes"); Status.LogInformation($"Updated LastNetworkLogon Device Property for Device/s, {changeCount:N0} changes");
@@ -144,7 +144,7 @@ namespace Disco.Services.Interop.ActiveDirectory
// Update Status // Update Status
double progress = 5 + (queryIndex * (90 / scopedQueries.Count)); double progress = 5 + (queryIndex * (90 / scopedQueries.Count));
status.UpdateStatus(progress, string.Format("Querying Domain [{0}] using controller [{1}]", domain.NetBiosName, domainController.Name), string.Format("Searching: {0}", searchRoot)); status.UpdateStatus(progress, $"Querying Domain [{domain.NetBiosName}] using controller [{domainController.Name}]", $"Searching: {searchRoot}");
// Perform Query // Perform Query
var directoryResults = domainController.SearchInternal(searchRoot, ldapFilter, ldapProperties, null); var directoryResults = domainController.SearchInternal(searchRoot, ldapFilter, ldapProperties, null);
@@ -163,7 +163,7 @@ namespace Disco.Services.Interop.ActiveDirectory
if (highedValue > 0) if (highedValue > 0)
{ {
var computerName = string.Format(@"{0}\{1}", domain.NetBiosName, samAccountName.TrimEnd('$')); var computerName = $@"{domain.NetBiosName}\{samAccountName.TrimEnd('$')}";
var lastLogon = new DateTime((DateTime.FromFileTime(highedValue).Ticks / 10000000L) * 10000000L); var lastLogon = new DateTime((DateTime.FromFileTime(highedValue).Ticks / 10000000L) * 10000000L);
return Tuple.Create(computerName, lastLogon); return Tuple.Create(computerName, lastLogon);
} }
@@ -19,7 +19,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public string DistinguishedName { get; private set; } public string DistinguishedName { get; private set; }
public SecurityIdentifier SecurityIdentifier { get; private set; } public SecurityIdentifier SecurityIdentifier { get; private set; }
public string Id { get { return string.Format(@"{0}\{1}", Domain.NetBiosName, SamAccountName); } } public string Id { get { return $@"{Domain.NetBiosName}\{SamAccountName}"; } }
public string SamAccountName { get; private set; } public string SamAccountName { get; private set; }
public string Name { get; private set; } public string Name { get; private set; }
@@ -250,10 +250,10 @@ namespace Disco.Services.Interop.ActiveDirectory
public void DeleteAccount(ADDomainController WritableDomainController) public void DeleteAccount(ADDomainController WritableDomainController)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account [{DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (!WritableDomainController.IsWritable) if (!WritableDomainController.IsWritable)
throw new InvalidOperationException(string.Format("The domain controller [{0}] is not writable. This action (Delete Account) requires a writable domain controller.", Name)); throw new InvalidOperationException($"The domain controller [{Name}] is not writable. This action (Delete Account) requires a writable domain controller.");
using (ADDirectoryEntry entry = WritableDomainController.RetrieveDirectoryEntry(DistinguishedName)) using (ADDirectoryEntry entry = WritableDomainController.RetrieveDirectoryEntry(DistinguishedName))
{ {
@@ -268,7 +268,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void DisableAccount(ADDomainController WritableDomainController) public void DisableAccount(ADDomainController WritableDomainController)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (!IsDisabled) if (!IsDisabled)
{ {
@@ -296,7 +296,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void EnableAccount(ADDomainController WritableDomainController) public void EnableAccount(ADDomainController WritableDomainController)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (IsDisabled) if (IsDisabled)
{ {
@@ -324,7 +324,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void SetDisplayName(ADDomainController WritableDomainController, string DisplayName) public void SetDisplayName(ADDomainController WritableDomainController, string DisplayName)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (this.DisplayName != DisplayName) if (this.DisplayName != DisplayName)
{ {
@@ -357,7 +357,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void SetSurname(ADDomainController WritableDomainController, string Surname) public void SetSurname(ADDomainController WritableDomainController, string Surname)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (this.Surname != Surname) if (this.Surname != Surname)
{ {
@@ -390,7 +390,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void SetGivenName(ADDomainController WritableDomainController, string GivenName) public void SetGivenName(ADDomainController WritableDomainController, string GivenName)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (this.GivenName != GivenName) if (this.GivenName != GivenName)
{ {
@@ -423,7 +423,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void SetEmail(ADDomainController WritableDomainController, string Email) public void SetEmail(ADDomainController WritableDomainController, string Email)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (this.Email != Email) if (this.Email != Email)
{ {
@@ -456,7 +456,7 @@ namespace Disco.Services.Interop.ActiveDirectory
public void SetPhone(ADDomainController WritableDomainController, string Phone) public void SetPhone(ADDomainController WritableDomainController, string Phone)
{ {
if (IsCriticalSystemObject) if (IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco ICT refuses to modify it", DistinguishedName)); throw new InvalidOperationException($"This account {DistinguishedName} is a Critical System Active Directory Object and Disco ICT refuses to modify it");
if (this.Phone != Phone) if (this.Phone != Phone)
{ {
@@ -139,7 +139,7 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
ADDomain domain; ADDomain domain;
if (!TryGetDomainFromDistinguishedName(DistinguishedName, out domain)) if (!TryGetDomainFromDistinguishedName(DistinguishedName, out domain))
throw new ArgumentException(string.Format("The distinguished name is from an unknown domain: [{0}]", DistinguishedName), "DistinguishedName"); throw new ArgumentException($"The distinguished name is from an unknown domain: [{DistinguishedName}]", "DistinguishedName");
return domain; return domain;
} }
@@ -152,7 +152,7 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
ADDomain domain; ADDomain domain;
if (!TryGetDomainByNetBiosName(NetBiosName, out domain)) if (!TryGetDomainByNetBiosName(NetBiosName, out domain))
throw new ArgumentException(string.Format("The domain for specified NetBios name is unknown [{0}]", NetBiosName), "NetBiosName"); throw new ArgumentException($"The domain for specified NetBios name is unknown [{NetBiosName}]", "NetBiosName");
return domain; return domain;
} }
@@ -165,7 +165,7 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
ADDomain domain; ADDomain domain;
if (!TryGetDomainByName(Name, out domain)) if (!TryGetDomainByName(Name, out domain))
throw new ArgumentException(string.Format("The domain for specified DNS name is unknown [{0}]", Name), "Name"); throw new ArgumentException($"The domain for specified DNS name is unknown [{Name}]", "Name");
return domain; return domain;
} }
@@ -178,7 +178,7 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
ADDomain domain; ADDomain domain;
if (!TryGetDomainFromSecurityIdentifier(SecurityIdentifier, out domain)) if (!TryGetDomainFromSecurityIdentifier(SecurityIdentifier, out domain))
throw new ArgumentException(string.Format("The domain for specified Security Identifier is unknown [{0}]", SecurityIdentifier.ToString()), "SecurityIdentifier"); throw new ArgumentException($"The domain for specified Security Identifier is unknown [{SecurityIdentifier.ToString()}]", "SecurityIdentifier");
return domain; return domain;
} }
@@ -190,7 +190,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var slashIndex = Id.IndexOf('\\'); var slashIndex = Id.IndexOf('\\');
if (slashIndex < 0) if (slashIndex < 0)
throw new ArgumentException(string.Format("The Id must include the Domain [{0}]", Id), "Id"); throw new ArgumentException($"The Id must include the Domain [{Id}]", "Id");
return TryGetDomainByNetBiosName(Id.Substring(0, slashIndex), out Domain); return TryGetDomainByNetBiosName(Id.Substring(0, slashIndex), out Domain);
} }
@@ -202,7 +202,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var slashIndex = Id.IndexOf('\\'); var slashIndex = Id.IndexOf('\\');
if (slashIndex < 0) if (slashIndex < 0)
throw new ArgumentException(string.Format("The Id must include the Domain [{0}]", Id), "Id"); throw new ArgumentException($"The Id must include the Domain [{Id}]", "Id");
return GetDomainByNetBiosName(Id.Substring(0, slashIndex)); return GetDomainByNetBiosName(Id.Substring(0, slashIndex));
} }
@@ -41,7 +41,7 @@ namespace Disco.Services.Interop.ActiveDirectory
.FirstOrDefault(g => g.Configuration.GroupId.Equals(ManagedGroup.Configuration.GroupId, StringComparison.OrdinalIgnoreCase)); .FirstOrDefault(g => g.Configuration.GroupId.Equals(ManagedGroup.Configuration.GroupId, StringComparison.OrdinalIgnoreCase));
if (existingGroup != null) if (existingGroup != null)
throw new ArgumentException(string.Format("[{0}] cannot manage this group [{1}] because is already managed by [{2}]", ManagedGroup.Key, ManagedGroup.Configuration.GroupId, existingGroup.Key), "ManagedGroup"); throw new ArgumentException($"[{ManagedGroup.Key}] cannot manage this group [{ManagedGroup.Configuration.GroupId}] because is already managed by [{existingGroup.Key}]", "ManagedGroup");
managedGroups.AddOrUpdate(key, ManagedGroup, (itemKey, item) => managedGroups.AddOrUpdate(key, ManagedGroup, (itemKey, item) =>
{ {
@@ -93,9 +93,9 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
var group = ActiveDirectory.RetrieveADGroup(GroupId, "isCriticalSystemObject"); var group = ActiveDirectory.RetrieveADGroup(GroupId, "isCriticalSystemObject");
if (group == null) if (group == null)
throw new ArgumentException(string.Format("The group [{0}] wasn't found", GroupId), "DevicesLinkedGroup"); throw new ArgumentException($"The group [{GroupId}] wasn't found", "DevicesLinkedGroup");
if (group.GetPropertyValue<bool>("isCriticalSystemObject")) if (group.GetPropertyValue<bool>("isCriticalSystemObject"))
throw new ArgumentException(string.Format("The group [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", group.DistinguishedName), "DevicesLinkedGroup"); throw new ArgumentException($"The group [{group.DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", "DevicesLinkedGroup");
GroupId = group.Id; GroupId = group.Id;
@@ -103,7 +103,7 @@ namespace Disco.Services.Interop.ActiveDirectory
.Where(g => g.Key != IgnoreManagedGroupKey) .Where(g => g.Key != IgnoreManagedGroupKey)
.FirstOrDefault(g => g.Configuration.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase)); .FirstOrDefault(g => g.Configuration.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase));
if (otherManagedGroup != null) if (otherManagedGroup != null)
throw new ArgumentException(string.Format("Cannot manage this group [{0}] because is already managed by [{1}]", GroupId, otherManagedGroup.Key), "DevicesLinkedGroup"); throw new ArgumentException($"Cannot manage this group [{GroupId}] because is already managed by [{otherManagedGroup.Key}]", "DevicesLinkedGroup");
return GroupId; return GroupId;
} }
@@ -160,7 +160,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var scopeAccounts = ActiveDirectory.Context.SearchScope("(|(objectCategory=computer)(objectCategory=person))", adSearchLoadProperties); var scopeAccounts = ActiveDirectory.Context.SearchScope("(|(objectCategory=computer)(objectCategory=person))", adSearchLoadProperties);
foreach (var scopeAccount in scopeAccounts) foreach (var scopeAccount in scopeAccounts)
{ {
var id = string.Format(@"{0}\{1}", scopeAccount.Domain.NetBiosName, scopeAccount.Value<string>("sAMAccountName")); var id = $@"{scopeAccount.Domain.NetBiosName}\{scopeAccount.Value<string>("sAMAccountName")}";
accountDNCache[id] = scopeAccount.Value<string>("distinguishedName"); accountDNCache[id] = scopeAccount.Value<string>("distinguishedName");
} }
} }
@@ -182,7 +182,7 @@ namespace Disco.Services.Interop.ActiveDirectory
return null; return null;
} }
var ldapFilter = string.Format("(&(|(objectCategory=computer)(objectCategory=person))(sAMAccountName={0}))", memberUsername); var ldapFilter = $"(&(|(objectCategory=computer)(objectCategory=person))(sAMAccountName={memberUsername}))";
var adSearchResult = memberDomain.SearchEntireDomain(ldapFilter, adSearchLoadProperties, ActiveDirectory.SingleSearchResult).FirstOrDefault(); var adSearchResult = memberDomain.SearchEntireDomain(ldapFilter, adSearchLoadProperties, ActiveDirectory.SingleSearchResult).FirstOrDefault();
if (adSearchResult != null) if (adSearchResult != null)
@@ -234,7 +234,7 @@ namespace Disco.Services.Interop.ActiveDirectory
using (var adGroupEntry = ActiveDirectory.Context.RetrieveDirectoryEntry(adGroup.DistinguishedName, new string[] { "member", "isCriticalSystemObject" })) using (var adGroupEntry = ActiveDirectory.Context.RetrieveDirectoryEntry(adGroup.DistinguishedName, new string[] { "member", "isCriticalSystemObject" }))
{ {
if (adGroupEntry.Entry.Properties.Value<bool>("isCriticalSystemObject")) if (adGroupEntry.Entry.Properties.Value<bool>("isCriticalSystemObject"))
throw new InvalidOperationException(string.Format("This group [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", adGroup.DistinguishedName)); throw new InvalidOperationException($"This group [{adGroup.DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it");
var adGroupEntryMembers = adGroupEntry.Entry.Properties["member"]; var adGroupEntryMembers = adGroupEntry.Entry.Properties["member"];
foreach (var item in actionItems) foreach (var item in actionItems)
@@ -291,7 +291,7 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
Status.UpdateStatus( Status.UpdateStatus(
((double)30 / managedGroups.Count) * index, // 0 -> 30 ((double)30 / managedGroups.Count) * index, // 0 -> 30
string.Format("Determining Group Members: {0} [{1}]", g.GroupDescription, g.Configuration.GroupId)); $"Determining Group Members: {g.GroupDescription} [{g.Configuration.GroupId}]");
return Tuple.Create( return Tuple.Create(
g, g,
g.DetermineMembers(Database).Select(m => g.DetermineMembers(Database).Select(m =>
@@ -316,7 +316,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var scopeAccounts = ActiveDirectory.Context.SearchScope("(|(objectCategory=computer)(objectCategory=person))", adSearchLoadProperties); var scopeAccounts = ActiveDirectory.Context.SearchScope("(|(objectCategory=computer)(objectCategory=person))", adSearchLoadProperties);
foreach (var scopeAccount in scopeAccounts) foreach (var scopeAccount in scopeAccounts)
{ {
var id = string.Format(@"{0}\{1}", scopeAccount.Domain.NetBiosName, scopeAccount.Value<string>("sAMAccountName")); var id = $@"{scopeAccount.Domain.NetBiosName}\{scopeAccount.Value<string>("sAMAccountName")}";
accountDNCache[id] = Tuple.Create(scopeAccount.Value<string>("distinguishedName"), scopeAccount.Value<string>("displayName") ?? scopeAccount.Value<string>("name")); accountDNCache[id] = Tuple.Create(scopeAccount.Value<string>("distinguishedName"), scopeAccount.Value<string>("displayName") ?? scopeAccount.Value<string>("name"));
} }
} }
@@ -325,7 +325,7 @@ namespace Disco.Services.Interop.ActiveDirectory
{ {
Status.UpdateStatus( Status.UpdateStatus(
30 + (((double)30 / actionGroups.Count) * index), // 30 -> 60 30 + (((double)30 / actionGroups.Count) * index), // 30 -> 60
string.Format("Resolving {0} Group Members: {1} [{2}]", g.Item2.Count, g.Item1.GroupDescription, g.Item1.Configuration.GroupId)); $"Resolving {g.Item2.Count} Group Members: {g.Item1.GroupDescription} [{g.Item1.Configuration.GroupId}]");
// Resolve Member Ids to AD Distinguished Names // Resolve Member Ids to AD Distinguished Names
// Discard non-existent users // Discard non-existent users
@@ -344,7 +344,7 @@ namespace Disco.Services.Interop.ActiveDirectory
return null; return null;
} }
var ldapFilter = string.Format("(&(|(objectCategory=computer)(objectCategory=person))(sAMAccountName={0}))", memberUsername); var ldapFilter = $"(&(|(objectCategory=computer)(objectCategory=person))(sAMAccountName={memberUsername}))";
var adSearchResult = memberDomain.SearchEntireDomain(ldapFilter, adSearchLoadProperties, ActiveDirectory.SingleSearchResult).FirstOrDefault(); var adSearchResult = memberDomain.SearchEntireDomain(ldapFilter, adSearchLoadProperties, ActiveDirectory.SingleSearchResult).FirstOrDefault();
if (adSearchResult != null) if (adSearchResult != null)
@@ -379,15 +379,15 @@ namespace Disco.Services.Interop.ActiveDirectory
Status.UpdateStatus( Status.UpdateStatus(
60 + (((double)40 / actionGroups.Count) * actionGroups.IndexOf(actionGroup)), // 60 -> 100 60 + (((double)40 / actionGroups.Count) * actionGroups.IndexOf(actionGroup)), // 60 -> 100
string.Format("Synchronizing {0} Group Members: {1} [{2}]", actionGroup.Item2.Count, actionGroup.Item1.GroupDescription, actionGroup.Item1.Configuration.GroupId)); $"Synchronizing {actionGroup.Item2.Count} Group Members: {actionGroup.Item1.GroupDescription} [{actionGroup.Item1.Configuration.GroupId}]");
using (var adGroupEntry = ActiveDirectory.Context.RetrieveDirectoryEntry(adGroup.DistinguishedName, new string[] { "isCriticalSystemObject", "description", "member" })) using (var adGroupEntry = ActiveDirectory.Context.RetrieveDirectoryEntry(adGroup.DistinguishedName, new string[] { "isCriticalSystemObject", "description", "member" }))
{ {
if (adGroupEntry.Entry.Properties.Value<bool>("isCriticalSystemObject")) if (adGroupEntry.Entry.Properties.Value<bool>("isCriticalSystemObject"))
throw new InvalidOperationException(string.Format("This group [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", adGroup.DistinguishedName)); throw new InvalidOperationException($"This group [{adGroup.DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it");
// Update Description // Update Description
var groupDescription = string.Format("Disco ICT: {0}", actionGroup.Item1.GroupDescription); var groupDescription = $"Disco ICT: {actionGroup.Item1.GroupDescription}";
if (adGroupEntry.Entry.Properties.Value<string>("description") != groupDescription) if (adGroupEntry.Entry.Properties.Value<string>("description") != groupDescription)
{ {
var adGroupEntryDescription = adGroupEntry.Entry.Properties["description"]; var adGroupEntryDescription = adGroupEntry.Entry.Properties["description"];
+6 -6
View File
@@ -51,15 +51,15 @@ namespace Disco.Services.Interop.DiscoServices
.ToList() .ToList()
.ForEach(a => .ForEach(a =>
{ {
formData.Add(new StringContent(a.Attachment.Filename), string.Format("Attachments[{0}].Filename", a.Index)); formData.Add(new StringContent(a.Attachment.Filename), $"Attachments[{a.Index}].Filename");
formData.Add(new StringContent(a.Attachment.MimeType), string.Format("Attachments[{0}].MimeType", a.Index)); formData.Add(new StringContent(a.Attachment.MimeType), $"Attachments[{a.Index}].MimeType");
formData.Add(new StringContent(a.Attachment.Timestamp.ToISO8601()), string.Format("Attachments[{0}].CreatedDate", a.Index)); formData.Add(new StringContent(a.Attachment.Timestamp.ToISO8601()), $"Attachments[{a.Index}].CreatedDate");
if (a.Attachment.DocumentTemplateId != null) if (a.Attachment.DocumentTemplateId != null)
formData.Add(new StringContent(a.Attachment.DocumentTemplateId), string.Format("Attachments[{0}].DocumentTemplateId", a.Index)); formData.Add(new StringContent(a.Attachment.DocumentTemplateId), $"Attachments[{a.Index}].DocumentTemplateId");
if (a.Attachment.Comments != null) if (a.Attachment.Comments != null)
formData.Add(new StringContent(a.Attachment.Comments), string.Format("Attachments[{0}].Comments", a.Index)); formData.Add(new StringContent(a.Attachment.Comments), $"Attachments[{a.Index}].Comments");
formData.Add(new ByteArrayContent(File.ReadAllBytes(a.Filename)), string.Format("Attachments[{0}].File", a.Index), a.Attachment.Filename); formData.Add(new ByteArrayContent(File.ReadAllBytes(a.Filename)), $"Attachments[{a.Index}].File", a.Attachment.Filename);
}); });
} }
@@ -63,10 +63,10 @@ namespace Disco.Services.Interop.DiscoServices
return new PluginIncompatibility() { PluginId = r.PluginId, Version = rVersion, Reason = "This plugin release is blocked by Disco ICT Online Services" }; return new PluginIncompatibility() { PluginId = r.PluginId, Version = rVersion, Reason = "This plugin release is blocked by Disco ICT Online Services" };
if (r.HostMinVersion != null && hostVersion < Version.Parse(r.HostMinVersion)) if (r.HostMinVersion != null && hostVersion < Version.Parse(r.HostMinVersion))
return new PluginIncompatibility() { PluginId = r.PluginId, Version = rVersion, Reason = string.Format("This plugin requires v{0} or newer", r.HostMinVersion) }; return new PluginIncompatibility() { PluginId = r.PluginId, Version = rVersion, Reason = $"This plugin requires v{r.HostMinVersion} or newer" };
if (r.HostMaxVersion != null && hostVersion > Version.Parse(r.HostMaxVersion)) if (r.HostMaxVersion != null && hostVersion > Version.Parse(r.HostMaxVersion))
return new PluginIncompatibility() { PluginId = r.PluginId, Version = rVersion, Reason = string.Format("This plugin requires v{0} or older", r.HostMaxVersion) }; return new PluginIncompatibility() { PluginId = r.PluginId, Version = rVersion, Reason = $"This plugin requires v{r.HostMaxVersion} or older" };
return null; return null;
}).Where(i => i != null).ToList() }).Where(i => i != null).ToList()
@@ -39,7 +39,7 @@ namespace Disco.Services.Interop.DiscoServices
public static string FormatVersion(Version Version) public static string FormatVersion(Version Version)
{ {
return string.Format("{0}.{1}.{2:0000}.{3:0000}", Version.Major, Version.Minor, Version.Build, Version.Revision); return $"{Version.Major}.{Version.Minor}.{Version.Build:0000}.{Version.Revision:0000}";
} }
public static string HashDeploymentData(DiscoDataContext Database, string Data) public static string HashDeploymentData(DiscoDataContext Database, string Data)
@@ -79,7 +79,7 @@ namespace Disco.Services.Interop.DiscoServices
request.ContentType = "application/json; charset=utf-8; encoding=gzip"; request.ContentType = "application/json; charset=utf-8; encoding=gzip";
request.Method = WebRequestMethods.Http.Post; request.Method = WebRequestMethods.Http.Post;
request.UserAgent = string.Format("Disco/{0} (Update)", discoVersion); request.UserAgent = $"Disco/{discoVersion} (Update)";
using (var requestStream = request.GetRequestStream()) using (var requestStream = request.GetRequestStream())
{ {
@@ -117,13 +117,13 @@ namespace Disco.Services.Interop.DiscoServices
Database.DiscoConfiguration.UpdateLastCheckResponse = updateResult; Database.DiscoConfiguration.UpdateLastCheckResponse = updateResult;
Database.SaveChanges(); Database.SaveChanges();
Status.SetFinishedMessage(string.Format("The update server reported Version {0} is the latest.", updateResult.LatestVersion)); Status.SetFinishedMessage($"The update server reported Version {updateResult.LatestVersion} is the latest.");
return updateResult; return updateResult;
} }
else else
{ {
Status.SetTaskException(new WebException(string.Format("Server responded with: [{0}] {1}", response.StatusCode, response.StatusDescription))); Status.SetTaskException(new WebException($"Server responded with: [{response.StatusCode}] {response.StatusDescription}"));
return null; return null;
} }
} }
@@ -216,7 +216,7 @@ namespace Disco.Services.Interop.DiscoServices
DeviceIdentifier = HashDeploymentData(Database, j.DeviceSerialNumber), DeviceIdentifier = HashDeploymentData(Database, j.DeviceSerialNumber),
UserIdentifier = HashDeploymentData(Database, j.UserId), UserIdentifier = HashDeploymentData(Database, j.UserId),
TechnicianIdentifier = HashDeploymentData(Database, j.JobTechnicianId), TechnicianIdentifier = HashDeploymentData(Database, j.JobTechnicianId),
DeviceModel = string.Format("{0};{1}", j.DeviceModelManufacturer, j.DeviceModelModel), DeviceModel = $"{j.DeviceModelManufacturer};{j.DeviceModelModel}",
Repairer = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairer : j.Repairer, Repairer = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairer : j.Repairer,
RepairerLogged = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairerLoggedDate : j.RepairerLoggedDate, RepairerLogged = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairerLoggedDate : j.RepairerLoggedDate,
RepairerCompleted = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairerCompletedDate : j.RepairerCompletedDate RepairerCompleted = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairerCompletedDate : j.RepairerCompletedDate
@@ -59,7 +59,7 @@ namespace Disco.Services.Interop.VicEduDept
wReq.Proxy = new WebProxy(); // Empty Proxy Config wReq.Proxy = new WebProxy(); // Empty Proxy Config
wReq.Method = WebRequestMethods.Http.Post; wReq.Method = WebRequestMethods.Http.Post;
wReq.ContentType = "application/x-www-form-urlencoded"; wReq.ContentType = "application/x-www-form-urlencoded";
wReq.UserAgent = string.Format("Disco/{0}", DiscoBIVersion); wReq.UserAgent = $"Disco/{DiscoBIVersion}";
using (var wrStream = wReq.GetRequestStream()) using (var wrStream = wReq.GetRequestStream())
{ {
using (var wrStreamWriter = new StreamWriter(wrStream)) using (var wrStreamWriter = new StreamWriter(wrStream))
+7 -7
View File
@@ -135,7 +135,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = Technician.UserId, TechUserId = Technician.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Waiting on User Action\r\n{0}", string.IsNullOrWhiteSpace(Reason) ? "<no reason provided>" : Reason) Comments = $"# Waiting on User Action\r\n{(string.IsNullOrWhiteSpace(Reason) ? "<no reason provided>" : Reason)}"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
@@ -162,7 +162,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = Technician.UserId, TechUserId = Technician.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# User Action Resolved\r\n{0}", string.IsNullOrWhiteSpace(Resolution) ? "<no comment provided>" : Resolution) Comments = $"# User Action Resolved\r\n{(string.IsNullOrWhiteSpace(Resolution) ? "<no comment provided>" : Resolution)}"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
@@ -238,7 +238,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = TechUser.UserId, TechUserId = TechUser.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Warranty Claim Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", warrantyProvider.Manifest.Name, Address.Name, providerRef, FaultDescription) Comments = $"# Warranty Claim Submitted\r\nProvider: **{warrantyProvider.Manifest.Name}**\r\nAddress: **{Address.Name}**\r\nReference: **{providerRef}**\r\n___\r\n```{FaultDescription}```"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
@@ -271,7 +271,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = TechUser.UserId, TechUserId = TechUser.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Manual Warranty Claim Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", ManualProviderName, Address.Name, ManualProviderReference ?? "<none>", FaultDescription) Comments = $"# Manual Warranty Claim Submitted\r\nProvider: **{ManualProviderName}**\r\nAddress: **{Address.Name}**\r\nReference: **{ManualProviderReference ?? "<none>"}**\r\n___\r\n```{FaultDescription}```"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
@@ -350,7 +350,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = techUser.UserId, TechUserId = techUser.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Job Type Converted\r\nFrom: **{0}**\r\nTo: **{1}**", Database.JobTypes.Find(JobType.JobTypeIds.HWar), Database.JobTypes.Find(JobType.JobTypeIds.HNWar)) Comments = $"# Job Type Converted\r\nFrom: **{Database.JobTypes.Find(JobType.JobTypeIds.HWar)}**\r\nTo: **{Database.JobTypes.Find(JobType.JobTypeIds.HNWar)}**"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
@@ -468,7 +468,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = TechUser.UserId, TechUserId = TechUser.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Repair Request Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", repairProvider.Manifest.Name, Address.Name, providerRef, RepairDescription) Comments = $"# Repair Request Submitted\r\nProvider: **{repairProvider.Manifest.Name}**\r\nAddress: **{Address.Name}**\r\nReference: **{providerRef}**\r\n___\r\n```{RepairDescription}```"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
@@ -501,7 +501,7 @@ namespace Disco.Services
JobId = j.Id, JobId = j.Id,
TechUserId = TechUser.UserId, TechUserId = TechUser.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Manual Repair Request Submitted\r\nProvider: **{0}**\r\nAddress: **{1}**\r\nReference: **{2}**\r\n___\r\n```{3}```", ManualProviderName, Address.Name, ManualProviderReference ?? "<none>", FaultDescription) Comments = $"# Manual Repair Request Submitted\r\nProvider: **{ManualProviderName}**\r\nAddress: **{Address.Name}**\r\nReference: **{ManualProviderReference ?? "<none>"}**\r\n___\r\n```{FaultDescription}```"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
} }
+1 -2
View File
@@ -267,8 +267,7 @@ namespace Disco.Services
public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext Database, PluginFeatureManifest WarrantyProviderDefinition) public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext Database, PluginFeatureManifest WarrantyProviderDefinition)
{ {
var versionDisco = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; var versionDisco = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
return string.Format("Automation by Disco ICT v{0}.{1}.{2:0000}.{3:0000} (Provider: {4} v{5})", return $"Automation by Disco ICT v{versionDisco.Major}.{versionDisco.Minor}.{versionDisco.Build:0000}.{versionDisco.Revision:0000} (Provider: {WarrantyProviderDefinition.Id} v{WarrantyProviderDefinition.PluginManifest.Version.ToString(4)})";
versionDisco.Major, versionDisco.Minor, versionDisco.Build, versionDisco.Revision, WarrantyProviderDefinition.Id, WarrantyProviderDefinition.PluginManifest.Version.ToString(4));
} }
public static void UpdateSubTypes(this Job j, DiscoDataContext Database, List<JobSubType> SubTypes, bool AddComponents, User TechUser) public static void UpdateSubTypes(this Job j, DiscoDataContext Database, List<JobSubType> SubTypes, bool AddComponents, User TechUser)
@@ -178,7 +178,7 @@ namespace Disco.Services.Jobs.JobLists
private void NotificationError(Exception ex) private void NotificationError(Exception ex)
{ {
SystemLog.LogException(string.Format("Disco.Services.Jobs.JobLists.ManagedJobList: [{0}]", Name), ex); SystemLog.LogException($"Disco.Services.Jobs.JobLists.ManagedJobList: [{Name}]", ex);
} }
private void JobNotification(RepositoryMonitorEvent e) private void JobNotification(RepositoryMonitorEvent e)
@@ -109,7 +109,7 @@ namespace Disco.Services.Jobs.JobQueues
throw new InvalidOperationException("The Job Queue cannot be deleted because it contains jobs"); throw new InvalidOperationException("The Job Queue cannot be deleted because it contains jobs");
// Delete History // Delete History
Status.UpdateStatus(0, string.Format("Removing '{0}' [{1}] Job Queue", queue.Name, queue.Id), "Starting"); Status.UpdateStatus(0, $"Removing '{queue.Name}' [{queue.Id}] Job Queue", "Starting");
var jobQueueJobs = Database.JobQueueJobs.Include("Job").Where(jsj => jsj.JobQueueId == queue.Id).ToList(); var jobQueueJobs = Database.JobQueueJobs.Include("Job").Where(jsj => jsj.JobQueueId == queue.Id).ToList();
if (jobQueueJobs.Count > 0) if (jobQueueJobs.Count > 0)
{ {
@@ -118,7 +118,7 @@ namespace Disco.Services.Jobs.JobQueues
{ {
var jqj = jobQueueJobs[jqjIndex]; var jqj = jobQueueJobs[jqjIndex];
Status.UpdateStatus(jqjIndex * progressInterval, string.Format("Merging history into job #{0} logs", jqj.JobId)); Status.UpdateStatus(jqjIndex * progressInterval, $"Merging history into job #{jqj.JobId} logs");
// Write Logs // Write Logs
Database.JobLogs.Add(new JobLog() Database.JobLogs.Add(new JobLog()
@@ -133,7 +133,7 @@ namespace Disco.Services.Jobs.JobQueues
JobId = jqj.JobId, JobId = jqj.JobId,
TechUserId = jqj.RemovedUserId, TechUserId = jqj.RemovedUserId,
Timestamp = jqj.RemovedDate.Value, Timestamp = jqj.RemovedDate.Value,
Comments = string.Format("# Removed from Queue\r\n**{0}**\r\n{1}", queue.Name, string.IsNullOrWhiteSpace(jqj.RemovedComment) ? "<no comment>" : jqj.RemovedComment) Comments = $"# Removed from Queue\r\n**{queue.Name}**\r\n{(string.IsNullOrWhiteSpace(jqj.RemovedComment) ? "<no comment>" : jqj.RemovedComment)}"
}); });
// Delete JQJ // Delete JQJ
@@ -152,7 +152,7 @@ namespace Disco.Services.Jobs.JobQueues
// Remove from Cache // Remove from Cache
_cache.RemoveQueue(JobQueueId); _cache.RemoveQueue(JobQueueId);
Status.Finished(string.Format("Successfully Deleted Job Queue: '{0}' [{1}]", queue.Name, queue.Id)); Status.Finished($"Successfully Deleted Job Queue: '{queue.Name}' [{queue.Id}]");
} }
#endregion #endregion
+3 -3
View File
@@ -158,7 +158,7 @@ namespace Disco.Services.Logging
{ {
Directory.CreateDirectory(logDirectory); Directory.CreateDirectory(logDirectory);
} }
var logFileName = string.Format("DiscoLog_{0:yyy-MM-dd}.sdf", Date); var logFileName = $"DiscoLog_{Date:yyy-MM-dd}.sdf";
return Path.Combine(logDirectory, logFileName); return Path.Combine(logDirectory, logFileName);
} }
@@ -286,10 +286,10 @@ namespace Disco.Services.Logging
} }
} }
else else
throw new InvalidOperationException(string.Format("Unknown Log Event Type Called: {0} (for Module: {1})", EventTypeId, ModuleId)); throw new InvalidOperationException($"Unknown Log Event Type Called: {EventTypeId} (for Module: {ModuleId})");
} }
else else
throw new InvalidOperationException(string.Format("Unknown Log Module Called: {0}", ModuleId)); throw new InvalidOperationException($"Unknown Log Module Called: {ModuleId}");
} }
} }
@@ -57,7 +57,7 @@ namespace Disco.Services.Logging
var module = LogContext.LogModules.Values.FirstOrDefault(m => m.ModuleName.Equals(name, StringComparison.OrdinalIgnoreCase)); var module = LogContext.LogModules.Values.FirstOrDefault(m => m.ModuleName.Equals(name, StringComparison.OrdinalIgnoreCase));
if (module == null) if (module == null)
throw new ArgumentException(string.Format("Invalid Module Name specified: {0}", name), "ModuleNames"); throw new ArgumentException($"Invalid Module Name specified: {name}", "ModuleNames");
yield return NotificationsModulePrefix + module.ModuleName; yield return NotificationsModulePrefix + module.ModuleName;
} }
+2 -2
View File
@@ -171,7 +171,7 @@ namespace Disco.Services.Logging
public static void CompressDirectory(string DirectoryPath) public static void CompressDirectory(string DirectoryPath)
{ {
if (DirectoryPath.Length > 250) if (DirectoryPath.Length > 250)
throw new InvalidOperationException(string.Format("Directory Path to Long (>250) to Compress: {0}", DirectoryPath)); throw new InvalidOperationException($"Directory Path to Long (>250) to Compress: {DirectoryPath}");
DirectoryInfo dirInfo = new DirectoryInfo(DirectoryPath); DirectoryInfo dirInfo = new DirectoryInfo(DirectoryPath);
if (dirInfo.Exists) if (dirInfo.Exists)
@@ -192,7 +192,7 @@ namespace Disco.Services.Logging
} }
else else
{ {
throw new InvalidOperationException(string.Format("Directory doesn't exist: {0}", DirectoryPath)); throw new InvalidOperationException($"Directory doesn't exist: {DirectoryPath}");
} }
} }
@@ -56,10 +56,10 @@ namespace Disco.Services.Plugins.Features.UIExtension
page.WriteLiteral("\n<div id=\"layout_uiExtensions\">"); page.WriteLiteral("\n<div id=\"layout_uiExtensions\">");
foreach (var uiExtResult in uiExtResults) foreach (var uiExtResult in uiExtResults)
{ {
string extensionDescription = HttpUtility.HtmlEncode(string.Format("{0} @ {1} v{2}", uiExtResult.Source.Id, uiExtResult.Source.PluginManifest.Id, uiExtResult.Source.PluginManifest.Version.ToString(4))); string extensionDescription = HttpUtility.HtmlEncode($"{uiExtResult.Source.Id} @ {uiExtResult.Source.PluginManifest.Id} v{uiExtResult.Source.PluginManifest.Version.ToString(4)}");
page.WriteLiteral(string.Format("\n<!-- BEGIN UI EXTENSION: {0} -->\n", extensionDescription)); page.WriteLiteral($"\n<!-- BEGIN UI EXTENSION: {extensionDescription} -->\n");
uiExtResult.ExecuteResult(page); uiExtResult.ExecuteResult(page);
page.WriteLiteral(string.Format("\n<!-- END UI EXTENSION: {0} -->", extensionDescription)); page.WriteLiteral($"\n<!-- END UI EXTENSION: {extensionDescription} -->");
} }
page.WriteLiteral("\n</div>"); page.WriteLiteral("\n</div>");
page.WriteLiteral("\n<!-- END: Disco ICT UI Extensions -->"); page.WriteLiteral("\n<!-- END: Disco ICT UI Extensions -->");
+5 -5
View File
@@ -69,7 +69,7 @@ namespace Disco.Services.Plugins
packageManifest = PluginManifest.FromPluginManifestFile(packageManifestStream); packageManifest = PluginManifest.FromPluginManifestFile(packageManifestStream);
} }
Status.UpdateStatus(20, string.Format("{0} [{1} v{2}] by {3}", packageManifest.Name, packageManifest.Id, packageManifest.Version.ToString(4), packageManifest.Author), "Initializing Install Environment"); Status.UpdateStatus(20, $"{packageManifest.Name} [{packageManifest.Id} v{packageManifest.Version.ToString(4)}] by {packageManifest.Author}", "Initializing Install Environment");
PluginsLog.LogInstalling(packageManifest); PluginsLog.LogInstalling(packageManifest);
@@ -80,7 +80,7 @@ namespace Disco.Services.Plugins
// Ensure not already installed // Ensure not already installed
if (Plugins.GetPlugins().FirstOrDefault(p => p.Id == packageManifest.Id) != null) if (Plugins.GetPlugins().FirstOrDefault(p => p.Id == packageManifest.Id) != null)
throw new InvalidOperationException(string.Format("The '{0} [{1}]' Plugin is already installed, please uninstall any existing versions before trying again", packageManifest.Name, packageManifest.Id)); throw new InvalidOperationException($"The '{packageManifest.Name} [{packageManifest.Id}]' Plugin is already installed, please uninstall any existing versions before trying again");
using (DiscoDataContext database = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
@@ -90,7 +90,7 @@ namespace Disco.Services.Plugins
var libraryIncompatibility = PluginLibrary.LoadManifest(database).LoadIncompatibilityData(); var libraryIncompatibility = PluginLibrary.LoadManifest(database).LoadIncompatibilityData();
PluginIncompatibility incompatibility; PluginIncompatibility incompatibility;
if (!libraryIncompatibility.IsCompatible(packageManifest.Id, packageManifest.Version, out incompatibility)) if (!libraryIncompatibility.IsCompatible(packageManifest.Id, packageManifest.Version, out incompatibility))
throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] is not compatible: {2}", packageManifest.Id, packageManifest.VersionFormatted, 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
if (Directory.Exists(packagePath)) if (Directory.Exists(packagePath))
@@ -116,7 +116,7 @@ namespace Disco.Services.Plugins
// Extract Package Contents // Extract Package Contents
foreach (var packageEntry in packageArchive.Entries) foreach (var packageEntry in packageArchive.Entries)
{ {
Status.UpdateStatus(30 + (countExtractedFiles++ * extractFileInterval), string.Format("Extracting File: {0}", packageEntry.FullName)); Status.UpdateStatus(30 + (countExtractedFiles++ * extractFileInterval), $"Extracting File: {packageEntry.FullName}");
// Determine Extraction Path // Determine Extraction Path
var packageEntryTarget = Path.Combine(packagePath, packageEntry.FullName); var packageEntryTarget = Path.Combine(packagePath, packageEntry.FullName);
@@ -153,7 +153,7 @@ namespace Disco.Services.Plugins
ScheduledTasks.InitializeScheduledTasks(database, new List<Assembly>() { packageManifest.PluginAssembly }); ScheduledTasks.InitializeScheduledTasks(database, new List<Assembly>() { packageManifest.PluginAssembly });
PluginsLog.LogInstalled(packageManifest); PluginsLog.LogInstalled(packageManifest);
Status.SetFinishedUrl(string.Format("/Config/Plugins/{0}", System.Web.HttpUtility.UrlEncode(packageManifest.Id))); Status.SetFinishedUrl($"/Config/Plugins/{System.Web.HttpUtility.UrlEncode(packageManifest.Id)}");
Status.UpdateStatus(100, "Plugin Installation Completed"); Status.UpdateStatus(100, "Plugin Installation Completed");
} }
} }
@@ -37,9 +37,9 @@ namespace Disco.Services.Plugins
get get
{ {
if (string.IsNullOrEmpty(_pluginRequested)) if (string.IsNullOrEmpty(_pluginRequested))
return string.Format("Invalid Category Type [{0}]", _categoryType.Name); return $"Invalid Category Type [{_categoryType.Name}]";
else else
return string.Format("Plugin [{1}] is not of the correct Category Type [{0}]", _categoryType.Name, _pluginRequested); return $"Plugin [{_pluginRequested}] is not of the correct Category Type [{_categoryType.Name}]";
} }
} }
+1 -1
View File
@@ -23,7 +23,7 @@ namespace Disco.Services.Plugins
public override sealed string ToString() public override sealed string ToString()
{ {
return string.Format("{0} ({1}) - v{2}", Manifest.Name, Manifest.Id, Manifest.Version.ToString(4)); return $"{Manifest.Name} ({Manifest.Id}) - v{Manifest.Version.ToString(4)}";
} }
} }
} }
+2 -2
View File
@@ -152,7 +152,7 @@ namespace Disco.Services.Plugins
var routeValues = new RouteValueDictionary(new { PluginId = manifest.Id, res = Resource }); var routeValues = new RouteValueDictionary(new { PluginId = manifest.Id, res = Resource });
string pluginActionUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, RequestContext, false); string pluginActionUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, RequestContext, false);
pluginActionUrl += string.Format("?v={0}", resourcePath.Item2); pluginActionUrl += $"?v={resourcePath.Item2}";
if (Download) if (Download)
pluginActionUrl += "&Download=true"; pluginActionUrl += "&Download=true";
@@ -297,7 +297,7 @@ namespace Disco.Services.Plugins
var routeValues = new RouteValueDictionary(new { PluginId = manifest.Id, res = Resource }); var routeValues = new RouteValueDictionary(new { PluginId = manifest.Id, res = Resource });
string pluginResourceUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, RequestContext, false); string pluginResourceUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, RequestContext, false);
pluginResourceUrl += string.Format("?v={0}", resourcePath.Item2); pluginResourceUrl += $"?v={resourcePath.Item2}";
HtmlString pluginResourceUrlHtml = new HtmlString(pluginResourceUrl); HtmlString pluginResourceUrlHtml = new HtmlString(pluginResourceUrl);
@@ -57,7 +57,7 @@ namespace Disco.Services.Plugins
return i; return i;
} }
else else
throw new InvalidOperationException(string.Format("The feature [{0}] cannot be cast into type [{1}]", Type.Name, typeof(CategoryType).Name)); throw new InvalidOperationException($"The feature [{Type.Name}] cannot be cast into type [{typeof(CategoryType).Name}]");
} }
/// <summary> /// <summary>
@@ -70,7 +70,7 @@ namespace Disco.Services.Plugins
var featureAttribute = (PluginFeatureAttribute)featureType.GetCustomAttributes(typeof(PluginFeatureAttribute), false).FirstOrDefault(); var featureAttribute = (PluginFeatureAttribute)featureType.GetCustomAttributes(typeof(PluginFeatureAttribute), false).FirstOrDefault();
if (featureAttribute == null) if (featureAttribute == null)
throw new ArgumentException(string.Format("Plugin Feature found [{0}], but no PluginFeatureAttribute found", featureType.Name), "featureType"); throw new ArgumentException($"Plugin Feature found [{featureType.Name}], but no PluginFeatureAttribute found", "featureType");
var featureId = featureAttribute.Id; var featureId = featureAttribute.Id;
var featureName = featureAttribute.Name; var featureName = featureAttribute.Name;
@@ -80,19 +80,19 @@ namespace Disco.Services.Plugins
var featureCategoryType = featureType.BaseType; var featureCategoryType = featureType.BaseType;
if (featureCategoryType == null) if (featureCategoryType == null)
throw new ArgumentException(string.Format("Plugin Feature found [{0}], but has no Base Type to determine its Category", featureType.Name), "featureType"); throw new ArgumentException($"Plugin Feature found [{featureType.Name}], but has no Base Type to determine its Category", "featureType");
// Handle Generic-Type Features (Only use base-feature, not generic parameters) // Handle Generic-Type Features (Only use base-feature, not generic parameters)
if (featureCategoryType.IsGenericType) if (featureCategoryType.IsGenericType)
featureCategoryType = featureCategoryType.GetGenericTypeDefinition(); featureCategoryType = featureCategoryType.GetGenericTypeDefinition();
if (featureCategoryType == typeof(PluginFeature) || !typeof(PluginFeature).IsAssignableFrom(featureCategoryType)) if (featureCategoryType == typeof(PluginFeature) || !typeof(PluginFeature).IsAssignableFrom(featureCategoryType))
throw new ArgumentException(string.Format("Plugin Feature found [{0}], but its Base Type is not a valid Feature Category Type (Base Feature or not assignable)", featureType.Name), "featureType"); throw new ArgumentException($"Plugin Feature found [{featureType.Name}], but its Base Type is not a valid Feature Category Type (Base Feature or not assignable)", "featureType");
var featureCategoryAttribute = (PluginFeatureCategoryAttribute)featureCategoryType.GetCustomAttributes(typeof(PluginFeatureCategoryAttribute), false).FirstOrDefault(); var featureCategoryAttribute = (PluginFeatureCategoryAttribute)featureCategoryType.GetCustomAttributes(typeof(PluginFeatureCategoryAttribute), false).FirstOrDefault();
if (featureCategoryAttribute == null) if (featureCategoryAttribute == null)
throw new ArgumentException(string.Format("Plugin Feature found [{0}], but its Base Type is not a valid Feature Category Type (no attribute)", featureType.Name), "featureType"); throw new ArgumentException($"Plugin Feature found [{featureType.Name}], but its Base Type is not a valid Feature Category Type (no attribute)", "featureType");
return new PluginFeatureManifest() return new PluginFeatureManifest()
{ {
+12 -12
View File
@@ -68,7 +68,7 @@ namespace Disco.Services.Plugins
get get
{ {
var v = Version; var v = Version;
return string.Format("{0}.{1}.{2:0000}.{3:0000}", v.Major, v.Minor, v.Build, v.Revision); return $"{v.Major}.{v.Minor}.{v.Build:0000}.{v.Revision:0000}";
} }
} }
@@ -242,7 +242,7 @@ namespace Disco.Services.Plugins
var pluginAttributes = pluginType.GetCustomAttribute<PluginAttribute>(false); var pluginAttributes = pluginType.GetCustomAttribute<PluginAttribute>(false);
if (pluginAttributes == null) if (pluginAttributes == null)
throw new ArgumentException(string.Format("Plugin found [{0}], but no PluginAttribute found", pluginType.Name), "pluginAssembly"); throw new ArgumentException($"Plugin found [{pluginType.Name}], but no PluginAttribute found", "pluginAssembly");
var pluginId = pluginAttributes.Id; var pluginId = pluginAttributes.Id;
var pluginName = pluginAttributes.Name; var pluginName = pluginAttributes.Name;
@@ -328,19 +328,19 @@ namespace Disco.Services.Plugins
var assemblyFullPath = Path.Combine(PluginLocation, AssemblyPath); var assemblyFullPath = Path.Combine(PluginLocation, AssemblyPath);
if (!File.Exists(assemblyFullPath)) if (!File.Exists(assemblyFullPath))
throw new FileNotFoundException(string.Format("Plugin Assembly [{0}] not found at: {1}", Id, assemblyFullPath), assemblyFullPath); throw new FileNotFoundException($"Plugin Assembly [{Id}] not found at: {assemblyFullPath}", assemblyFullPath);
if (PluginAssembly == null) if (PluginAssembly == null)
PluginAssembly = Assembly.LoadFile(assemblyFullPath); PluginAssembly = Assembly.LoadFile(assemblyFullPath);
if (PluginAssembly == null) if (PluginAssembly == null)
throw new InvalidOperationException(string.Format("Unable to load Plugin Assembly [{0}] at: {1}", Id, assemblyFullPath)); throw new InvalidOperationException($"Unable to load Plugin Assembly [{Id}] at: {assemblyFullPath}");
PluginsLog.LogInitializingPluginAssembly(PluginAssembly); PluginsLog.LogInitializingPluginAssembly(PluginAssembly);
// Check Manifest/Assembly Versions Match // Check Manifest/Assembly Versions Match
if (Version != PluginAssembly.GetName().Version) if (Version != PluginAssembly.GetName().Version)
throw new InvalidOperationException(string.Format("The plugin [{0}] manifest version [{1}] doesn't match the plugin assembly [{2} : {3}]", Id, Version, assemblyFullPath, PluginAssembly.GetName().Version)); throw new InvalidOperationException($"The plugin [{Id}] manifest version [{Version}] doesn't match the plugin assembly [{assemblyFullPath} : {PluginAssembly.GetName().Version}]");
if (Type == null) if (Type == null)
Type = PluginAssembly.GetType(TypeName, true, true); Type = PluginAssembly.GetType(TypeName, true, true);
@@ -442,7 +442,7 @@ namespace Disco.Services.Plugins
{ {
get get
{ {
return string.Format("/Config/Plugins/{0}", HttpUtility.UrlEncode(Id)); return $"/Config/Plugins/{HttpUtility.UrlEncode(Id)}";
} }
} }
[JsonIgnore] [JsonIgnore]
@@ -471,7 +471,7 @@ namespace Disco.Services.Plugins
{ {
var attributeDenied = WebHandlerAuthorizers.FirstOrDefault(a => !a.IsAuthorized(HostController.HttpContext)); var attributeDenied = WebHandlerAuthorizers.FirstOrDefault(a => !a.IsAuthorized(HostController.HttpContext));
if (attributeDenied != null) if (attributeDenied != null)
throw new AccessDeniedException(attributeDenied.HandleUnauthorizedMessage(), string.Format("[Plugin]::{0}::[Handler]", Id)); throw new AccessDeniedException(attributeDenied.HandleUnauthorizedMessage(), $"[Plugin]::{Id}::[Handler]");
} }
var handler = (PluginWebHandler)Activator.CreateInstance(WebHandlerType); var handler = (PluginWebHandler)Activator.CreateInstance(WebHandlerType);
@@ -487,7 +487,7 @@ namespace Disco.Services.Plugins
{ {
get get
{ {
return string.Format("/Plugin/{0}", HttpUtility.UrlEncode(Id)); return $"/Plugin/{HttpUtility.UrlEncode(Id)}";
} }
} }
public string WebActionUrl(string Action) public string WebActionUrl(string Action)
@@ -513,7 +513,7 @@ namespace Disco.Services.Plugins
var resourcePath = Path.Combine(PluginLocation, "WebResources", Resource.Replace(@"/", @"\")); var resourcePath = Path.Combine(PluginLocation, "WebResources", Resource.Replace(@"/", @"\"));
Tuple<string, DateTime> resourceHash; Tuple<string, DateTime> resourceHash;
string resourceKey = string.Format("{0}://{1}", Name, Resource); string resourceKey = $"{Name}://{Resource}";
if (WebResourceHashes.TryGetValue(resourceKey, out resourceHash)) if (WebResourceHashes.TryGetValue(resourceKey, out resourceHash))
{ {
#if DEBUG #if DEBUG
@@ -524,7 +524,7 @@ namespace Disco.Services.Plugins
} }
if (!File.Exists(resourcePath)) if (!File.Exists(resourcePath))
throw new FileNotFoundException(string.Format("Resource [{0}] not found", Resource), resourcePath); throw new FileNotFoundException($"Resource [{Resource}] not found", resourcePath);
var fileDate = System.IO.File.GetLastWriteTime(resourcePath); var fileDate = System.IO.File.GetLastWriteTime(resourcePath);
var fileBytes = System.IO.File.ReadAllBytes(resourcePath); var fileBytes = System.IO.File.ReadAllBytes(resourcePath);
@@ -548,7 +548,7 @@ namespace Disco.Services.Plugins
new RouteValueDictionary(new Dictionary<string, object>() { { "PluginId", Id }, { "res", Resource } }), new RouteValueDictionary(new Dictionary<string, object>() { { "PluginId", Id }, { "res", Resource } }),
RouteTable.Routes, HttpContext.Current.Request.RequestContext, false); RouteTable.Routes, HttpContext.Current.Request.RequestContext, false);
url += string.Format("?v={0}", resourcePath.Item2); url += $"?v={resourcePath.Item2}";
return url; return url;
} }
@@ -577,7 +577,7 @@ namespace Disco.Services.Plugins
public override string ToString() public override string ToString()
{ {
return string.Format("{0} [{1} v{2}]", Name, Id, VersionFormatted); return $"{Name} [{Id} v{VersionFormatted}]";
} }
} }
} }
+1 -1
View File
@@ -292,7 +292,7 @@ namespace Disco.Services.Plugins
var routeValues = new RouteValueDictionary(new { PluginId = Manifest.Id, res = Resource }); var routeValues = new RouteValueDictionary(new { PluginId = Manifest.Id, res = Resource });
string pluginActionUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, HostController.Request.RequestContext, false); string pluginActionUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, HostController.Request.RequestContext, false);
pluginActionUrl += string.Format("?v={0}", resourcePath.Item2); pluginActionUrl += $"?v={resourcePath.Item2}";
if (Download.HasValue && Download.Value) if (Download.HasValue && Download.Value)
{ {
@@ -173,7 +173,7 @@ namespace Disco.Services.Plugins
var filters = methodInfo.GetCustomAttributes<FilterAttribute>(true).OfType<IAuthorizationFilter>().ToList(); var filters = methodInfo.GetCustomAttributes<FilterAttribute>(true).OfType<IAuthorizationFilter>().ToList();
foreach (var authorizer in filters.OfType<DiscoAuthorizeBaseAttribute>()) foreach (var authorizer in filters.OfType<DiscoAuthorizeBaseAttribute>())
authorizer.AuthorizeResource = string.Format("[Plugin]::{0}::{1}", controllerDescription.Manifest.Id, methodInfo.Name); authorizer.AuthorizeResource = $"[Plugin]::{controllerDescription.Manifest.Id}::{methodInfo.Name}";
return filters.ToArray(); return filters.ToArray();
} }
+9 -9
View File
@@ -35,7 +35,7 @@ namespace Disco.Services.Plugins
lock (_PluginLock) lock (_PluginLock)
{ {
if (_PluginManifests.ContainsKey(Manifest.Id)) if (_PluginManifests.ContainsKey(Manifest.Id))
throw new InvalidOperationException(string.Format("The '{0} [{1}]' Plugin is already installed, please uninstall any existing versions before trying again", Manifest.Name, Manifest.Id)); throw new InvalidOperationException($"The '{Manifest.Name} [{Manifest.Id}]' Plugin is already installed, please uninstall any existing versions before trying again");
// Add Plugin Manifest to Environment // Add Plugin Manifest to Environment
_PluginManifests[Manifest.Id] = Manifest; _PluginManifests[Manifest.Id] = Manifest;
@@ -256,7 +256,7 @@ namespace Disco.Services.Plugins
if (FeatureCategoryDisplayNames.TryGetValue(FeatureCategoryType, out displayName)) if (FeatureCategoryDisplayNames.TryGetValue(FeatureCategoryType, out displayName))
return displayName; return displayName;
else else
throw new InvalidOperationException(string.Format("Unknown Plugin Feature Category Type: [{0}]", FeatureCategoryType.Name)); throw new InvalidOperationException($"Unknown Plugin Feature Category Type: [{FeatureCategoryType.Name}]");
} }
public static void InitalizePlugins(DiscoDataContext Database) public static void InitalizePlugins(DiscoDataContext Database)
@@ -295,10 +295,10 @@ namespace Disco.Services.Plugins
if (pluginManifest != null) if (pluginManifest != null)
{ {
if (loadedPlugins.ContainsKey(pluginManifest.Id)) if (loadedPlugins.ContainsKey(pluginManifest.Id))
throw new InvalidOperationException(string.Format("The plugin [{0}] is already initialized", pluginManifest.Id)); throw new InvalidOperationException($"The plugin [{pluginManifest.Id}] is already initialized");
// Check for Update // Check for Update
string updatePackagePath = Path.Combine(pluginDirectoryRoot.FullName, string.Format("{0}.discoPlugin", pluginManifest.Id)); string updatePackagePath = Path.Combine(pluginDirectoryRoot.FullName, $"{pluginManifest.Id}.discoPlugin");
if (File.Exists(updatePackagePath)) if (File.Exists(updatePackagePath))
{ {
// Update Plugin // Update Plugin
@@ -310,12 +310,12 @@ namespace Disco.Services.Plugins
// Check Version Compatibility // Check Version Compatibility
var pluginIncompatible = compatibilityData.Value.IncompatiblePlugins.FirstOrDefault(i => i.PluginId.Equals(pluginManifest.Id, StringComparison.OrdinalIgnoreCase) && pluginManifest.Version == i.Version); var pluginIncompatible = compatibilityData.Value.IncompatiblePlugins.FirstOrDefault(i => i.PluginId.Equals(pluginManifest.Id, StringComparison.OrdinalIgnoreCase) && pluginManifest.Version == i.Version);
if (pluginIncompatible != null) if (pluginIncompatible != null)
throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] is not compatible: {2}", pluginManifest.Id, pluginManifest.VersionFormatted, pluginIncompatible.Reason)); throw new InvalidOperationException($"The plugin [{pluginManifest.Id} v{pluginManifest.VersionFormatted}] is not compatible: {pluginIncompatible.Reason}");
if (pluginManifest.HostVersionMin != null && pluginManifest.HostVersionMin > hostVersion) if (pluginManifest.HostVersionMin != null && pluginManifest.HostVersionMin > hostVersion)
throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] does not support this version of Disco ICT (Requires v{2} or greater)", pluginManifest.Id, pluginManifest.VersionFormatted, pluginManifest.HostVersionMin.ToString())); throw new InvalidOperationException($"The plugin [{pluginManifest.Id} v{pluginManifest.VersionFormatted}] does not support this version of Disco ICT (Requires v{pluginManifest.HostVersionMin.ToString()} or greater)");
if (pluginManifest.HostVersionMax != null && pluginManifest.HostVersionMax < hostVersion) if (pluginManifest.HostVersionMax != null && pluginManifest.HostVersionMax < hostVersion)
throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] does not support this version of Disco ICT (Support expired as of v{2})", pluginManifest.Id, pluginManifest.VersionFormatted, pluginManifest.HostVersionMax.ToString())); throw new InvalidOperationException($"The plugin [{pluginManifest.Id} v{pluginManifest.VersionFormatted}] does not support this version of Disco ICT (Support expired as of v{pluginManifest.HostVersionMax.ToString()})");
RegisterPluginAssemblyReferences(pluginManifest); RegisterPluginAssemblyReferences(pluginManifest);
@@ -429,7 +429,7 @@ namespace Disco.Services.Plugins
PluginLibraryIncompatibility = PluginLibrary.LoadManifest(Database).LoadIncompatibilityData(); PluginLibraryIncompatibility = PluginLibrary.LoadManifest(Database).LoadIncompatibilityData();
var pluginIncompatibility = PluginLibraryIncompatibility.IncompatiblePlugins.FirstOrDefault(i => i.PluginId.Equals(packageManifest.Id, StringComparison.OrdinalIgnoreCase) && packageManifest.Version == i.Version); var pluginIncompatibility = PluginLibraryIncompatibility.IncompatiblePlugins.FirstOrDefault(i => i.PluginId.Equals(packageManifest.Id, StringComparison.OrdinalIgnoreCase) && packageManifest.Version == i.Version);
if (pluginIncompatibility != null) if (pluginIncompatibility != null)
throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] is not compatible: {2}", packageManifest.Id, packageManifest.VersionFormatted, pluginIncompatibility.Reason)); throw new InvalidOperationException($"The plugin [{packageManifest.Id} v{packageManifest.VersionFormatted}] is not compatible: {pluginIncompatibility.Reason}");
string packagePath = Path.Combine(Database.DiscoConfiguration.PluginsLocation, packageManifest.Id); string packagePath = Path.Combine(Database.DiscoConfiguration.PluginsLocation, packageManifest.Id);
@@ -554,7 +554,7 @@ namespace Disco.Services.Plugins
} }
catch (Exception ex) catch (Exception ex)
{ {
PluginsLog.LogPluginException(string.Format("Resolving Plugin Reference Assembly: '{0}' [{1}]; Requested by: '{2}' [{3}]; Disco.Plugins.DiscoPlugins.CurrentDomain_AssemblyResolve()", args.Name, assemblyPath, args.RequestingAssembly.FullName, args.RequestingAssembly.Location), ex); PluginsLog.LogPluginException($"Resolving Plugin Reference Assembly: '{args.Name}' [{assemblyPath}]; Requested by: '{args.RequestingAssembly.FullName}' [{args.RequestingAssembly.Location}]; Disco.Plugins.DiscoPlugins.CurrentDomain_AssemblyResolve()", ex);
} }
} }
} }
@@ -16,7 +16,7 @@ namespace Disco.Services.Plugins
var manifest = (PluginManifest)ExecutionContext.JobDetail.JobDataMap["PluginManifest"]; var manifest = (PluginManifest)ExecutionContext.JobDetail.JobDataMap["PluginManifest"];
var UninstallData = (bool)ExecutionContext.JobDetail.JobDataMap["UninstallData"]; var UninstallData = (bool)ExecutionContext.JobDetail.JobDataMap["UninstallData"];
Status.UpdateStatus(25, string.Format("Uninstalling Plugin: {0} [{1}]", manifest.Name, manifest.Id), "Queuing plugin for uninstall"); Status.UpdateStatus(25, $"Uninstalling Plugin: {manifest.Name} [{manifest.Id}]", "Queuing plugin for uninstall");
PluginsLog.LogUninstalling(manifest, UninstallData); PluginsLog.LogUninstalling(manifest, UninstallData);
@@ -27,7 +27,7 @@ namespace Disco.Services.Plugins
{ {
get get
{ {
return string.Format("Unknown Plugin Id: [{0}]", _pluginRequested); return $"Unknown Plugin Id: [{_pluginRequested}]";
} }
} }
} }
+5 -5
View File
@@ -187,8 +187,8 @@ namespace Disco.Services.Plugins
if (string.IsNullOrEmpty(packageTempFilePath)) if (string.IsNullOrEmpty(packageTempFilePath))
{ {
// Download Update // Download Update
Status.UpdateStatus(0, string.Format("Downloading Plugin Package: {0}", pluginName), "Connecting..."); Status.UpdateStatus(0, $"Downloading Plugin Package: {pluginName}", "Connecting...");
packageTempFilePath = Path.Combine(pluginPackagesLocation, string.Format("{0}.discoPlugin", pluginId)); packageTempFilePath = Path.Combine(pluginPackagesLocation, $"{pluginId}.discoPlugin");
if (File.Exists(packageTempFilePath)) if (File.Exists(packageTempFilePath))
File.Delete(packageTempFilePath); File.Delete(packageTempFilePath);
@@ -238,7 +238,7 @@ namespace Disco.Services.Plugins
if (updateManifest.Version < existingManifest.Version) if (updateManifest.Version < existingManifest.Version)
throw new InvalidOperationException("Older versions cannot update existing plugins"); throw new InvalidOperationException("Older versions cannot update existing plugins");
Status.UpdateStatus(20, string.Format("{0} [{1} v{2}] by {3}", updateManifest.Name, updateManifest.Id, updateManifest.Version.ToString(4), updateManifest.Author), "Initializing Update Environment"); Status.UpdateStatus(20, $"{updateManifest.Name} [{updateManifest.Id} v{updateManifest.Version.ToString(4)}] by {updateManifest.Author}", "Initializing Update Environment");
using (DiscoDataContext database = new DiscoDataContext()) using (DiscoDataContext database = new DiscoDataContext())
{ {
@@ -246,9 +246,9 @@ namespace Disco.Services.Plugins
var incompatibilityLibrary = PluginLibrary.LoadManifest(database).LoadIncompatibilityData(); var incompatibilityLibrary = PluginLibrary.LoadManifest(database).LoadIncompatibilityData();
PluginIncompatibility incompatibility; PluginIncompatibility incompatibility;
if (!incompatibilityLibrary.IsCompatible(updateManifest.Id, updateManifest.Version, out incompatibility)) if (!incompatibilityLibrary.IsCompatible(updateManifest.Id, updateManifest.Version, out incompatibility))
throw new InvalidOperationException(string.Format("The plugin [{0} v{1}] is not compatible: {2}", updateManifest.Id, updateManifest.VersionFormatted, incompatibility.Reason)); throw new InvalidOperationException($"The plugin [{updateManifest.Id} v{updateManifest.VersionFormatted}] is not compatible: {incompatibility.Reason}");
var updatePluginPath = Path.Combine(database.DiscoConfiguration.PluginsLocation, string.Format("{0}.discoPlugin", updateManifest.Id)); var updatePluginPath = Path.Combine(database.DiscoConfiguration.PluginsLocation, $"{updateManifest.Id}.discoPlugin");
File.Move(packageTempFilePath, updatePluginPath); File.Move(packageTempFilePath, updatePluginPath);
if (existingManifest != null) if (existingManifest != null)
+1 -1
View File
@@ -130,7 +130,7 @@ namespace Disco.Services.Tasks
{ {
var existingGuid = _RunningTasks.Where(t => t.IsRunning && t.TaskType == taskType).Select(t => t.SessionId).FirstOrDefault(); var existingGuid = _RunningTasks.Where(t => t.IsRunning && t.TaskType == taskType).Select(t => t.SessionId).FirstOrDefault();
if (existingGuid != null) if (existingGuid != null)
throw new InvalidOperationException(string.Format("This Single-Instance Task is already running, SessionId: {0}", existingGuid)); throw new InvalidOperationException($"This Single-Instance Task is already running, SessionId: {existingGuid}");
} }
_RunningTasks.Add(taskStatus); _RunningTasks.Add(taskStatus);
} }
+1 -1
View File
@@ -18,7 +18,7 @@ namespace Disco.Services
public static string ToStringFriendly(this User u) public static string ToStringFriendly(this User u)
{ {
return string.Format("{0} ({1})", u.DisplayName, u.FriendlyId()); return $"{u.DisplayName} ({u.FriendlyId()})";
} }
public static string FriendlyId(this User u) public static string FriendlyId(this User u)
@@ -100,7 +100,7 @@ namespace Disco.Services.Users.UserFlags
Interop.ActiveDirectory.ActiveDirectory.Context.ManagedGroups.Remove(UserFlagUsersManagedGroup.GetKey(flag)); Interop.ActiveDirectory.ActiveDirectory.Context.ManagedGroups.Remove(UserFlagUsersManagedGroup.GetKey(flag));
// Delete Assignments // Delete Assignments
Status.UpdateStatus(0, string.Format("Removing '{0}' [{1}] User Flag", flag.Name, flag.Id), "Starting"); Status.UpdateStatus(0, $"Removing '{flag.Name}' [{flag.Id}] User Flag", "Starting");
List<UserFlagAssignment> flagAssignments = Database.UserFlagAssignments.Where(fa => fa.UserFlagId == flag.Id).ToList(); List<UserFlagAssignment> flagAssignments = Database.UserFlagAssignments.Where(fa => fa.UserFlagId == flag.Id).ToList();
if (flagAssignments.Count > 0) if (flagAssignments.Count > 0)
{ {
@@ -117,7 +117,7 @@ namespace Disco.Services.Users.UserFlags
// Remove from Cache // Remove from Cache
_cache.Remove(UserFlagId); _cache.Remove(UserFlagId);
Status.Finished(string.Format("Successfully Deleted User Flag: '{0}' [{1}]", flag.Name, flag.Id)); Status.Finished($"Successfully Deleted User Flag: '{flag.Name}' [{flag.Id}]");
} }
#endregion #endregion
@@ -140,7 +140,7 @@ namespace Disco.Services.Users.UserFlags
var chunkResults = chunk.Select((user, index) => var chunkResults = chunk.Select((user, index) =>
{ {
Status.UpdateStatus((chunkIndexOffset + index) * progressInterval, string.Format("Assigning Flag: {0}", user.ToString())); Status.UpdateStatus((chunkIndexOffset + index) * progressInterval, $"Assigning Flag: {user.ToString()}");
return user.OnAddUserFlag(Database, UserFlag, Technician, comments); return user.OnAddUserFlag(Database, UserFlag, Technician, comments);
}).ToList(); }).ToList();
@@ -151,7 +151,7 @@ namespace Disco.Services.Users.UserFlags
return chunkResults; return chunkResults;
}).Where(fa => fa != null).ToList(); }).Where(fa => fa != null).ToList();
Status.SetFinishedMessage(string.Format("{0} Users/s Added; {1} User/s Skipped", addUsers.Count, (Users.Count - addUsers.Count))); Status.SetFinishedMessage($"{addUsers.Count} Users/s Added; {(Users.Count - addUsers.Count)} User/s Skipped");
return addedUserAssignments; return addedUserAssignments;
} }
@@ -186,7 +186,7 @@ namespace Disco.Services.Users.UserFlags
var chunkResults = chunk.Select((flagAssignment, index) => var chunkResults = chunk.Select((flagAssignment, index) =>
{ {
Status.UpdateStatus((chunkIndexOffset + index) * progressInterval, string.Format("Removing Flag: {0}", flagAssignment.User.ToString())); Status.UpdateStatus((chunkIndexOffset + index) * progressInterval, $"Removing Flag: {flagAssignment.User.ToString()}");
flagAssignment.OnRemoveUnsafe(Database, Technician); flagAssignment.OnRemoveUnsafe(Database, Technician);
@@ -206,7 +206,7 @@ namespace Disco.Services.Users.UserFlags
var chunkResults = chunk.Select((user, index) => var chunkResults = chunk.Select((user, index) =>
{ {
Status.UpdateStatus((chunkIndexOffset + index) * progressInterval, string.Format("Assigning Flag: {0}", user.ToString())); Status.UpdateStatus((chunkIndexOffset + index) * progressInterval, $"Assigning Flag: {user.ToString()}");
return user.OnAddUserFlag(Database, UserFlag, Technician, comments); return user.OnAddUserFlag(Database, UserFlag, Technician, comments);
}).ToList(); }).ToList();
@@ -217,7 +217,7 @@ namespace Disco.Services.Users.UserFlags
return chunkResults; return chunkResults;
}).ToList(); }).ToList();
Status.SetFinishedMessage(string.Format("{0} Users/s Added; {1} User/s Removed; {2} User/s Skipped", addUsers.Count, removeAssignments.Count, (Users.Count - addUsers.Count))); Status.SetFinishedMessage($"{addUsers.Count} Users/s Added; {removeAssignments.Count} User/s Removed; {(Users.Count - addUsers.Count)} User/s Skipped");
return addedUserAssignments; return addedUserAssignments;
} }
@@ -32,7 +32,7 @@ namespace Disco.Services.Users.UserFlags
if (userFlag == null) if (userFlag == null)
throw new Exception("Invalid User Flag Id"); throw new Exception("Invalid User Flag Id");
Status.UpdateStatus(0, string.Format("Bulk Assigning Users to User Flag: {0}", userFlag.Name), "Preparing to start"); Status.UpdateStatus(0, $"Bulk Assigning Users to User Flag: {userFlag.Name}", "Preparing to start");
// Load Technician // Load Technician
var technician = Database.Users.FirstOrDefault(user => user.UserId == TechnicianUserId); var technician = Database.Users.FirstOrDefault(user => user.UserId == TechnicianUserId);
@@ -56,7 +56,7 @@ namespace Disco.Services.Users.UserFlags
for (int index = 0; index < missingUserIds.Count; index++) for (int index = 0; index < missingUserIds.Count; index++)
{ {
var userId = missingUserIds[index]; var userId = missingUserIds[index];
Status.UpdateStatus(20 + (index * ((double)30 / missingUserIds.Count)), string.Format("Loading user from Active Directory: {0}", userId)); Status.UpdateStatus(20 + (index * ((double)30 / missingUserIds.Count)), $"Loading user from Active Directory: {userId}");
try try
{ {
users.Add(UserService.GetUser(userId, Database, true)); users.Add(UserService.GetUser(userId, Database, true));
@@ -68,7 +68,7 @@ namespace Disco.Services.Users.UserFlags
} }
if (invalidUsersIds.Count > 0) if (invalidUsersIds.Count > 0)
throw new InvalidOperationException(string.Format("Bulk assignment aborted, invalid User Ids: {0}", string.Join(", ", invalidUsersIds))); throw new InvalidOperationException($"Bulk assignment aborted, invalid User Ids: {string.Join(", ", invalidUsersIds)}");
} }
users = users.OrderBy(u => u.UserId).ToList(); users = users.OrderBy(u => u.UserId).ToList();
+4 -4
View File
@@ -44,7 +44,7 @@ namespace Disco.Services.Web.Bundles
var bundle = GetBundleFor(BundleUrl); var bundle = GetBundleFor(BundleUrl);
if (bundle == null) if (bundle == null)
throw new ArgumentException(string.Format("Unknown Bundle Url: {0}", BundleUrl), "BundleUrl"); throw new ArgumentException($"Unknown Bundle Url: {BundleUrl}", "BundleUrl");
return VirtualPathUtility.ToAbsolute(bundle.VersionUrl); return VirtualPathUtility.ToAbsolute(bundle.VersionUrl);
} }
@@ -53,16 +53,16 @@ namespace Disco.Services.Web.Bundles
var bundle = GetBundleFor(BundleUrl); var bundle = GetBundleFor(BundleUrl);
if (bundle == null) if (bundle == null)
throw new ArgumentException(string.Format("Unknown Bundle Url: {0}", BundleUrl), "BundleUrl"); throw new ArgumentException($"Unknown Bundle Url: {BundleUrl}", "BundleUrl");
var bundleUrl = VirtualPathUtility.ToAbsolute(bundle.VersionUrl); var bundleUrl = VirtualPathUtility.ToAbsolute(bundle.VersionUrl);
switch (bundle.ContentType) switch (bundle.ContentType)
{ {
case "text/css": case "text/css":
return string.Format("<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />", bundleUrl); return $"<link href=\"{bundleUrl}\" rel=\"stylesheet\" type=\"text/css\" />";
case "text/javascript": case "text/javascript":
return string.Format("<script src=\"{0}\" type=\"text/javascript\"></script>", bundleUrl); return $"<script src=\"{bundleUrl}\" type=\"text/javascript\"></script>";
default: default:
throw new ArgumentException("Unsupported Bundle Content Type", "BundleUrl"); throw new ArgumentException("Unsupported Bundle Content Type", "BundleUrl");
} }
+3 -3
View File
@@ -30,7 +30,7 @@ namespace Disco.Services.Web.Bundles
get get
{ {
#if DEBUG #if DEBUG
return string.Format("{0}?v={1}", Url, FileHash); return $"{Url}?v={FileHash}";
#else #else
return _VersionUrl; return _VersionUrl;
#endif #endif
@@ -53,7 +53,7 @@ namespace Disco.Services.Web.Bundles
var fileInfo = new FileInfo(File); var fileInfo = new FileInfo(File);
if (!fileInfo.Exists) if (!fileInfo.Exists)
throw new FileNotFoundException(string.Format("Not Found: {0}", File), File); throw new FileNotFoundException($"Not Found: {File}", File);
this.Url = Url; this.Url = Url;
this.File = File; this.File = File;
@@ -78,7 +78,7 @@ namespace Disco.Services.Web.Bundles
//this.Version = fileInfo.LastWriteTimeUtc.Ticks; //this.Version = fileInfo.LastWriteTimeUtc.Ticks;
_VersionUrl = string.Format("{0}?v={1}", this.Url, FileHash); _VersionUrl = $"{this.Url}?v={FileHash}";
} }
private void UpdateFileHash() private void UpdateFileHash()
+1 -1
View File
@@ -53,7 +53,7 @@ namespace Disco.Services.Web
var resource = accessDeniedException.Resource; var resource = accessDeniedException.Resource;
var httpContext = HttpContext.Current; var httpContext = HttpContext.Current;
if (httpContext != null && httpContext.Request != null) if (httpContext != null && httpContext.Request != null)
resource = string.Format("{0} [{1}]", resource, httpContext.Request.RawUrl); resource = $"{resource} [{httpContext.Request.RawUrl}]";
AuthorizationLog.LogAccessDenied(UserService.CurrentUserId ?? "[Anonymous]", resource, accessDeniedException.Message); AuthorizationLog.LogAccessDenied(UserService.CurrentUserId ?? "[Anonymous]", resource, accessDeniedException.Message);
} }
@@ -22,12 +22,12 @@ namespace Disco.Web.Extensions
{ {
var selectItems = default(List<SelectListItem>); var selectItems = default(List<SelectListItem>);
if (!SelectedId.HasValue) if (!SelectedId.HasValue)
selectItems = organisationAddressess.Select(wpd => new SelectListItem { Value = wpd.Id.Value.ToString(), Text = string.Format("{0} ({1})", wpd.Name, wpd.ShortName) }).ToList(); selectItems = organisationAddressess.Select(wpd => new SelectListItem { Value = wpd.Id.Value.ToString(), Text = $"{wpd.Name} ({wpd.ShortName})" }).ToList();
else else
selectItems = organisationAddressess.Select(wpd => new SelectListItem { Value = wpd.Id.Value.ToString(), Text = string.Format("{0} ({1})", wpd.Name, wpd.ShortName), Selected = (SelectedId.Equals(wpd.Id)) }).ToList(); selectItems = organisationAddressess.Select(wpd => new SelectListItem { Value = wpd.Id.Value.ToString(), Text = $"{wpd.Name} ({wpd.ShortName})", Selected = (SelectedId.Equals(wpd.Id)) }).ToList();
if (IncludeInstructionFirst) if (IncludeInstructionFirst)
selectItems.Insert(0, new SelectListItem() { Value = String.Empty, Text = String.Format("<{0}>", InstructionMessage), Selected = !SelectedId.HasValue }); selectItems.Insert(0, new SelectListItem() { Value = String.Empty, Text = $"<{InstructionMessage}>", Selected = !SelectedId.HasValue });
return selectItems; return selectItems;
} }
@@ -52,7 +52,7 @@ namespace Disco.Web.Extensions
var selectItems = items.OrderBy(i => i.Text).ToList(); var selectItems = items.OrderBy(i => i.Text).ToList();
if (IncludeInstructionFirst) if (IncludeInstructionFirst)
selectItems.Insert(0, new SelectListItem() { Value = String.Empty, Text = String.Format("<{0}>", InstructionMessage), Selected = (selectedIds?.Count ?? 0) != 0 }); selectItems.Insert(0, new SelectListItem() { Value = String.Empty, Text = $"<{InstructionMessage}>", Selected = (selectedIds?.Count ?? 0) != 0 });
return selectItems; return selectItems;
} }
@@ -76,7 +76,7 @@ namespace Disco.Web.Extensions
selectItems = PluginDefinitions.Select(wpd => new SelectListItem { Value = wpd.Id, Text = wpd.Name, Selected = (SelectedId.Equals(wpd.Id)) }).ToList(); selectItems = PluginDefinitions.Select(wpd => new SelectListItem { Value = wpd.Id, Text = wpd.Name, Selected = (SelectedId.Equals(wpd.Id)) }).ToList();
if (IncludeInstructionFirst) if (IncludeInstructionFirst)
selectItems.Insert(0, new SelectListItem() { Value = String.Empty, Text = String.Format("<{0}>", InstructionMessage), Selected = String.IsNullOrEmpty(SelectedId) }); selectItems.Insert(0, new SelectListItem() { Value = String.Empty, Text = $"<{InstructionMessage}>", Selected = String.IsNullOrEmpty(SelectedId) });
return selectItems; return selectItems;
} }
@@ -6,7 +6,7 @@ namespace Disco.Web.Extensions
{ {
public static string ToJavascriptDate(this DateTime d) public static string ToJavascriptDate(this DateTime d)
{ {
return string.Format("new Date({0}, {1}, {2}, {3}, {4}, {5})", d.Year, d.Month - 1, d.Day, d.Hour, d.Minute, d.Second); return $"new Date({d.Year}, {d.Month - 1}, {d.Day}, {d.Hour}, {d.Minute}, {d.Second})";
} }
public static string ToJavascriptDate(this DateTime? d, DateTime? DefaultDate = null) public static string ToJavascriptDate(this DateTime? d, DateTime? DefaultDate = null)
{ {
@@ -12,7 +12,7 @@ namespace Disco.Web.Extensions
List<string> selectedIds = default(List<string>); List<string> selectedIds = default(List<string>);
if (SelectedItems != null) if (SelectedItems != null)
selectedIds = SelectedItems.Select(i => string.Format("{0}_{1}", i.JobTypeId, i.Id)).ToList(); selectedIds = SelectedItems.Select(i => $"{i.JobTypeId}_{i.Id}").ToList();
return jobSubTypes.ToSelectListItems(selectedIds); return jobSubTypes.ToSelectListItems(selectedIds);
} }
@@ -20,9 +20,9 @@ namespace Disco.Web.Extensions
public static List<SelectListItem> ToSelectListItems(this IEnumerable<JobSubType> jobSubTypes, List<string> SelectedIds = null, bool IncludeQueueIcons = false) public static List<SelectListItem> ToSelectListItems(this IEnumerable<JobSubType> jobSubTypes, List<string> SelectedIds = null, bool IncludeQueueIcons = false)
{ {
if (SelectedIds == null) if (SelectedIds == null)
return jobSubTypes.Select(jst => new SelectListItem { Value = string.Format("{0}_{1}", jst.JobTypeId, jst.Id), Text = IncludeQueueIcons ? jst.DescriptionWithIcons() : jst.Description }).ToList(); return jobSubTypes.Select(jst => new SelectListItem { Value = $"{jst.JobTypeId}_{jst.Id}", Text = IncludeQueueIcons ? jst.DescriptionWithIcons() : jst.Description }).ToList();
else else
return jobSubTypes.Select(jst => new SelectListItem { Value = string.Format("{0}_{1}", jst.JobTypeId, jst.Id), Text = IncludeQueueIcons ? jst.DescriptionWithIcons() : jst.Description, Selected = (SelectedIds.Contains(string.Format("{0}_{1}", jst.JobTypeId, jst.Id))) }).ToList(); return jobSubTypes.Select(jst => new SelectListItem { Value = $"{jst.JobTypeId}_{jst.Id}", Text = IncludeQueueIcons ? jst.DescriptionWithIcons() : jst.Description, Selected = (SelectedIds.Contains($"{jst.JobTypeId}_{jst.Id}")) }).ToList();
} }
public static string DescriptionWithIcons(this JobSubType jst) public static string DescriptionWithIcons(this JobSubType jst)
@@ -32,7 +32,7 @@ namespace Disco.Web.Extensions
var sb = new System.Text.StringBuilder(System.Web.HttpUtility.HtmlEncode(jst.Description)); var sb = new System.Text.StringBuilder(System.Web.HttpUtility.HtmlEncode(jst.Description));
foreach (var jq in jst.JobQueues) foreach (var jq in jst.JobQueues)
sb.AppendFormat("&nbsp;<i class=\"queue fa fa-{0} fa-fw d-{1}\" title=\"{2}\"></i>", jq.Icon, jq.IconColour, jq.Name); sb.AppendFormat($"&nbsp;<i class=\"queue fa fa-{jq.Icon} fa-fw d-{jq.IconColour}\" title=\"{jq.Name}\"></i>");
return sb.ToString(); return sb.ToString();
} }
+1 -1
View File
@@ -42,7 +42,7 @@ namespace Disco.Web
// Scripts - Modules // Scripts - Modules
#if DEBUG #if DEBUG
foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/ClientSource/Scripts/Modules")).EnumerateFiles("*.js", SearchOption.TopDirectoryOnly)) foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/ClientSource/Scripts/Modules")).EnumerateFiles("*.js", SearchOption.TopDirectoryOnly))
BundleTable.Add(new FileBundle(string.Format("~/ClientScripts/Modules/{0}", f.Name.Substring(0, f.Name.Length - 3)), f.FullName)); BundleTable.Add(new FileBundle($"~/ClientScripts/Modules/{f.Name.Substring(0, f.Name.Length - 3)}", f.FullName));
#else #else
foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/ClientSource/Scripts/Modules")).EnumerateFiles("*.min.js", SearchOption.TopDirectoryOnly)) foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/ClientSource/Scripts/Modules")).EnumerateFiles("*.min.js", SearchOption.TopDirectoryOnly))
BundleTable.Add(new FileBundle(string.Format("~/ClientScripts/Modules/{0}", f.Name.Substring(0, f.Name.Length - 7)), f.FullName)); BundleTable.Add(new FileBundle(string.Format("~/ClientScripts/Modules/{0}", f.Name.Substring(0, f.Name.Length - 7)), f.FullName));
@@ -52,7 +52,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -114,7 +114,7 @@ namespace Disco.Web.Areas.API.Controllers
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList(); var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0) if (invalidSubjects.Count > 0)
throw new ArgumentException(string.Format("Subjects not found: {0}", string.Join(", ", invalidSubjects)), "Subjects"); throw new ArgumentException($"Subjects not found: {string.Join(", ", invalidSubjects)}", "Subjects");
var proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray(); var proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
var currentSubjects = AuthorizationRole.SubjectIds == null ? new string[0] : AuthorizationRole.SubjectIds.Split(','); var currentSubjects = AuthorizationRole.SubjectIds == null ? new string[0] : AuthorizationRole.SubjectIds.Split(',');
@@ -170,7 +170,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -200,7 +200,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -229,7 +229,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -253,7 +253,7 @@ namespace Disco.Web.Areas.API.Controllers
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList(); var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0) if (invalidSubjects.Count > 0)
throw new ArgumentException(string.Format("Subjects not found: {0}", string.Join(", ", invalidSubjects)), "Subjects"); throw new ArgumentException($"Subjects not found: {string.Join(", ", invalidSubjects)}", "Subjects");
proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray(); proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
var currentSubjects = UserService.AdministratorSubjectIds; var currentSubjects = UserService.AdministratorSubjectIds;
@@ -25,7 +25,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
public virtual ActionResult MacSshPassword(string MacSshPassword) public virtual ActionResult MacSshPassword(string MacSshPassword)
@@ -45,7 +45,7 @@ namespace Disco.Web.Areas.API.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -116,7 +116,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -235,7 +235,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
[DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)]
@@ -267,7 +267,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
#endregion #endregion
@@ -534,7 +534,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -595,7 +595,7 @@ namespace Disco.Web.Areas.API.Controllers
start = bi.PurchaseDate, start = bi.PurchaseDate,
end = bi.WarrantyValidUntil, end = bi.WarrantyValidUntil,
caption = bi.DefaultModelDescription, caption = bi.DefaultModelDescription,
title = string.Format("{0} [{1} x{2}]", bi.Name, bi.DefaultModelDescription, bi.DeviceCount), title = $"{bi.Name} [{bi.DefaultModelDescription} x{bi.DeviceCount}]",
textColor = "#000", textColor = "#000",
description = bi.Comments ?? string.Empty, description = bi.Comments ?? string.Empty,
color = ColorTranslator.ToHtml(color), color = ColorTranslator.ToHtml(color),
@@ -16,7 +16,7 @@ namespace Disco.Web.Areas.API.Controllers
{ {
throw new Exception("Invalid Device Certificate Id"); throw new Exception("Invalid Device Certificate Id");
} }
return File(wc.Content, "application/x-pkcs12", string.Format("{0}.pfx", wc.Name)); return File(wc.Content, "application/x-pkcs12", $"{wc.Name}.pfx");
} }
} }
@@ -106,7 +106,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -131,7 +131,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
[DiscoAuthorize(Claims.Config.DeviceFlag.Configure)] [DiscoAuthorize(Claims.Config.DeviceFlag.Configure)]
@@ -75,7 +75,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -223,7 +223,7 @@ namespace Disco.Web.Areas.API.Controllers
// DataStore Failed - Use Generic Images // DataStore Failed - Use Generic Images
if (m.ModelType != null) if (m.ModelType != null)
{ {
var modelTypePath = Server.MapPath(string.Format("~/ClientSource/Style/Images/DeviceTypes/{0}.png", m.ModelType)); var modelTypePath = Server.MapPath($"~/ClientSource/Style/Images/DeviceTypes/{m.ModelType}.png");
if (System.IO.File.Exists(modelTypePath)) if (System.IO.File.Exists(modelTypePath))
{ {
return File(modelTypePath, "image/png"); return File(modelTypePath, "image/png");
@@ -295,7 +295,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -121,7 +121,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -375,7 +375,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
[DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)]
@@ -407,7 +407,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
#endregion #endregion
@@ -467,7 +467,7 @@ namespace Disco.Web.Areas.API.Controllers
var featureManifest = Plugins.GetPluginFeature(certificateProviderId, typeof(CertificateProviderFeature)); var featureManifest = Plugins.GetPluginFeature(certificateProviderId, typeof(CertificateProviderFeature));
if (featureManifest == null) if (featureManifest == null)
{ {
throw new Exception(string.Format("Invalid Certificate Provider Plugin Id: [{0}]", certificateProviderId)); throw new Exception($"Invalid Certificate Provider Plugin Id: [{certificateProviderId}]");
} }
else else
{ {
@@ -503,7 +503,7 @@ namespace Disco.Web.Areas.API.Controllers
var featureManifest = Plugins.GetPluginFeature(certificateAuthorityProviderId, typeof(CertificateAuthorityProviderFeature)); var featureManifest = Plugins.GetPluginFeature(certificateAuthorityProviderId, typeof(CertificateAuthorityProviderFeature));
if (featureManifest == null) if (featureManifest == null)
{ {
throw new Exception(string.Format("Invalid Certificate Authority Provider Plugin Id: [{0}]", certificateAuthorityProviderId)); throw new Exception($"Invalid Certificate Authority Provider Plugin Id: [{certificateAuthorityProviderId}]");
} }
else else
{ {
@@ -539,7 +539,7 @@ namespace Disco.Web.Areas.API.Controllers
var featureManifest = Plugins.GetPluginFeature(wirelessProfileProviderId, typeof(WirelessProfileProviderFeature)); var featureManifest = Plugins.GetPluginFeature(wirelessProfileProviderId, typeof(WirelessProfileProviderFeature));
if (featureManifest == null) if (featureManifest == null)
{ {
throw new Exception(string.Format("Invalid Wireless Profile Provider Plugin Id: [{0}]", wirelessProfileProviderId)); throw new Exception($"Invalid Wireless Profile Provider Plugin Id: [{wirelessProfileProviderId}]");
} }
else else
{ {
@@ -728,7 +728,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -758,7 +758,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -792,7 +792,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -104,7 +104,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -120,7 +120,7 @@ namespace Disco.Web.Areas.API.Controllers
var filename = documentTemplate.RepositoryFilename(Database); var filename = documentTemplate.RepositoryFilename(Database);
if (System.IO.File.Exists(filename)) if (System.IO.File.Exists(filename))
{ {
return File(filename, DocumentTemplate.PdfMimeType, string.Format("{0}.pdf", documentTemplate.Id)); return File(filename, DocumentTemplate.PdfMimeType, $"{documentTemplate.Id}.pdf");
} }
else else
{ {
@@ -151,7 +151,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -235,7 +235,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -269,7 +269,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -302,7 +302,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
#endregion #endregion
@@ -498,7 +498,7 @@ namespace Disco.Web.Areas.API.Controllers
public virtual ActionResult ImporterThumbnail(string SessionId, int PageNumber) public virtual ActionResult ImporterThumbnail(string SessionId, int PageNumber)
{ {
var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(Database, "Cache\\DocumentDropBox_SessionPages"); var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(Database, "Cache\\DocumentDropBox_SessionPages");
var filename = System.IO.Path.Combine(dataStoreSessionPagesCacheLocation, string.Format("{0}-{1}", SessionId, PageNumber)); var filename = System.IO.Path.Combine(dataStoreSessionPagesCacheLocation, $"{SessionId}-{PageNumber}");
if (System.IO.File.Exists(filename)) if (System.IO.File.Exists(filename))
return File(filename, "image/png"); return File(filename, "image/png");
else else
@@ -1318,7 +1318,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -76,7 +76,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -111,7 +111,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -165,7 +165,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -381,7 +381,7 @@ namespace Disco.Web.Areas.API.Controllers
var timeStamp = DateTime.Now; var timeStamp = DateTime.Now;
var pdf = package.GeneratePdfPackageBulk(Database, UserService.CurrentUser, timeStamp, InsertBlankPage, dataIds); var pdf = package.GeneratePdfPackageBulk(Database, UserService.CurrentUser, timeStamp, InsertBlankPage, dataIds);
return File(pdf, "application/pdf", string.Format("{0}_Bulk_{1:yyyyMMdd-HHmmss}.pdf", package.Id, timeStamp)); return File(pdf, "application/pdf", $"{package.Id}_Bulk_{timeStamp:yyyyMMdd-HHmmss}.pdf");
} }
public virtual ActionResult Generate(string id, string TargetId) public virtual ActionResult Generate(string id, string TargetId)
@@ -455,7 +455,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -306,7 +306,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -1476,7 +1476,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -1519,7 +1519,7 @@ namespace Disco.Web.Areas.API.Controllers
JobId = job.Id, JobId = job.Id,
TechUserId = CurrentUser.UserId, TechUserId = CurrentUser.UserId,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("# Added Flag\r\n**{0}**\r\n{1}", flagStatus.Item1, string.IsNullOrWhiteSpace(Reason) ? "<no reason provided>" : Reason) Comments = $"# Added Flag\r\n**{flagStatus.Item1}**\r\n{(string.IsNullOrWhiteSpace(Reason) ? "<no reason provided>" : Reason)}"
}; };
Database.JobLogs.Add(jobLog); Database.JobLogs.Add(jobLog);
@@ -1542,7 +1542,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -1573,7 +1573,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -1604,7 +1604,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -2192,9 +2192,9 @@ namespace Disco.Web.Areas.API.Controllers
if (locRef.References != null && locRef.References.Count > 0) if (locRef.References != null && locRef.References.Count > 0)
{ {
if (locRef.References.Count == 1) if (locRef.References.Count == 1)
reference = string.Format("Job {0}", locRef.References[0].JobId); reference = $"Job {locRef.References[0].JobId}";
else else
reference = string.Format("{0} jobs", locRef.References.Count); reference = $"{locRef.References.Count} jobs";
} }
return new Models.Job.DeviceHeldLocationModel() return new Models.Job.DeviceHeldLocationModel()
@@ -71,7 +71,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -139,7 +139,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -170,7 +170,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -199,7 +199,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
#endregion #endregion
@@ -295,7 +295,7 @@ namespace Disco.Web.Areas.API.Controllers
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList(); var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0) if (invalidSubjects.Count > 0)
throw new ArgumentException(string.Format("Subjects not found: {0}", string.Join(", ", invalidSubjects)), "Subjects"); throw new ArgumentException($"Subjects not found: {string.Join(", ", invalidSubjects)}", "Subjects");
var proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray(); var proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
@@ -364,7 +364,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
#endregion #endregion
@@ -50,7 +50,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Job Queue Job Id"); throw new Exception("Invalid Job Queue Job Id");
} }
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
return Redirect(string.Format("{0}#jobDetailTab-Queues", Url.Action(MVC.Job.Show(jobQueueJob.JobId)))); return Redirect($"{Url.Action(MVC.Job.Show(jobQueueJob.JobId))}#jobDetailTab-Queues");
else else
return Json("OK", JsonRequestBehavior.AllowGet); return Json("OK", JsonRequestBehavior.AllowGet);
} }
@@ -59,7 +59,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -104,7 +104,7 @@ namespace Disco.Web.Areas.API.Controllers
throw new Exception("Invalid Job Queue Job Id"); throw new Exception("Invalid Job Queue Job Id");
} }
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
return Redirect(string.Format("{0}#jobDetailTab-Queues", Url.Action(MVC.Job.Show(jobQueueJob.JobId)))); return Redirect($"{Url.Action(MVC.Job.Show(jobQueueJob.JobId))}#jobDetailTab-Queues");
else else
return Json("OK", JsonRequestBehavior.AllowGet); return Json("OK", JsonRequestBehavior.AllowGet);
} }
@@ -113,7 +113,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
#endregion #endregion
@@ -195,7 +195,7 @@ namespace Disco.Web.Areas.API.Controllers
var jobQueueJob = job.OnAddQueue(Database, jobQueueToken.JobQueue, CurrentUser, Comment, SLAExpires, Priority); var jobQueueJob = job.OnAddQueue(Database, jobQueueToken.JobQueue, CurrentUser, Comment, SLAExpires, Priority);
Database.SaveChanges(); Database.SaveChanges();
return Redirect(string.Format("{0}#jobDetailTab-Queues", Url.Action(MVC.Job.Show(job.Id)))); return Redirect($"{Url.Action(MVC.Job.Show(job.Id))}#jobDetailTab-Queues");
} }
[DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyQueues, Claims.Job.Actions.RemoveOwnQueues)] [DiscoAuthorizeAny(Claims.Job.Actions.RemoveAnyQueues, Claims.Job.Actions.RemoveOwnQueues)]
@@ -223,7 +223,7 @@ namespace Disco.Web.Areas.API.Controllers
Database.SaveChanges(); Database.SaveChanges();
} }
return Redirect(string.Format("{0}#jobDetailTab-Queues", Url.Action(MVC.Job.Show(job.Id)))); return Redirect($"{Url.Action(MVC.Job.Show(job.Id))}#jobDetailTab-Queues");
} }
#endregion #endregion
@@ -85,7 +85,7 @@ namespace Disco.Web.Areas.API.Controllers
if (Plugins.PluginInstalled(libraryItem.Id)) if (Plugins.PluginInstalled(libraryItem.Id))
throw new InvalidOperationException("This plugin is already installed"); throw new InvalidOperationException("This plugin is already installed");
var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, string.Format("{0}.discoPlugin", libraryItem.Id)); var tempPluginLocation = Path.Combine(Database.DiscoConfiguration.PluginPackagesLocation, $"{libraryItem.Id}.discoPlugin");
var status = InstallPluginTask.InstallPlugin(libraryItem.LatestCompatibleRelease(libraryIncompatibility).DownloadUrl, tempPluginLocation, true); var status = InstallPluginTask.InstallPlugin(libraryItem.LatestCompatibleRelease(libraryIncompatibility).DownloadUrl, tempPluginLocation, true);
@@ -275,7 +275,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -75,7 +75,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -131,7 +131,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
[DiscoAuthorize(Claims.Config.UserFlag.Configure)] [DiscoAuthorize(Claims.Config.UserFlag.Configure)]
@@ -174,7 +174,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
[DiscoAuthorize(Claims.Config.UserFlag.Configure)] [DiscoAuthorize(Claims.Config.UserFlag.Configure)]
@@ -207,7 +207,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect) if (redirect)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
#endregion #endregion
@@ -371,7 +371,7 @@ namespace Disco.Web.Areas.API.Controllers
if (redirect.HasValue && redirect.Value) if (redirect.HasValue && redirect.Value)
throw; throw;
else else
return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet);
} }
} }
@@ -17,7 +17,7 @@ namespace Disco.Web.Areas.API.Models.DeviceModel
Id = dc.Id, Id = dc.Id,
Description = dc.Description, Description = dc.Description,
Cost = dc.Cost.ToString("C"), Cost = dc.Cost.ToString("C"),
JobSubTypes = dc.JobSubTypes.Select(j => string.Format("{0}_{1}", j.JobTypeId, j.Id)).ToList() JobSubTypes = dc.JobSubTypes.Select(j => $"{j.JobTypeId}_{j.Id}").ToList()
}; };
} }
@@ -13,7 +13,7 @@ namespace Disco.Web.Areas.API.Models.DocumentTemplate
return new ImporterUndetectedDataIdLookupModel return new ImporterUndetectedDataIdLookupModel
{ {
value = item.Id, value = item.Id,
label = string.Format("{0} - {1} - {2}", item.Id, item.ComputerName, item.DeviceModelDescription) label = $"{item.Id} - {item.ComputerName} - {item.DeviceModelDescription}"
}; };
} }
public static ImporterUndetectedDataIdLookupModel FromSearchResultItem(JobTableItemModel item) public static ImporterUndetectedDataIdLookupModel FromSearchResultItem(JobTableItemModel item)
@@ -21,7 +21,7 @@ namespace Disco.Web.Areas.API.Models.DocumentTemplate
return new ImporterUndetectedDataIdLookupModel return new ImporterUndetectedDataIdLookupModel
{ {
value = item.JobId.ToString(), value = item.JobId.ToString(),
label = string.Format("{0} ({1}; {2})", item.JobId, item.DeviceSerialNumber, item.UserDisplayName) label = $"{item.JobId} ({item.DeviceSerialNumber}; {item.UserDisplayName})"
}; };
} }
public static ImporterUndetectedDataIdLookupModel FromSearchResultItem(UserSearchResultItem item) public static ImporterUndetectedDataIdLookupModel FromSearchResultItem(UserSearchResultItem item)
@@ -29,7 +29,7 @@ namespace Disco.Web.Areas.API.Models.DocumentTemplate
return new ImporterUndetectedDataIdLookupModel return new ImporterUndetectedDataIdLookupModel
{ {
value = item.Id, value = item.Id,
label = string.Format("{0} - {1}", item.Id, item.DisplayName) label = $"{item.Id} - {item.DisplayName}"
}; };
} }
@@ -15,7 +15,7 @@ namespace Disco.Web.Areas.Config.Models.DeviceModel
public override string ToString() public override string ToString()
{ {
if (string.IsNullOrEmpty(Name)) if (string.IsNullOrEmpty(Name))
return string.Format("{0} {1}", Manufacturer, Model); return $"{Manufacturer} {Model}";
else else
return Name; return Name;
} }
@@ -67,7 +67,7 @@ namespace Disco.Web.Areas.Config.Models.DocumentTemplate
{ {
if (model.Types != null && model.SubTypes != null) if (model.Types != null && model.SubTypes != null)
{ {
var typeId = string.Format("{0}_", model.Types); var typeId = $"{model.Types}_";
model.SubTypes = model.SubTypes.Where(m => model.Types.Contains(m.Substring(0, m.IndexOf("_")))).ToList(); model.SubTypes = model.SubTypes.Where(m => model.Types.Contains(m.Substring(0, m.IndexOf("_")))).ToList();
} }
} }
@@ -70,7 +70,7 @@ namespace Disco.Web.Areas.Config.Models.JobPreferences
var current = LongRunningJobDaysThreshold; var current = LongRunningJobDaysThreshold;
if (!options.Any(o => o.Key == current)) if (!options.Any(o => o.Key == current))
{ {
options.Add(new KeyValuePair<int, string>(current, string.Format("{0} Days", current))); options.Add(new KeyValuePair<int, string>(current, $"{current} Days"));
options = options.OrderBy(o => o.Key).ToList(); options = options.OrderBy(o => o.Key).ToList();
} }
@@ -106,7 +106,7 @@ namespace Disco.Web.Areas.Config.Models.JobPreferences
var current = StaleJobMinutesThreshold; var current = StaleJobMinutesThreshold;
if (!options.Any(o => o.Key == current)) if (!options.Any(o => o.Key == current))
{ {
options.Add(new KeyValuePair<int, string>(current, string.Format("{0} Minutes", current))); options.Add(new KeyValuePair<int, string>(current, $"{current} Minutes"));
options = options.OrderBy(o => o.Key).ToList(); options = options.OrderBy(o => o.Key).ToList();
} }
@@ -87,7 +87,7 @@ namespace Disco.Web.Areas.Services.Controllers
} }
} }
} }
throw new MissingMethodException(string.Format("Unknown Feature: {0}", feature)); throw new MissingMethodException($"Unknown Feature: {feature}");
} }
[Authorize] [Authorize]
@@ -136,7 +136,7 @@ namespace Disco.Web.Areas.Services.Controllers
return Json(enrolResponse); return Json(enrolResponse);
} }
} }
throw new MissingMethodException(string.Format("Unknown Feature: {0}", feature)); throw new MissingMethodException($"Unknown Feature: {feature}");
} }
public virtual ActionResult ClientError(string SessionId, string DeviceIdentifier, string JsonException) public virtual ActionResult ClientError(string SessionId, string DeviceIdentifier, string JsonException)
+1 -1
View File
@@ -240,7 +240,7 @@ namespace Disco.Web.Controllers
.FirstOrDefault(d => d.SerialNumber == id); .FirstOrDefault(d => d.SerialNumber == id);
if (m.Device == null) if (m.Device == null)
throw new ArgumentException(string.Format("Unknown Device: [{0}]", id), "id"); throw new ArgumentException($"Unknown Device: [{id}]", "id");
// No Necessary - Yet... // No Necessary - Yet...
//if (!string.IsNullOrWhiteSpace(m.Device.ComputerName)) //if (!string.IsNullOrWhiteSpace(m.Device.ComputerName))
@@ -150,11 +150,11 @@ namespace Disco.Web.Controllers
if (sqlException != null) if (sqlException != null)
{ {
ModelState.AddModelError(string.Empty, string.Format("Unable to create or migrate the database to the latest version: [{0}] {1}", sqlException.GetType().Name, sqlException.Message)); ModelState.AddModelError(string.Empty, $"Unable to create or migrate the database to the latest version: [{sqlException.GetType().Name}] {sqlException.Message}");
} }
else else
{ {
ModelState.AddModelError(string.Empty, string.Format("Unable to create or migrate the database to the latest version: [{0}] {1}", innermostException.GetType().Name, innermostException.Message)); ModelState.AddModelError(string.Empty, $"Unable to create or migrate the database to the latest version: [{innermostException.GetType().Name}] {innermostException.Message}");
} }
} }
@@ -232,7 +232,7 @@ namespace Disco.Web.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
ModelState.AddModelError(string.Empty, string.Format("Unable to extract File Store template: [{0}] {1}", ex.GetType().Name, ex.Message)); ModelState.AddModelError(string.Empty, $"Unable to extract File Store template: [{ex.GetType().Name}] {ex.Message}");
} }
} }
@@ -313,7 +313,7 @@ namespace Disco.Web.Controllers
var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList(); var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList();
if (invalidSubjects.Count > 0) if (invalidSubjects.Count > 0)
throw new ArgumentException(string.Format("Subjects not found: {0}", string.Join(", ", invalidSubjects)), "Subjects"); throw new ArgumentException($"Subjects not found: {string.Join(", ", invalidSubjects)}", "Subjects");
proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray(); proposedSubjects = subjects.Select(s => s.Item2.Id).OrderBy(s => s).ToArray();
var currentSubjects = UserService.AdministratorSubjectIds; var currentSubjects = UserService.AdministratorSubjectIds;
+6 -6
View File
@@ -69,7 +69,7 @@ namespace Disco.Web.Controllers
if (queueToken == null) if (queueToken == null)
throw new ArgumentException("Invalid Job Queue Id", "id"); throw new ArgumentException("Invalid Job Queue Id", "id");
var m = new Models.Job.ListModel() { Title = string.Format("Queue: {0}", queueToken.JobQueue.Name) }; var m = new Models.Job.ListModel() { Title = $"Queue: {queueToken.JobQueue.Name}" };
m.JobTable = ManagedJobList.OpenJobsTable(q => q.Where(j => j.ActiveJobQueues.Any(jqj => jqj.QueueId == queueToken.JobQueue.Id))); m.JobTable = ManagedJobList.OpenJobsTable(q => q.Where(j => j.ActiveJobQueues.Any(jqj => jqj.QueueId == queueToken.JobQueue.Id)));
// UI Extensions // UI Extensions
@@ -326,7 +326,7 @@ namespace Disco.Web.Controllers
.FirstOrDefault(j => j.Id == id.Value); .FirstOrDefault(j => j.Id == id.Value);
if (m.Job == null) if (m.Job == null)
throw new ArgumentException(string.Format("Unknown Job: [{0}]", id), "id"); throw new ArgumentException($"Unknown Job: [{id}]", "id");
// Validate Authorization // Validate Authorization
switch (m.Job.JobTypeId) switch (m.Job.JobTypeId)
@@ -695,14 +695,14 @@ namespace Disco.Web.Controllers
else else
{ {
model.JobDetailsSupported = false; model.JobDetailsSupported = false;
model.JobDetailsNotSupportedMessage = string.Format("Plugin '{0} ({1})' (Warranty Provider for '{2}') doesn't support Job Details", providerInstance.Manifest.Name, providerInstance.Manifest.Id, providerInstance.WarrantyProviderId); model.JobDetailsNotSupportedMessage = $"Plugin '{providerInstance.Manifest.Name} ({providerInstance.Manifest.Id})' (Warranty Provider for '{providerInstance.WarrantyProviderId}') doesn't support Job Details";
return View(model); return View(model);
} }
} }
} }
model.JobDetailsSupported = false; model.JobDetailsSupported = false;
model.JobDetailsNotSupportedMessage = string.Format("Warranty Provider '{0}' is not integrated with Disco ICT", job.JobMetaWarranty.ExternalName); model.JobDetailsNotSupportedMessage = $"Warranty Provider '{job.JobMetaWarranty.ExternalName}' is not integrated with Disco ICT";
return View(model); return View(model);
} }
else else
@@ -874,14 +874,14 @@ namespace Disco.Web.Controllers
else else
{ {
model.JobDetailsSupported = false; model.JobDetailsSupported = false;
model.JobDetailsNotSupportedMessage = string.Format("Plugin '{0} ({1})' (Repair Provider for '{2}') doesn't support Job Details", providerInstance.Manifest.Name, providerInstance.Manifest.Id, providerInstance.ProviderId); model.JobDetailsNotSupportedMessage = $"Plugin '{providerInstance.Manifest.Name} ({providerInstance.Manifest.Id})' (Repair Provider for '{providerInstance.ProviderId}') doesn't support Job Details";
return View(model); return View(model);
} }
} }
} }
model.JobDetailsSupported = false; model.JobDetailsSupported = false;
model.JobDetailsNotSupportedMessage = string.Format("Repair Provider '{0}' is not integrated with Disco ICT", job.JobMetaNonWarranty.RepairerName); model.JobDetailsNotSupportedMessage = $"Repair Provider '{job.JobMetaNonWarranty.RepairerName}' is not integrated with Disco ICT";
return View(model); return View(model);
} }
else else

Some files were not shown because too many files have changed in this diff Show More