diff --git a/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs b/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs index 6550219a..88840746 100644 --- a/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs +++ b/Disco.BI/BI/Interop/Pdf/PdfGenerator.cs @@ -397,7 +397,7 @@ namespace Disco.BI.Interop.Pdf TechUserId = CreatorUser.UserId, 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); } diff --git a/Disco.Client/Presentation.cs b/Disco.Client/Presentation.cs index c0ddc7e4..3440e17a 100644 --- a/Disco.Client/Presentation.cs +++ b/Disco.Client/Presentation.cs @@ -26,7 +26,7 @@ namespace Disco.Client } 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) { @@ -90,7 +90,7 @@ namespace Disco.Client 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 { diff --git a/Disco.ClientBootstrapper/BootstrapperLoop.cs b/Disco.ClientBootstrapper/BootstrapperLoop.cs index 0e7359e3..e3777408 100644 --- a/Disco.ClientBootstrapper/BootstrapperLoop.cs +++ b/Disco.ClientBootstrapper/BootstrapperLoop.cs @@ -217,11 +217,11 @@ namespace Disco.ClientBootstrapper { if (na.IsWireless) { - info.AppendLine(string.Format("{0}: {1}", na.NetConnectionID, na.WirelessConnectionStatusMeaning(na.WirelessConnectionStatus))); + info.AppendLine($"{na.NetConnectionID}: {na.WirelessConnectionStatusMeaning(na.WirelessConnectionStatus)}"); } 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()); @@ -232,7 +232,7 @@ namespace Disco.ClientBootstrapper { 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[] { ',' }); switch (e.Data[0]) { diff --git a/Disco.ClientBootstrapper/FormStatus.cs b/Disco.ClientBootstrapper/FormStatus.cs index ecc91f78..d5a71245 100644 --- a/Disco.ClientBootstrapper/FormStatus.cs +++ b/Disco.ClientBootstrapper/FormStatus.cs @@ -14,7 +14,7 @@ namespace Disco.ClientBootstrapper InitializeComponent(); 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); diff --git a/Disco.ClientBootstrapper/Interop/CertificateInterop.cs b/Disco.ClientBootstrapper/Interop/CertificateInterop.cs index 6986eb7f..822b91cb 100644 --- a/Disco.ClientBootstrapper/Interop/CertificateInterop.cs +++ b/Disco.ClientBootstrapper/Interop/CertificateInterop.cs @@ -41,7 +41,7 @@ namespace Disco.ClientBootstrapper.Interop { if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) _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); } } @@ -66,7 +66,7 @@ namespace Disco.ClientBootstrapper.Interop { if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) _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); } } @@ -91,7 +91,7 @@ namespace Disco.ClientBootstrapper.Interop { if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) _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); } } diff --git a/Disco.ClientBootstrapper/Interop/InstallInterop.cs b/Disco.ClientBootstrapper/Interop/InstallInterop.cs index 9e37c1c9..db328475 100644 --- a/Disco.ClientBootstrapper/Interop/InstallInterop.cs +++ b/Disco.ClientBootstrapper/Interop/InstallInterop.cs @@ -105,7 +105,7 @@ namespace Disco.ClientBootstrapper.Interop { 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(); } } @@ -193,7 +193,7 @@ namespace Disco.ClientBootstrapper.Interop if (InstallLocation.EndsWith(".wim", StringComparison.OrdinalIgnoreCase)) { // 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); // Mount WIM @@ -204,7 +204,7 @@ namespace Disco.ClientBootstrapper.Interop WimImageId = "1"; 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); 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)) { 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); break; } @@ -224,7 +224,7 @@ namespace Disco.ClientBootstrapper.Interop } 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); return; } @@ -245,7 +245,7 @@ namespace Disco.ClientBootstrapper.Interop try { // 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); m_MessageCallback = new WIMInterop.WindowsImageContainer.NativeMethods.MessageCallback(WimImageEventMessagePump); Interop.WIMInterop.WindowsImageContainer.NativeMethods.RegisterCallback(m_MessageCallback); @@ -254,7 +254,7 @@ namespace Disco.ClientBootstrapper.Interop // Load Local Machine Registry 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); using (var wimReg = new RegistryInterop(RegistryInterop.RegistryHives.HKEY_LOCAL_MACHINE, "DiscoClientBootstrapperWimHive", wimHivePath)) { @@ -268,7 +268,7 @@ namespace Disco.ClientBootstrapper.Interop } // 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); wimReg.Unload(); } @@ -281,7 +281,7 @@ namespace Disco.ClientBootstrapper.Interop finally { // 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); Interop.WIMInterop.WindowsImageContainer.NativeMethods.DismountImage(wimMountPath, InstallLocation, wimImageIndex, wimCommitChanges); @@ -300,7 +300,7 @@ namespace Disco.ClientBootstrapper.Interop else { // 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); string rootFileSystemLocation = Path.GetPathRoot(InstallLocation); RegistryKey rootRegistryLocation = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); @@ -339,7 +339,7 @@ namespace Disco.ClientBootstrapper.Interop timeRemainingMessage = "Calculating, please wait..."; 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; default: diff --git a/Disco.ClientBootstrapper/Interop/NetworkInterop.cs b/Disco.ClientBootstrapper/Interop/NetworkInterop.cs index 37aa8a04..92251fce 100644 --- a/Disco.ClientBootstrapper/Interop/NetworkInterop.cs +++ b/Disco.ClientBootstrapper/Interop/NetworkInterop.cs @@ -211,12 +211,12 @@ namespace Disco.ClientBootstrapper.Interop { 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); } 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); } } diff --git a/Disco.ClientBootstrapper/Program.cs b/Disco.ClientBootstrapper/Program.cs index 77958c24..ca75c1d5 100644 --- a/Disco.ClientBootstrapper/Program.cs +++ b/Disco.ClientBootstrapper/Program.cs @@ -86,15 +86,15 @@ namespace Disco.ClientBootstrapper { 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(); ErrorMessage.AppendLine(); ErrorMessage.AppendLine(DateTime.Now.ToLongDateString()); ErrorMessage.AppendLine(DateTime.Now.ToLongTimeString()); - ErrorMessage.AppendLine(string.Format("Type: {0}", ex.GetType().FullName)); - ErrorMessage.AppendLine(string.Format("Message: {0}", ex.Message)); - ErrorMessage.AppendLine(string.Format("Source: {0}", ex.Source)); - ErrorMessage.AppendLine(string.Format("Stack: {0}", ex.StackTrace)); + ErrorMessage.AppendLine($"Type: {ex.GetType().FullName}"); + ErrorMessage.AppendLine($"Message: {ex.Message}"); + ErrorMessage.AppendLine($"Source: {ex.Source}"); + ErrorMessage.AppendLine($"Stack: {ex.StackTrace}"); System.IO.File.AppendAllText(AppErrorPath, ErrorMessage.ToString()); } catch (Exception) { } diff --git a/Disco.Data/Repository/DiscoDataSeeder.cs b/Disco.Data/Repository/DiscoDataSeeder.cs index 7447eca8..d96c20f0 100644 --- a/Disco.Data/Repository/DiscoDataSeeder.cs +++ b/Disco.Data/Repository/DiscoDataSeeder.cs @@ -296,7 +296,7 @@ namespace Disco.Data.Repository private static void UpdateDeviceModelDuplicates(this DiscoDataContext Database) { 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) { var primaryModel = duplicateModel.OrderBy(dm => dm.Id).First(); @@ -310,9 +310,9 @@ namespace Disco.Data.Repository if (!redundantModel.Description.EndsWith("** REDUNDANT **")) { 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 - 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(); 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"); if (System.IO.Directory.Exists(userAttachmentsDirectory)) diff --git a/Disco.Data/Repository/DiscoDatabaseConnectionFactory.cs b/Disco.Data/Repository/DiscoDatabaseConnectionFactory.cs index 63cb7829..e3f3a764 100644 --- a/Disco.Data/Repository/DiscoDatabaseConnectionFactory.cs +++ b/Disco.Data/Repository/DiscoDatabaseConnectionFactory.cs @@ -48,7 +48,7 @@ namespace Disco.Data.Repository } 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); } } } diff --git a/Disco.Data/Repository/Monitor/RepositoryMonitor.cs b/Disco.Data/Repository/Monitor/RepositoryMonitor.cs index 726e35a8..85c0d1d5 100644 --- a/Disco.Data/Repository/Monitor/RepositoryMonitor.cs +++ b/Disco.Data/Repository/Monitor/RepositoryMonitor.cs @@ -110,7 +110,7 @@ namespace Disco.Data.Repository.Monitor eventType = RepositoryMonitorEventType.Unchanged; break; 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()); diff --git a/Disco.Models/Repository/Device/Device.cs b/Disco.Models/Repository/Device/Device.cs index 9922ac77..0319be17 100644 --- a/Disco.Models/Repository/Device/Device.cs +++ b/Disco.Models/Repository/Device/Device.cs @@ -73,7 +73,7 @@ namespace Disco.Models.Repository public override string ToString() { if (DeviceModel != null) - return string.Format("{0} - {1}", DeviceModel, SerialNumber); + return $"{DeviceModel} - {SerialNumber}"; else return SerialNumber; } diff --git a/Disco.Models/Repository/Device/DeviceBatch.cs b/Disco.Models/Repository/Device/DeviceBatch.cs index 9775c48c..0aa4e9d6 100644 --- a/Disco.Models/Repository/Device/DeviceBatch.cs +++ b/Disco.Models/Repository/Device/DeviceBatch.cs @@ -55,7 +55,7 @@ namespace Disco.Models.Repository { if (string.IsNullOrWhiteSpace(Name)) { - return string.Format("{0}: {1}", Id, PurchaseDate.ToLongDateString()); + return $"{Id}: {PurchaseDate.ToLongDateString()}"; } return Name; } diff --git a/Disco.Models/Repository/Device/DeviceProfile.cs b/Disco.Models/Repository/Device/DeviceProfile.cs index 4a364ca6..dc870cca 100644 --- a/Disco.Models/Repository/Device/DeviceProfile.cs +++ b/Disco.Models/Repository/Device/DeviceProfile.cs @@ -52,7 +52,7 @@ namespace Disco.Models.Repository { return Name; } - return string.Format("{0} ({1})", Name, ShortName); + return $"{Name} ({ShortName})"; } [StringLength(200)] diff --git a/Disco.Models/Repository/User/Flag/UserFlagAssignment.cs b/Disco.Models/Repository/User/Flag/UserFlagAssignment.cs index a0710bc2..107e0c03 100644 --- a/Disco.Models/Repository/User/Flag/UserFlagAssignment.cs +++ b/Disco.Models/Repository/User/Flag/UserFlagAssignment.cs @@ -38,7 +38,7 @@ namespace Disco.Models.Repository 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}"; } } } \ No newline at end of file diff --git a/Disco.Models/Services/Searching/DeviceSearchResultItem.cs b/Disco.Models/Services/Searching/DeviceSearchResultItem.cs index 79d7afc3..b19b69ca 100644 --- a/Disco.Models/Services/Searching/DeviceSearchResultItem.cs +++ b/Disco.Models/Services/Searching/DeviceSearchResultItem.cs @@ -16,7 +16,7 @@ namespace Disco.Models.Services.Searching public string Id { get; set; } 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 AssetNumber { get; set; } @@ -27,7 +27,7 @@ namespace Disco.Models.Services.Searching if (AssignedUserId != null) { if (AssignedUserDisplayName != null) - return string.Format("{0} ({1})", AssignedUserDisplayName, AssignedUserId); + return $"{AssignedUserDisplayName} ({AssignedUserId})"; else return AssignedUserId; } diff --git a/Disco.Models/Services/Searching/JobSearchResultItem.cs b/Disco.Models/Services/Searching/JobSearchResultItem.cs index 054efa19..74f6db4a 100644 --- a/Disco.Models/Services/Searching/JobSearchResultItem.cs +++ b/Disco.Models/Services/Searching/JobSearchResultItem.cs @@ -14,7 +14,7 @@ namespace Disco.Models.Services.Searching public virtual string Id { get; set; } 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 DeviceSerialNumber { get; set; } diff --git a/Disco.Models/Services/Searching/UserSearchResultItem.cs b/Disco.Models/Services/Searching/UserSearchResultItem.cs index 8410eb8d..9da276d0 100644 --- a/Disco.Models/Services/Searching/UserSearchResultItem.cs +++ b/Disco.Models/Services/Searching/UserSearchResultItem.cs @@ -17,7 +17,7 @@ namespace Disco.Models.Services.Searching public string Id { get; set; } public string FriendlyId { get; set; } 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 DisplayName { get; set; } diff --git a/Disco.Services.Plugins.ManifestGenerator/Program.cs b/Disco.Services.Plugins.ManifestGenerator/Program.cs index 9b29680d..9ec0db54 100644 --- a/Disco.Services.Plugins.ManifestGenerator/Program.cs +++ b/Disco.Services.Plugins.ManifestGenerator/Program.cs @@ -101,7 +101,7 @@ namespace Disco.Services.Plugins.ManifestGenerator 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()) { @@ -114,7 +114,7 @@ namespace Disco.Services.Plugins.ManifestGenerator 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 excludedFiles) diff --git a/Disco.Services/Authorization/AuthorizationToken.cs b/Disco.Services/Authorization/AuthorizationToken.cs index 677a6ab6..4f96db29 100644 --- a/Disco.Services/Authorization/AuthorizationToken.cs +++ b/Disco.Services/Authorization/AuthorizationToken.cs @@ -169,9 +169,9 @@ namespace Disco.Services.Authorization filename = filename.Substring(filename.IndexOf("\\Disco\\Disco.") + 7); 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)) - resource = string.Format("{0} [{1}]", resource, filename); + resource = $"{resource} [{filename}]"; return resource; } diff --git a/Disco.Services/Authorization/ClaimNavigatorItem.cs b/Disco.Services/Authorization/ClaimNavigatorItem.cs index 3f3cec81..cbdd823a 100644 --- a/Disco.Services/Authorization/ClaimNavigatorItem.cs +++ b/Disco.Services/Authorization/ClaimNavigatorItem.cs @@ -76,7 +76,7 @@ namespace Disco.Services.Authorization public override string ToString() { - return string.Format("{0}: {1}={2}", Name, Key, Value); + return $"{Name}: {Key}={Value}"; } } } diff --git a/Disco.Services/Authorization/DiscoAuthorizeBaseAttribute.cs b/Disco.Services/Authorization/DiscoAuthorizeBaseAttribute.cs index c27a1f69..d6311790 100644 --- a/Disco.Services/Authorization/DiscoAuthorizeBaseAttribute.cs +++ b/Disco.Services/Authorization/DiscoAuthorizeBaseAttribute.cs @@ -65,10 +65,10 @@ namespace Disco.Services.Authorization var controllerName = FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName; 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}]"; } } } diff --git a/Disco.Services/Devices/DeviceActionExtensions.cs b/Disco.Services/Devices/DeviceActionExtensions.cs index 387ed356..341cabe7 100644 --- a/Disco.Services/Devices/DeviceActionExtensions.cs +++ b/Disco.Services/Devices/DeviceActionExtensions.cs @@ -156,7 +156,7 @@ namespace Disco.Services if (j.CanDelete()) j.OnDelete(Database); 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 { @@ -169,8 +169,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = UserService.CurrentUser.UserId, Timestamp = DateTime.Now, - Comments = string.Format("# Device Deleted\r\n\r\nSerial Number: **{0}**\r\nComputer Name: **{1}**\r\nModel: **{2}**\r\nProfile: **{3}**", - d.SerialNumber, d.DeviceDomainId, d.DeviceModel, d.DeviceProfile) + Comments = $"# Device Deleted\r\n\r\nSerial Number: **{d.SerialNumber}**\r\nComputer Name: **{d.DeviceDomainId}**\r\nModel: **{d.DeviceModel}**\r\nProfile: **{d.DeviceProfile}**" }; Database.JobLogs.Add(jobLog); } diff --git a/Disco.Services/Devices/DeviceDataStoreExtensions.cs b/Disco.Services/Devices/DeviceDataStoreExtensions.cs index 4ca6e3f9..98eb6e98 100644 --- a/Disco.Services/Devices/DeviceDataStoreExtensions.cs +++ b/Disco.Services/Devices/DeviceDataStoreExtensions.cs @@ -55,7 +55,7 @@ namespace Disco.Services 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) diff --git a/Disco.Services/Devices/DeviceExtensions.cs b/Disco.Services/Devices/DeviceExtensions.cs index edf784fb..12a2f163 100644 --- a/Disco.Services/Devices/DeviceExtensions.cs +++ b/Disco.Services/Devices/DeviceExtensions.cs @@ -32,14 +32,14 @@ namespace Disco.Services } 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) { 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 AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, DateTime TimeStamp) { @@ -250,7 +250,7 @@ namespace Disco.Services public static string Status(this Device Device) { if (Device.DecommissionedDate.HasValue) - return string.Format("Decommissioned ({0})", Device.DecommissionReason.ReasonMessage()); + return $"Decommissioned ({Device.DecommissionReason.ReasonMessage()})"; if (!Device.EnrolledDate.HasValue) return "Not Enrolled"; diff --git a/Disco.Services/Devices/DeviceFlags/DeviceFlagsBulkAssignTask.cs b/Disco.Services/Devices/DeviceFlags/DeviceFlagsBulkAssignTask.cs index ab6a54c5..e0ba6f63 100644 --- a/Disco.Services/Devices/DeviceFlags/DeviceFlagsBulkAssignTask.cs +++ b/Disco.Services/Devices/DeviceFlags/DeviceFlagsBulkAssignTask.cs @@ -32,7 +32,7 @@ namespace Disco.Services.Devices.DeviceFlags if (flag == null) 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 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(); 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(); diff --git a/Disco.Services/Devices/Enrolment/LogMacAddressImportingTask.cs b/Disco.Services/Devices/Enrolment/LogMacAddressImportingTask.cs index ba26f7a0..a222f4ab 100644 --- a/Disco.Services/Devices/Enrolment/LogMacAddressImportingTask.cs +++ b/Disco.Services/Devices/Enrolment/LogMacAddressImportingTask.cs @@ -81,14 +81,14 @@ namespace Disco.Services.Devices.Enrolment }; var results = logRetriever.Query(database); - Status.UpdateStatus(50, string.Format("Passing {0} logs", results.Count)); + Status.UpdateStatus(50, $"Passing {results.Count} logs"); Dictionary> addresses = new Dictionary>(); foreach (var result in results.OrderBy(r => r.Timestamp)) addresses[((string)result.Arguments[1]).ToLower()] = new Tuple((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(); diff --git a/Disco.Services/Devices/Importing/DeviceImport.cs b/Disco.Services/Devices/Importing/DeviceImport.cs index 440d6f35..e80bbc38 100644 --- a/Disco.Services/Devices/Importing/DeviceImport.cs +++ b/Disco.Services/Devices/Importing/DeviceImport.cs @@ -118,7 +118,7 @@ namespace Disco.Services.Devices.Importing { 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; if (DeviceSerialNumberImportField.IsDeviceSerialNumberValid(deviceSerialNumber)) diff --git a/Disco.Services/Documents/AttachmentImport/Importer.cs b/Disco.Services/Documents/AttachmentImport/Importer.cs index 0c1f27b1..4d7bc3cc 100644 --- a/Disco.Services/Documents/AttachmentImport/Importer.cs +++ b/Disco.Services/Documents/AttachmentImport/Importer.cs @@ -22,7 +22,7 @@ namespace Disco.Services.Documents.AttachmentImport 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); } @@ -135,7 +135,7 @@ namespace Disco.Services.Documents.AttachmentImport 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()) { diff --git a/Disco.Services/Documents/AttachmentImport/ImporterJob.cs b/Disco.Services/Documents/AttachmentImport/ImporterJob.cs index 9cf7848a..bf658f80 100644 --- a/Disco.Services/Documents/AttachmentImport/ImporterJob.cs +++ b/Disco.Services/Documents/AttachmentImport/ImporterJob.cs @@ -52,7 +52,7 @@ namespace Disco.Services.Documents.AttachmentImport if (retryCount < 18) { 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 var trig = new SimpleTriggerImpl(Guid.NewGuid().ToString(), new DateTimeOffset(DateTime.Now.AddSeconds(10))); context.Scheduler.RescheduleJob(context.Trigger.Key, trig); diff --git a/Disco.Services/Interop/ActiveDirectory/ADDomain.cs b/Disco.Services/Interop/ActiveDirectory/ADDomain.cs index 0c36d65b..dac88a2d 100644 --- a/Disco.Services/Interop/ActiveDirectory/ADDomain.cs +++ b/Disco.Services/Interop/ActiveDirectory/ADDomain.cs @@ -59,7 +59,7 @@ namespace Disco.Services.Interop.ActiveDirectory var dc = Domain.FindDomainController(); - string ldapPath = string.Format("LDAP://{0}/", dc.Name); + string ldapPath = $"LDAP://{dc.Name}/"; 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)) { - 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)) { @@ -233,7 +233,7 @@ namespace Disco.Services.Interop.ActiveDirectory throw new ArgumentNullException("DistinguishedName"); 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(); @@ -309,12 +309,12 @@ namespace Disco.Services.Interop.ActiveDirectory // Set offline for DomainControllerUnavailableMinutes 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); 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)); } @@ -335,14 +335,14 @@ namespace Disco.Services.Interop.ActiveDirectory { get { - return string.Format("CN=Computers,{0}", DistinguishedName); + return $"CN=Computers,{DistinguishedName}"; } } public string FriendlyDistinguishedNamePath(string DistinguishedName) { 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(); @@ -365,7 +365,7 @@ namespace Disco.Services.Interop.ActiveDirectory public override string ToString() { - return string.Format("{0} [{1}]", Name, NetBiosName); + return $"{Name} [{NetBiosName}]"; } public override bool Equals(object obj) diff --git a/Disco.Services/Interop/ActiveDirectory/ADDomainController.cs b/Disco.Services/Interop/ActiveDirectory/ADDomainController.cs index a187ac6a..4eca4240 100644 --- a/Disco.Services/Interop/ActiveDirectory/ADDomainController.cs +++ b/Disco.Services/Interop/ActiveDirectory/ADDomainController.cs @@ -65,7 +65,7 @@ namespace Disco.Services.Interop.ActiveDirectory throw new ArgumentNullException("DistinguishedName"); 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))); @@ -225,7 +225,7 @@ namespace Disco.Services.Interop.ActiveDirectory if (SecurityIdentifier == null) throw new ArgumentNullException("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(); @@ -373,12 +373,12 @@ namespace Disco.Services.Interop.ActiveDirectory using (var deOU = RetrieveDirectoryEntry(OrganisationalUnit, new string[] { "distinguishedName" })) { 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) { - 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); string tempFileName = System.IO.Path.GetTempFileName(); - string argumentOU = (!string.IsNullOrWhiteSpace(OrganisationalUnit)) ? string.Format(" /MACHINEOU \"{0}\"", OrganisationalUnit) : string.Empty; - string arguments = string.Format("/PROVISION /DOMAIN \"{0}\" /DCNAME \"{1}\" /MACHINE \"{2}\"{3} /REUSE /SAVEFILE \"{4}\"", - Domain.Name, - Name, - ComputerSamAccountName, - argumentOU, - tempFileName - ); + string argumentOU = (!string.IsNullOrWhiteSpace(OrganisationalUnit)) ? $" /MACHINEOU \"{OrganisationalUnit}\"" : string.Empty; + string arguments = $"/PROVISION /DOMAIN \"{Domain.Name}\" /DCNAME \"{Name}\" /MACHINE \"{ComputerSamAccountName}\"{argumentOU} /REUSE /SAVEFILE \"{tempFileName}\""; ProcessStartInfo commandStarter = new ProcessStartInfo("DJOIN.EXE", arguments) { CreateNoWindow = true, @@ -403,7 +397,7 @@ namespace Disco.Services.Interop.ActiveDirectory RedirectStandardError = true, UseShellExecute = false }; - diagnosticInfo.AppendFormat("{0} {1}", "DJOIN.EXE", arguments); + diagnosticInfo.AppendFormat($"DJOIN.EXE {arguments}"); diagnosticInfo.AppendLine(); string stdOutput; diff --git a/Disco.Services/Interop/ActiveDirectory/ADGroup.cs b/Disco.Services/Interop/ActiveDirectory/ADGroup.cs index 160f7bba..caba8ea0 100644 --- a/Disco.Services/Interop/ActiveDirectory/ADGroup.cs +++ b/Disco.Services/Interop/ActiveDirectory/ADGroup.cs @@ -17,7 +17,7 @@ namespace Disco.Services.Interop.ActiveDirectory public string DistinguishedName { 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 Name { get; private set; } diff --git a/Disco.Services/Interop/ActiveDirectory/ADMachineAccount.cs b/Disco.Services/Interop/ActiveDirectory/ADMachineAccount.cs index 5b05aedf..91927144 100644 --- a/Disco.Services/Interop/ActiveDirectory/ADMachineAccount.cs +++ b/Disco.Services/Interop/ActiveDirectory/ADMachineAccount.cs @@ -73,7 +73,7 @@ namespace Disco.Services.Interop.ActiveDirectory var dNSName = SearchResult.Value("dNSHostName"); if (dNSName == null) - dNSName = string.Format("{0}.{1}", sAMAccountName.TrimEnd('$'), SearchResult.Domain.Name); + dNSName = $"{sAMAccountName.TrimEnd('$')}.{SearchResult.Domain.Name}"; var userAccountControl = (ADUserAccountControlFlags)SearchResult.Value("userAccountControl"); var isCriticalSystemObject = SearchResult.Value("isCriticalSystemObject"); @@ -123,7 +123,7 @@ namespace Disco.Services.Interop.ActiveDirectory var dNSName = properties.Value("dNSHostName"); if (dNSName == null) - dNSName = string.Format("{0}.{1}", sAMAccountName.TrimEnd('$'), directoryEntry.Domain.Name); + dNSName = $"{sAMAccountName.TrimEnd('$')}.{directoryEntry.Domain.Name}"; var userAccountControl = (ADUserAccountControlFlags)properties.Value("userAccountControl"); var isCriticalSystemObject = properties.Value("isCriticalSystemObject"); @@ -208,10 +208,10 @@ namespace Disco.Services.Interop.ActiveDirectory public void DeleteAccount(ADDomainController WritableDomainController) { 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) - 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)) { @@ -226,7 +226,7 @@ namespace Disco.Services.Interop.ActiveDirectory private void SetNetbootGUID(ADDomainController WritableDomainController, Guid updatedNetbootGUID) { 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) { @@ -247,7 +247,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void SetDescription(ADDomainController WritableDomainController, string Description) { 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) { @@ -320,7 +320,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void DisableAccount(ADDomainController WritableDomainController) { 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) { @@ -348,7 +348,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void EnableAccount(ADDomainController WritableDomainController) { 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) { @@ -376,7 +376,7 @@ namespace Disco.Services.Interop.ActiveDirectory public bool UpdateNetbootGUID(ADDomainController WritableDomainController, string UUID, string MACAddress) { 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; @@ -414,7 +414,7 @@ namespace Disco.Services.Interop.ActiveDirectory Guid NetbootGUIDFromMACAddress; 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; } else @@ -427,7 +427,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void MoveOrganisationalUnit(ADDomainController WritableDomainController, string NewOrganisationUnit) { 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; @@ -438,7 +438,7 @@ namespace Disco.Services.Interop.ActiveDirectory NewOrganisationUnit = Domain.DefaultComputerContainer; 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)) { diff --git a/Disco.Services/Interop/ActiveDirectory/ADManagedGroupsSyncTask.cs b/Disco.Services/Interop/ActiveDirectory/ADManagedGroupsSyncTask.cs index f2ead91f..e967b8c1 100644 --- a/Disco.Services/Interop/ActiveDirectory/ADManagedGroupsSyncTask.cs +++ b/Disco.Services/Interop/ActiveDirectory/ADManagedGroupsSyncTask.cs @@ -35,7 +35,7 @@ namespace Disco.Services.Interop.ActiveDirectory changeCount = ActiveDirectory.Context.ManagedGroups.SyncManagedGroups(managedGroups, Status); 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) diff --git a/Disco.Services/Interop/ActiveDirectory/ADNetworkLogonDatesUpdateTask.cs b/Disco.Services/Interop/ActiveDirectory/ADNetworkLogonDatesUpdateTask.cs index ad966358..e5d1f9fe 100644 --- a/Disco.Services/Interop/ActiveDirectory/ADNetworkLogonDatesUpdateTask.cs +++ b/Disco.Services/Interop/ActiveDirectory/ADNetworkLogonDatesUpdateTask.cs @@ -33,7 +33,7 @@ namespace Disco.Services.Interop.ActiveDirectory UpdateLastNetworkLogonDates(database, Status); Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database"); 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"); @@ -144,7 +144,7 @@ namespace Disco.Services.Interop.ActiveDirectory // Update Status 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 var directoryResults = domainController.SearchInternal(searchRoot, ldapFilter, ldapProperties, null); @@ -163,7 +163,7 @@ namespace Disco.Services.Interop.ActiveDirectory 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); return Tuple.Create(computerName, lastLogon); } diff --git a/Disco.Services/Interop/ActiveDirectory/ADUserAccount.cs b/Disco.Services/Interop/ActiveDirectory/ADUserAccount.cs index 475f8f94..1c79b39a 100644 --- a/Disco.Services/Interop/ActiveDirectory/ADUserAccount.cs +++ b/Disco.Services/Interop/ActiveDirectory/ADUserAccount.cs @@ -19,7 +19,7 @@ namespace Disco.Services.Interop.ActiveDirectory public string DistinguishedName { 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 Name { get; private set; } @@ -250,10 +250,10 @@ namespace Disco.Services.Interop.ActiveDirectory public void DeleteAccount(ADDomainController WritableDomainController) { 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) - 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)) { @@ -268,7 +268,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void DisableAccount(ADDomainController WritableDomainController) { 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) { @@ -296,7 +296,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void EnableAccount(ADDomainController WritableDomainController) { 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) { @@ -324,7 +324,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void SetDisplayName(ADDomainController WritableDomainController, string DisplayName) { 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) { @@ -357,7 +357,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void SetSurname(ADDomainController WritableDomainController, string Surname) { 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) { @@ -390,7 +390,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void SetGivenName(ADDomainController WritableDomainController, string GivenName) { 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) { @@ -423,7 +423,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void SetEmail(ADDomainController WritableDomainController, string Email) { 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) { @@ -456,7 +456,7 @@ namespace Disco.Services.Interop.ActiveDirectory public void SetPhone(ADDomainController WritableDomainController, string Phone) { 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) { diff --git a/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryContext.cs b/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryContext.cs index e04621f2..8392fae7 100644 --- a/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryContext.cs +++ b/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryContext.cs @@ -139,7 +139,7 @@ namespace Disco.Services.Interop.ActiveDirectory { ADDomain 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; } @@ -152,7 +152,7 @@ namespace Disco.Services.Interop.ActiveDirectory { ADDomain 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; } @@ -165,7 +165,7 @@ namespace Disco.Services.Interop.ActiveDirectory { ADDomain 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; } @@ -178,7 +178,7 @@ namespace Disco.Services.Interop.ActiveDirectory { ADDomain 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; } @@ -190,7 +190,7 @@ namespace Disco.Services.Interop.ActiveDirectory var slashIndex = Id.IndexOf('\\'); 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); } @@ -202,7 +202,7 @@ namespace Disco.Services.Interop.ActiveDirectory var slashIndex = Id.IndexOf('\\'); 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)); } diff --git a/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryManagedGroups.cs b/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryManagedGroups.cs index 37168053..f2d12de7 100644 --- a/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryManagedGroups.cs +++ b/Disco.Services/Interop/ActiveDirectory/ActiveDirectoryManagedGroups.cs @@ -41,7 +41,7 @@ namespace Disco.Services.Interop.ActiveDirectory .FirstOrDefault(g => g.Configuration.GroupId.Equals(ManagedGroup.Configuration.GroupId, StringComparison.OrdinalIgnoreCase)); 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) => { @@ -93,9 +93,9 @@ namespace Disco.Services.Interop.ActiveDirectory { var group = ActiveDirectory.RetrieveADGroup(GroupId, "isCriticalSystemObject"); 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("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; @@ -103,7 +103,7 @@ namespace Disco.Services.Interop.ActiveDirectory .Where(g => g.Key != IgnoreManagedGroupKey) .FirstOrDefault(g => g.Configuration.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase)); 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; } @@ -160,7 +160,7 @@ namespace Disco.Services.Interop.ActiveDirectory var scopeAccounts = ActiveDirectory.Context.SearchScope("(|(objectCategory=computer)(objectCategory=person))", adSearchLoadProperties); foreach (var scopeAccount in scopeAccounts) { - var id = string.Format(@"{0}\{1}", scopeAccount.Domain.NetBiosName, scopeAccount.Value("sAMAccountName")); + var id = $@"{scopeAccount.Domain.NetBiosName}\{scopeAccount.Value("sAMAccountName")}"; accountDNCache[id] = scopeAccount.Value("distinguishedName"); } } @@ -182,7 +182,7 @@ namespace Disco.Services.Interop.ActiveDirectory 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(); if (adSearchResult != null) @@ -234,7 +234,7 @@ namespace Disco.Services.Interop.ActiveDirectory using (var adGroupEntry = ActiveDirectory.Context.RetrieveDirectoryEntry(adGroup.DistinguishedName, new string[] { "member", "isCriticalSystemObject" })) { if (adGroupEntry.Entry.Properties.Value("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"]; foreach (var item in actionItems) @@ -291,7 +291,7 @@ namespace Disco.Services.Interop.ActiveDirectory { Status.UpdateStatus( ((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( g, g.DetermineMembers(Database).Select(m => @@ -316,7 +316,7 @@ namespace Disco.Services.Interop.ActiveDirectory var scopeAccounts = ActiveDirectory.Context.SearchScope("(|(objectCategory=computer)(objectCategory=person))", adSearchLoadProperties); foreach (var scopeAccount in scopeAccounts) { - var id = string.Format(@"{0}\{1}", scopeAccount.Domain.NetBiosName, scopeAccount.Value("sAMAccountName")); + var id = $@"{scopeAccount.Domain.NetBiosName}\{scopeAccount.Value("sAMAccountName")}"; accountDNCache[id] = Tuple.Create(scopeAccount.Value("distinguishedName"), scopeAccount.Value("displayName") ?? scopeAccount.Value("name")); } } @@ -325,7 +325,7 @@ namespace Disco.Services.Interop.ActiveDirectory { Status.UpdateStatus( 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 // Discard non-existent users @@ -344,7 +344,7 @@ namespace Disco.Services.Interop.ActiveDirectory 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(); if (adSearchResult != null) @@ -379,15 +379,15 @@ namespace Disco.Services.Interop.ActiveDirectory Status.UpdateStatus( 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" })) { if (adGroupEntry.Entry.Properties.Value("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 - var groupDescription = string.Format("Disco ICT: {0}", actionGroup.Item1.GroupDescription); + var groupDescription = $"Disco ICT: {actionGroup.Item1.GroupDescription}"; if (adGroupEntry.Entry.Properties.Value("description") != groupDescription) { var adGroupEntryDescription = adGroupEntry.Entry.Properties["description"]; diff --git a/Disco.Services/Interop/DiscoServices/Jobs.cs b/Disco.Services/Interop/DiscoServices/Jobs.cs index 096e3b2b..80761937 100644 --- a/Disco.Services/Interop/DiscoServices/Jobs.cs +++ b/Disco.Services/Interop/DiscoServices/Jobs.cs @@ -51,15 +51,15 @@ namespace Disco.Services.Interop.DiscoServices .ToList() .ForEach(a => { - formData.Add(new StringContent(a.Attachment.Filename), string.Format("Attachments[{0}].Filename", a.Index)); - formData.Add(new StringContent(a.Attachment.MimeType), string.Format("Attachments[{0}].MimeType", a.Index)); - formData.Add(new StringContent(a.Attachment.Timestamp.ToISO8601()), string.Format("Attachments[{0}].CreatedDate", a.Index)); + formData.Add(new StringContent(a.Attachment.Filename), $"Attachments[{a.Index}].Filename"); + formData.Add(new StringContent(a.Attachment.MimeType), $"Attachments[{a.Index}].MimeType"); + formData.Add(new StringContent(a.Attachment.Timestamp.ToISO8601()), $"Attachments[{a.Index}].CreatedDate"); 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) - 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); }); } diff --git a/Disco.Services/Interop/DiscoServices/PluginLibrary.cs b/Disco.Services/Interop/DiscoServices/PluginLibrary.cs index 85646879..f37a8079 100644 --- a/Disco.Services/Interop/DiscoServices/PluginLibrary.cs +++ b/Disco.Services/Interop/DiscoServices/PluginLibrary.cs @@ -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" }; 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)) - 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; }).Where(i => i != null).ToList() diff --git a/Disco.Services/Interop/DiscoServices/UpdateQuery.cs b/Disco.Services/Interop/DiscoServices/UpdateQuery.cs index 1f1e000d..b8d2e6b0 100644 --- a/Disco.Services/Interop/DiscoServices/UpdateQuery.cs +++ b/Disco.Services/Interop/DiscoServices/UpdateQuery.cs @@ -39,7 +39,7 @@ namespace Disco.Services.Interop.DiscoServices 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) @@ -79,7 +79,7 @@ namespace Disco.Services.Interop.DiscoServices request.ContentType = "application/json; charset=utf-8; encoding=gzip"; request.Method = WebRequestMethods.Http.Post; - request.UserAgent = string.Format("Disco/{0} (Update)", discoVersion); + request.UserAgent = $"Disco/{discoVersion} (Update)"; using (var requestStream = request.GetRequestStream()) { @@ -117,13 +117,13 @@ namespace Disco.Services.Interop.DiscoServices Database.DiscoConfiguration.UpdateLastCheckResponse = updateResult; 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; } 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; } } @@ -216,7 +216,7 @@ namespace Disco.Services.Interop.DiscoServices DeviceIdentifier = HashDeploymentData(Database, j.DeviceSerialNumber), UserIdentifier = HashDeploymentData(Database, j.UserId), 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, RepairerLogged = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairerLoggedDate : j.RepairerLoggedDate, RepairerCompleted = j.JobType == JobType.JobTypeIds.HWar ? j.WarrantyRepairerCompletedDate : j.RepairerCompletedDate diff --git a/Disco.Services/Interop/VicEduDept/VicSmart.cs b/Disco.Services/Interop/VicEduDept/VicSmart.cs index 761ca429..a53289e3 100644 --- a/Disco.Services/Interop/VicEduDept/VicSmart.cs +++ b/Disco.Services/Interop/VicEduDept/VicSmart.cs @@ -59,7 +59,7 @@ namespace Disco.Services.Interop.VicEduDept wReq.Proxy = new WebProxy(); // Empty Proxy Config wReq.Method = WebRequestMethods.Http.Post; 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 wrStreamWriter = new StreamWriter(wrStream)) diff --git a/Disco.Services/Jobs/JobActionExtensions.cs b/Disco.Services/Jobs/JobActionExtensions.cs index 5089ad07..1bf0f8ab 100644 --- a/Disco.Services/Jobs/JobActionExtensions.cs +++ b/Disco.Services/Jobs/JobActionExtensions.cs @@ -135,7 +135,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = Technician.UserId, Timestamp = DateTime.Now, - Comments = string.Format("# Waiting on User Action\r\n{0}", string.IsNullOrWhiteSpace(Reason) ? "" : Reason) + Comments = $"# Waiting on User Action\r\n{(string.IsNullOrWhiteSpace(Reason) ? "" : Reason)}" }; Database.JobLogs.Add(jobLog); } @@ -162,7 +162,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = Technician.UserId, Timestamp = DateTime.Now, - Comments = string.Format("# User Action Resolved\r\n{0}", string.IsNullOrWhiteSpace(Resolution) ? "" : Resolution) + Comments = $"# User Action Resolved\r\n{(string.IsNullOrWhiteSpace(Resolution) ? "" : Resolution)}" }; Database.JobLogs.Add(jobLog); } @@ -238,7 +238,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = TechUser.UserId, 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); @@ -271,7 +271,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = TechUser.UserId, 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 ?? "", FaultDescription) + Comments = $"# Manual Warranty Claim Submitted\r\nProvider: **{ManualProviderName}**\r\nAddress: **{Address.Name}**\r\nReference: **{ManualProviderReference ?? ""}**\r\n___\r\n```{FaultDescription}```" }; Database.JobLogs.Add(jobLog); } @@ -350,7 +350,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = techUser.UserId, 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); @@ -468,7 +468,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = TechUser.UserId, 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); @@ -501,7 +501,7 @@ namespace Disco.Services JobId = j.Id, TechUserId = TechUser.UserId, 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 ?? "", FaultDescription) + Comments = $"# Manual Repair Request Submitted\r\nProvider: **{ManualProviderName}**\r\nAddress: **{Address.Name}**\r\nReference: **{ManualProviderReference ?? ""}**\r\n___\r\n```{FaultDescription}```" }; Database.JobLogs.Add(jobLog); } diff --git a/Disco.Services/Jobs/JobExtensions.cs b/Disco.Services/Jobs/JobExtensions.cs index 756c69aa..141a7ecb 100644 --- a/Disco.Services/Jobs/JobExtensions.cs +++ b/Disco.Services/Jobs/JobExtensions.cs @@ -267,8 +267,7 @@ namespace Disco.Services public static string GenerateFaultDescriptionFooter(this Job j, DiscoDataContext Database, PluginFeatureManifest WarrantyProviderDefinition) { 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})", - versionDisco.Major, versionDisco.Minor, versionDisco.Build, versionDisco.Revision, WarrantyProviderDefinition.Id, WarrantyProviderDefinition.PluginManifest.Version.ToString(4)); + 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)})"; } public static void UpdateSubTypes(this Job j, DiscoDataContext Database, List SubTypes, bool AddComponents, User TechUser) diff --git a/Disco.Services/Jobs/JobLists/ManagedJobList.cs b/Disco.Services/Jobs/JobLists/ManagedJobList.cs index a52f7788..72d8a0d7 100644 --- a/Disco.Services/Jobs/JobLists/ManagedJobList.cs +++ b/Disco.Services/Jobs/JobLists/ManagedJobList.cs @@ -178,7 +178,7 @@ namespace Disco.Services.Jobs.JobLists 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) diff --git a/Disco.Services/Jobs/JobQueues/JobQueueService.cs b/Disco.Services/Jobs/JobQueues/JobQueueService.cs index 5808b34a..9c24c431 100644 --- a/Disco.Services/Jobs/JobQueues/JobQueueService.cs +++ b/Disco.Services/Jobs/JobQueues/JobQueueService.cs @@ -109,7 +109,7 @@ namespace Disco.Services.Jobs.JobQueues throw new InvalidOperationException("The Job Queue cannot be deleted because it contains jobs"); // 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(); if (jobQueueJobs.Count > 0) { @@ -118,7 +118,7 @@ namespace Disco.Services.Jobs.JobQueues { 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 Database.JobLogs.Add(new JobLog() @@ -133,7 +133,7 @@ namespace Disco.Services.Jobs.JobQueues JobId = jqj.JobId, TechUserId = jqj.RemovedUserId, Timestamp = jqj.RemovedDate.Value, - Comments = string.Format("# Removed from Queue\r\n**{0}**\r\n{1}", queue.Name, string.IsNullOrWhiteSpace(jqj.RemovedComment) ? "" : jqj.RemovedComment) + Comments = $"# Removed from Queue\r\n**{queue.Name}**\r\n{(string.IsNullOrWhiteSpace(jqj.RemovedComment) ? "" : jqj.RemovedComment)}" }); // Delete JQJ @@ -152,7 +152,7 @@ namespace Disco.Services.Jobs.JobQueues // Remove from Cache _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 diff --git a/Disco.Services/Logging/LogContext.cs b/Disco.Services/Logging/LogContext.cs index 342f7b20..e8c7d360 100644 --- a/Disco.Services/Logging/LogContext.cs +++ b/Disco.Services/Logging/LogContext.cs @@ -158,7 +158,7 @@ namespace Disco.Services.Logging { 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); } @@ -286,10 +286,10 @@ namespace Disco.Services.Logging } } 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 - throw new InvalidOperationException(string.Format("Unknown Log Module Called: {0}", ModuleId)); + throw new InvalidOperationException($"Unknown Log Module Called: {ModuleId}"); } } diff --git a/Disco.Services/Logging/LogNotificationsHub.cs b/Disco.Services/Logging/LogNotificationsHub.cs index 426425df..1e25918c 100644 --- a/Disco.Services/Logging/LogNotificationsHub.cs +++ b/Disco.Services/Logging/LogNotificationsHub.cs @@ -57,7 +57,7 @@ namespace Disco.Services.Logging var module = LogContext.LogModules.Values.FirstOrDefault(m => m.ModuleName.Equals(name, StringComparison.OrdinalIgnoreCase)); 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; } diff --git a/Disco.Services/Logging/Utilities.cs b/Disco.Services/Logging/Utilities.cs index 1ec15294..25a291cc 100644 --- a/Disco.Services/Logging/Utilities.cs +++ b/Disco.Services/Logging/Utilities.cs @@ -171,7 +171,7 @@ namespace Disco.Services.Logging public static void CompressDirectory(string DirectoryPath) { 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); if (dirInfo.Exists) @@ -192,7 +192,7 @@ namespace Disco.Services.Logging } else { - throw new InvalidOperationException(string.Format("Directory doesn't exist: {0}", DirectoryPath)); + throw new InvalidOperationException($"Directory doesn't exist: {DirectoryPath}"); } } diff --git a/Disco.Services/Plugins/Features/UIExtension/UIExtensions.cs b/Disco.Services/Plugins/Features/UIExtension/UIExtensions.cs index b23a7e55..0d184e7d 100644 --- a/Disco.Services/Plugins/Features/UIExtension/UIExtensions.cs +++ b/Disco.Services/Plugins/Features/UIExtension/UIExtensions.cs @@ -56,10 +56,10 @@ namespace Disco.Services.Plugins.Features.UIExtension page.WriteLiteral("\n
"); 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))); - page.WriteLiteral(string.Format("\n\n", extensionDescription)); + string extensionDescription = HttpUtility.HtmlEncode($"{uiExtResult.Source.Id} @ {uiExtResult.Source.PluginManifest.Id} v{uiExtResult.Source.PluginManifest.Version.ToString(4)}"); + page.WriteLiteral($"\n\n"); uiExtResult.ExecuteResult(page); - page.WriteLiteral(string.Format("\n", extensionDescription)); + page.WriteLiteral($"\n"); } page.WriteLiteral("\n
"); page.WriteLiteral("\n"); diff --git a/Disco.Services/Plugins/InstallPluginTask.cs b/Disco.Services/Plugins/InstallPluginTask.cs index 02ef0c60..e14e9ad9 100644 --- a/Disco.Services/Plugins/InstallPluginTask.cs +++ b/Disco.Services/Plugins/InstallPluginTask.cs @@ -69,7 +69,7 @@ namespace Disco.Services.Plugins 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); @@ -80,7 +80,7 @@ namespace Disco.Services.Plugins // Ensure not already installed 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()) { @@ -90,7 +90,7 @@ namespace Disco.Services.Plugins var libraryIncompatibility = PluginLibrary.LoadManifest(database).LoadIncompatibilityData(); PluginIncompatibility 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 if (Directory.Exists(packagePath)) @@ -116,7 +116,7 @@ namespace Disco.Services.Plugins // Extract Package Contents 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 var packageEntryTarget = Path.Combine(packagePath, packageEntry.FullName); @@ -153,7 +153,7 @@ namespace Disco.Services.Plugins ScheduledTasks.InitializeScheduledTasks(database, new List() { packageManifest.PluginAssembly }); 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"); } } diff --git a/Disco.Services/Plugins/InvalidFeatureCategoryTypeException.cs b/Disco.Services/Plugins/InvalidFeatureCategoryTypeException.cs index b5c94767..62f3afea 100644 --- a/Disco.Services/Plugins/InvalidFeatureCategoryTypeException.cs +++ b/Disco.Services/Plugins/InvalidFeatureCategoryTypeException.cs @@ -37,9 +37,9 @@ namespace Disco.Services.Plugins get { if (string.IsNullOrEmpty(_pluginRequested)) - return string.Format("Invalid Category Type [{0}]", _categoryType.Name); + return $"Invalid Category Type [{_categoryType.Name}]"; 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}]"; } } diff --git a/Disco.Services/Plugins/Plugin.cs b/Disco.Services/Plugins/Plugin.cs index 6fd14706..502bc4c4 100644 --- a/Disco.Services/Plugins/Plugin.cs +++ b/Disco.Services/Plugins/Plugin.cs @@ -23,7 +23,7 @@ namespace Disco.Services.Plugins 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)}"; } } } diff --git a/Disco.Services/Plugins/PluginExtensions.cs b/Disco.Services/Plugins/PluginExtensions.cs index 18d9304b..1bcc1ac8 100644 --- a/Disco.Services/Plugins/PluginExtensions.cs +++ b/Disco.Services/Plugins/PluginExtensions.cs @@ -152,7 +152,7 @@ namespace Disco.Services.Plugins var routeValues = new RouteValueDictionary(new { PluginId = manifest.Id, res = Resource }); 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) pluginActionUrl += "&Download=true"; @@ -297,7 +297,7 @@ namespace Disco.Services.Plugins var routeValues = new RouteValueDictionary(new { PluginId = manifest.Id, res = Resource }); 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); diff --git a/Disco.Services/Plugins/PluginFeatureManifest.cs b/Disco.Services/Plugins/PluginFeatureManifest.cs index b954d658..dd155968 100644 --- a/Disco.Services/Plugins/PluginFeatureManifest.cs +++ b/Disco.Services/Plugins/PluginFeatureManifest.cs @@ -57,7 +57,7 @@ namespace Disco.Services.Plugins return i; } 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}]"); } /// @@ -70,7 +70,7 @@ namespace Disco.Services.Plugins var featureAttribute = (PluginFeatureAttribute)featureType.GetCustomAttributes(typeof(PluginFeatureAttribute), false).FirstOrDefault(); 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 featureName = featureAttribute.Name; @@ -80,19 +80,19 @@ namespace Disco.Services.Plugins var featureCategoryType = featureType.BaseType; 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) if (featureCategoryType.IsGenericType) featureCategoryType = featureCategoryType.GetGenericTypeDefinition(); 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(); 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() { diff --git a/Disco.Services/Plugins/PluginManifest.cs b/Disco.Services/Plugins/PluginManifest.cs index b374bd22..cbcf0edf 100644 --- a/Disco.Services/Plugins/PluginManifest.cs +++ b/Disco.Services/Plugins/PluginManifest.cs @@ -68,7 +68,7 @@ namespace Disco.Services.Plugins get { 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(false); 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 pluginName = pluginAttributes.Name; @@ -328,19 +328,19 @@ namespace Disco.Services.Plugins var assemblyFullPath = Path.Combine(PluginLocation, AssemblyPath); 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) PluginAssembly = Assembly.LoadFile(assemblyFullPath); 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); // Check Manifest/Assembly Versions Match 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) Type = PluginAssembly.GetType(TypeName, true, true); @@ -442,7 +442,7 @@ namespace Disco.Services.Plugins { get { - return string.Format("/Config/Plugins/{0}", HttpUtility.UrlEncode(Id)); + return $"/Config/Plugins/{HttpUtility.UrlEncode(Id)}"; } } [JsonIgnore] @@ -471,7 +471,7 @@ namespace Disco.Services.Plugins { var attributeDenied = WebHandlerAuthorizers.FirstOrDefault(a => !a.IsAuthorized(HostController.HttpContext)); 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); @@ -487,7 +487,7 @@ namespace Disco.Services.Plugins { get { - return string.Format("/Plugin/{0}", HttpUtility.UrlEncode(Id)); + return $"/Plugin/{HttpUtility.UrlEncode(Id)}"; } } public string WebActionUrl(string Action) @@ -513,7 +513,7 @@ namespace Disco.Services.Plugins var resourcePath = Path.Combine(PluginLocation, "WebResources", Resource.Replace(@"/", @"\")); Tuple resourceHash; - string resourceKey = string.Format("{0}://{1}", Name, Resource); + string resourceKey = $"{Name}://{Resource}"; if (WebResourceHashes.TryGetValue(resourceKey, out resourceHash)) { #if DEBUG @@ -524,7 +524,7 @@ namespace Disco.Services.Plugins } 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 fileBytes = System.IO.File.ReadAllBytes(resourcePath); @@ -548,7 +548,7 @@ namespace Disco.Services.Plugins new RouteValueDictionary(new Dictionary() { { "PluginId", Id }, { "res", Resource } }), RouteTable.Routes, HttpContext.Current.Request.RequestContext, false); - url += string.Format("?v={0}", resourcePath.Item2); + url += $"?v={resourcePath.Item2}"; return url; } @@ -577,7 +577,7 @@ namespace Disco.Services.Plugins public override string ToString() { - return string.Format("{0} [{1} v{2}]", Name, Id, VersionFormatted); + return $"{Name} [{Id} v{VersionFormatted}]"; } } } diff --git a/Disco.Services/Plugins/PluginWebHandler.cs b/Disco.Services/Plugins/PluginWebHandler.cs index 6e136cbc..3fc6997c 100644 --- a/Disco.Services/Plugins/PluginWebHandler.cs +++ b/Disco.Services/Plugins/PluginWebHandler.cs @@ -292,7 +292,7 @@ namespace Disco.Services.Plugins 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); - pluginActionUrl += string.Format("?v={0}", resourcePath.Item2); + pluginActionUrl += $"?v={resourcePath.Item2}"; if (Download.HasValue && Download.Value) { diff --git a/Disco.Services/Plugins/PluginWebHandlerController.cs b/Disco.Services/Plugins/PluginWebHandlerController.cs index e46ea18c..fcf777c1 100644 --- a/Disco.Services/Plugins/PluginWebHandlerController.cs +++ b/Disco.Services/Plugins/PluginWebHandlerController.cs @@ -173,7 +173,7 @@ namespace Disco.Services.Plugins var filters = methodInfo.GetCustomAttributes(true).OfType().ToList(); foreach (var authorizer in filters.OfType()) - authorizer.AuthorizeResource = string.Format("[Plugin]::{0}::{1}", controllerDescription.Manifest.Id, methodInfo.Name); + authorizer.AuthorizeResource = $"[Plugin]::{controllerDescription.Manifest.Id}::{methodInfo.Name}"; return filters.ToArray(); } diff --git a/Disco.Services/Plugins/Plugins.cs b/Disco.Services/Plugins/Plugins.cs index e3b77209..b777eb52 100644 --- a/Disco.Services/Plugins/Plugins.cs +++ b/Disco.Services/Plugins/Plugins.cs @@ -35,7 +35,7 @@ namespace Disco.Services.Plugins lock (_PluginLock) { 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 _PluginManifests[Manifest.Id] = Manifest; @@ -256,7 +256,7 @@ namespace Disco.Services.Plugins if (FeatureCategoryDisplayNames.TryGetValue(FeatureCategoryType, out displayName)) return displayName; 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) @@ -295,10 +295,10 @@ namespace Disco.Services.Plugins if (pluginManifest != null) { 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 - 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)) { // Update Plugin @@ -310,12 +310,12 @@ namespace Disco.Services.Plugins // Check Version Compatibility var pluginIncompatible = compatibilityData.Value.IncompatiblePlugins.FirstOrDefault(i => i.PluginId.Equals(pluginManifest.Id, StringComparison.OrdinalIgnoreCase) && pluginManifest.Version == i.Version); 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) - 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) - 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); @@ -429,7 +429,7 @@ namespace Disco.Services.Plugins PluginLibraryIncompatibility = PluginLibrary.LoadManifest(Database).LoadIncompatibilityData(); var pluginIncompatibility = PluginLibraryIncompatibility.IncompatiblePlugins.FirstOrDefault(i => i.PluginId.Equals(packageManifest.Id, StringComparison.OrdinalIgnoreCase) && packageManifest.Version == i.Version); 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); @@ -554,7 +554,7 @@ namespace Disco.Services.Plugins } 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); } } } diff --git a/Disco.Services/Plugins/UninstallPluginTask.cs b/Disco.Services/Plugins/UninstallPluginTask.cs index 957e49a7..57d8a588 100644 --- a/Disco.Services/Plugins/UninstallPluginTask.cs +++ b/Disco.Services/Plugins/UninstallPluginTask.cs @@ -16,7 +16,7 @@ namespace Disco.Services.Plugins var manifest = (PluginManifest)ExecutionContext.JobDetail.JobDataMap["PluginManifest"]; 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); diff --git a/Disco.Services/Plugins/UnknownPluginException.cs b/Disco.Services/Plugins/UnknownPluginException.cs index 65ee23ac..461187b4 100644 --- a/Disco.Services/Plugins/UnknownPluginException.cs +++ b/Disco.Services/Plugins/UnknownPluginException.cs @@ -27,7 +27,7 @@ namespace Disco.Services.Plugins { get { - return string.Format("Unknown Plugin Id: [{0}]", _pluginRequested); + return $"Unknown Plugin Id: [{_pluginRequested}]"; } } } diff --git a/Disco.Services/Plugins/UpdatePluginTask.cs b/Disco.Services/Plugins/UpdatePluginTask.cs index 04bb4f27..e40fab5d 100644 --- a/Disco.Services/Plugins/UpdatePluginTask.cs +++ b/Disco.Services/Plugins/UpdatePluginTask.cs @@ -187,8 +187,8 @@ namespace Disco.Services.Plugins if (string.IsNullOrEmpty(packageTempFilePath)) { // Download Update - Status.UpdateStatus(0, string.Format("Downloading Plugin Package: {0}", pluginName), "Connecting..."); - packageTempFilePath = Path.Combine(pluginPackagesLocation, string.Format("{0}.discoPlugin", pluginId)); + Status.UpdateStatus(0, $"Downloading Plugin Package: {pluginName}", "Connecting..."); + packageTempFilePath = Path.Combine(pluginPackagesLocation, $"{pluginId}.discoPlugin"); if (File.Exists(packageTempFilePath)) File.Delete(packageTempFilePath); @@ -238,7 +238,7 @@ namespace Disco.Services.Plugins if (updateManifest.Version < existingManifest.Version) 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()) { @@ -246,9 +246,9 @@ namespace Disco.Services.Plugins var incompatibilityLibrary = PluginLibrary.LoadManifest(database).LoadIncompatibilityData(); PluginIncompatibility 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); if (existingManifest != null) diff --git a/Disco.Services/Tasks/ScheduledTasks.cs b/Disco.Services/Tasks/ScheduledTasks.cs index b8277e3b..3f824773 100644 --- a/Disco.Services/Tasks/ScheduledTasks.cs +++ b/Disco.Services/Tasks/ScheduledTasks.cs @@ -130,7 +130,7 @@ namespace Disco.Services.Tasks { var existingGuid = _RunningTasks.Where(t => t.IsRunning && t.TaskType == taskType).Select(t => t.SessionId).FirstOrDefault(); 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); } diff --git a/Disco.Services/Users/UserExtensions.cs b/Disco.Services/Users/UserExtensions.cs index cb0dfb59..483b589e 100644 --- a/Disco.Services/Users/UserExtensions.cs +++ b/Disco.Services/Users/UserExtensions.cs @@ -18,7 +18,7 @@ namespace Disco.Services 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) diff --git a/Disco.Services/Users/UserFlags/UserFlagService.cs b/Disco.Services/Users/UserFlags/UserFlagService.cs index 17488c4c..8e2532ad 100644 --- a/Disco.Services/Users/UserFlags/UserFlagService.cs +++ b/Disco.Services/Users/UserFlags/UserFlagService.cs @@ -100,7 +100,7 @@ namespace Disco.Services.Users.UserFlags Interop.ActiveDirectory.ActiveDirectory.Context.ManagedGroups.Remove(UserFlagUsersManagedGroup.GetKey(flag)); // 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 flagAssignments = Database.UserFlagAssignments.Where(fa => fa.UserFlagId == flag.Id).ToList(); if (flagAssignments.Count > 0) { @@ -117,7 +117,7 @@ namespace Disco.Services.Users.UserFlags // Remove from Cache _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 @@ -140,7 +140,7 @@ namespace Disco.Services.Users.UserFlags 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); }).ToList(); @@ -151,7 +151,7 @@ namespace Disco.Services.Users.UserFlags return chunkResults; }).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; } @@ -186,7 +186,7 @@ namespace Disco.Services.Users.UserFlags 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); @@ -206,7 +206,7 @@ namespace Disco.Services.Users.UserFlags 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); }).ToList(); @@ -217,7 +217,7 @@ namespace Disco.Services.Users.UserFlags return chunkResults; }).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; } diff --git a/Disco.Services/Users/UserFlags/UserFlagsBulkAssignTask.cs b/Disco.Services/Users/UserFlags/UserFlagsBulkAssignTask.cs index f0bfd3b4..0827b375 100644 --- a/Disco.Services/Users/UserFlags/UserFlagsBulkAssignTask.cs +++ b/Disco.Services/Users/UserFlags/UserFlagsBulkAssignTask.cs @@ -32,7 +32,7 @@ namespace Disco.Services.Users.UserFlags if (userFlag == null) 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 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++) { 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 { users.Add(UserService.GetUser(userId, Database, true)); @@ -68,7 +68,7 @@ namespace Disco.Services.Users.UserFlags } 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(); diff --git a/Disco.Services/Web/Bundles/BundleTable.cs b/Disco.Services/Web/Bundles/BundleTable.cs index 0eedf45a..a5612d6d 100644 --- a/Disco.Services/Web/Bundles/BundleTable.cs +++ b/Disco.Services/Web/Bundles/BundleTable.cs @@ -44,7 +44,7 @@ namespace Disco.Services.Web.Bundles var bundle = GetBundleFor(BundleUrl); 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); } @@ -53,16 +53,16 @@ namespace Disco.Services.Web.Bundles var bundle = GetBundleFor(BundleUrl); 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); switch (bundle.ContentType) { case "text/css": - return string.Format("", bundleUrl); + return $""; case "text/javascript": - return string.Format("", bundleUrl); + return $""; default: throw new ArgumentException("Unsupported Bundle Content Type", "BundleUrl"); } diff --git a/Disco.Services/Web/Bundles/FileBundle.cs b/Disco.Services/Web/Bundles/FileBundle.cs index 6bd59804..95d7fdda 100644 --- a/Disco.Services/Web/Bundles/FileBundle.cs +++ b/Disco.Services/Web/Bundles/FileBundle.cs @@ -30,7 +30,7 @@ namespace Disco.Services.Web.Bundles get { #if DEBUG - return string.Format("{0}?v={1}", Url, FileHash); + return $"{Url}?v={FileHash}"; #else return _VersionUrl; #endif @@ -53,7 +53,7 @@ namespace Disco.Services.Web.Bundles var fileInfo = new FileInfo(File); if (!fileInfo.Exists) - throw new FileNotFoundException(string.Format("Not Found: {0}", File), File); + throw new FileNotFoundException($"Not Found: {File}", File); this.Url = Url; this.File = File; @@ -78,7 +78,7 @@ namespace Disco.Services.Web.Bundles //this.Version = fileInfo.LastWriteTimeUtc.Ticks; - _VersionUrl = string.Format("{0}?v={1}", this.Url, FileHash); + _VersionUrl = $"{this.Url}?v={FileHash}"; } private void UpdateFileHash() diff --git a/Disco.Services/Web/HelperExtensions.cs b/Disco.Services/Web/HelperExtensions.cs index 4d67a334..42c240e1 100644 --- a/Disco.Services/Web/HelperExtensions.cs +++ b/Disco.Services/Web/HelperExtensions.cs @@ -53,7 +53,7 @@ namespace Disco.Services.Web var resource = accessDeniedException.Resource; var httpContext = HttpContext.Current; 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); } diff --git a/Disco.Web.Extensions/BIModelExtensions/OrganisationAddressExtensions.cs b/Disco.Web.Extensions/BIModelExtensions/OrganisationAddressExtensions.cs index 67e44e06..0abd15c1 100644 --- a/Disco.Web.Extensions/BIModelExtensions/OrganisationAddressExtensions.cs +++ b/Disco.Web.Extensions/BIModelExtensions/OrganisationAddressExtensions.cs @@ -22,12 +22,12 @@ namespace Disco.Web.Extensions { var selectItems = default(List); 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 - 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) - 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; } diff --git a/Disco.Web.Extensions/BIModelExtensions/PluginExtensions.cs b/Disco.Web.Extensions/BIModelExtensions/PluginExtensions.cs index 4e3c7fc0..97f81c90 100644 --- a/Disco.Web.Extensions/BIModelExtensions/PluginExtensions.cs +++ b/Disco.Web.Extensions/BIModelExtensions/PluginExtensions.cs @@ -52,7 +52,7 @@ namespace Disco.Web.Extensions var selectItems = items.OrderBy(i => i.Text).ToList(); 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; } @@ -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(); 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; } diff --git a/Disco.Web.Extensions/BIModelExtensions/UtilityExtensions.cs b/Disco.Web.Extensions/BIModelExtensions/UtilityExtensions.cs index b459b464..87535fa3 100644 --- a/Disco.Web.Extensions/BIModelExtensions/UtilityExtensions.cs +++ b/Disco.Web.Extensions/BIModelExtensions/UtilityExtensions.cs @@ -6,7 +6,7 @@ namespace Disco.Web.Extensions { 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) { diff --git a/Disco.Web.Extensions/DataModelExtension/JobSubTypeExtensions.cs b/Disco.Web.Extensions/DataModelExtension/JobSubTypeExtensions.cs index a8dbe937..5fdea7a6 100644 --- a/Disco.Web.Extensions/DataModelExtension/JobSubTypeExtensions.cs +++ b/Disco.Web.Extensions/DataModelExtension/JobSubTypeExtensions.cs @@ -12,7 +12,7 @@ namespace Disco.Web.Extensions List selectedIds = default(List); 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); } @@ -20,9 +20,9 @@ namespace Disco.Web.Extensions public static List ToSelectListItems(this IEnumerable jobSubTypes, List SelectedIds = null, bool IncludeQueueIcons = false) { 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 - 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) @@ -32,7 +32,7 @@ namespace Disco.Web.Extensions var sb = new System.Text.StringBuilder(System.Web.HttpUtility.HtmlEncode(jst.Description)); foreach (var jq in jst.JobQueues) - sb.AppendFormat(" ", jq.Icon, jq.IconColour, jq.Name); + sb.AppendFormat($" "); return sb.ToString(); } diff --git a/Disco.Web/App_Start/BundleConfig.cs b/Disco.Web/App_Start/BundleConfig.cs index f68c2cb5..25b980d1 100644 --- a/Disco.Web/App_Start/BundleConfig.cs +++ b/Disco.Web/App_Start/BundleConfig.cs @@ -42,7 +42,7 @@ namespace Disco.Web // Scripts - Modules #if DEBUG 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 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)); diff --git a/Disco.Web/Areas/API/Controllers/AuthorizationRoleController.cs b/Disco.Web/Areas/API/Controllers/AuthorizationRoleController.cs index 4f82c946..bef77c36 100644 --- a/Disco.Web/Areas/API/Controllers/AuthorizationRoleController.cs +++ b/Disco.Web/Areas/API/Controllers/AuthorizationRoleController.cs @@ -52,7 +52,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; 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(); 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 currentSubjects = AuthorizationRole.SubjectIds == null ? new string[0] : AuthorizationRole.SubjectIds.Split(','); @@ -170,7 +170,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; 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) throw; 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) throw; 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(); 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(); var currentSubjects = UserService.AdministratorSubjectIds; diff --git a/Disco.Web/Areas/API/Controllers/BootstrapperController.cs b/Disco.Web/Areas/API/Controllers/BootstrapperController.cs index 3b004b38..cb42446d 100644 --- a/Disco.Web/Areas/API/Controllers/BootstrapperController.cs +++ b/Disco.Web/Areas/API/Controllers/BootstrapperController.cs @@ -25,7 +25,7 @@ namespace Disco.Web.Areas.API.Controllers } 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) @@ -45,7 +45,7 @@ namespace Disco.Web.Areas.API.Controllers } catch (Exception ex) { - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs b/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs index 97adf735..37bc8d2b 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceBatchController.cs @@ -116,7 +116,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; 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) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } [DiscoAuthorize(Claims.Config.DeviceBatch.Configure)] @@ -267,7 +267,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } #endregion @@ -534,7 +534,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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, end = bi.WarrantyValidUntil, 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", description = bi.Comments ?? string.Empty, color = ColorTranslator.ToHtml(color), diff --git a/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs b/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs index 678d0606..96526ac0 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceCertificateController.cs @@ -16,7 +16,7 @@ namespace Disco.Web.Areas.API.Controllers { 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"); } } diff --git a/Disco.Web/Areas/API/Controllers/DeviceController.cs b/Disco.Web/Areas/API/Controllers/DeviceController.cs index f959fdb0..b1e336b1 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceController.cs @@ -106,7 +106,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Controllers/DeviceFlagController.cs b/Disco.Web/Areas/API/Controllers/DeviceFlagController.cs index a5cdc08e..08859713 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceFlagController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceFlagController.cs @@ -131,7 +131,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } [DiscoAuthorize(Claims.Config.DeviceFlag.Configure)] diff --git a/Disco.Web/Areas/API/Controllers/DeviceModelController.cs b/Disco.Web/Areas/API/Controllers/DeviceModelController.cs index 5d16cf6c..d57926bf 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceModelController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceModelController.cs @@ -75,7 +75,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; 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 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)) { return File(modelTypePath, "image/png"); @@ -295,7 +295,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs b/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs index 73ce8541..717b0071 100644 --- a/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs +++ b/Disco.Web/Areas/API/Controllers/DeviceProfileController.cs @@ -121,7 +121,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } [DiscoAuthorize(Claims.Config.DeviceProfile.Configure)] @@ -407,7 +407,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } #endregion @@ -467,7 +467,7 @@ namespace Disco.Web.Areas.API.Controllers var featureManifest = Plugins.GetPluginFeature(certificateProviderId, typeof(CertificateProviderFeature)); 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 { @@ -503,7 +503,7 @@ namespace Disco.Web.Areas.API.Controllers var featureManifest = Plugins.GetPluginFeature(certificateAuthorityProviderId, typeof(CertificateAuthorityProviderFeature)); 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 { @@ -539,7 +539,7 @@ namespace Disco.Web.Areas.API.Controllers var featureManifest = Plugins.GetPluginFeature(wirelessProfileProviderId, typeof(WirelessProfileProviderFeature)); 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 { @@ -728,7 +728,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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) throw; 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) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs b/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs index 9ee99ca7..ffeb953a 100644 --- a/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs +++ b/Disco.Web/Areas/API/Controllers/DocumentTemplateController.cs @@ -104,7 +104,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; 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); 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 { @@ -151,7 +151,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; 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) throw; 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) throw; 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) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } #endregion @@ -498,7 +498,7 @@ namespace Disco.Web.Areas.API.Controllers public virtual ActionResult ImporterThumbnail(string SessionId, int PageNumber) { 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)) return File(filename, "image/png"); else @@ -1318,7 +1318,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Controllers/DocumentTemplatePackageController.cs b/Disco.Web/Areas/API/Controllers/DocumentTemplatePackageController.cs index 8a4101e5..26ff9802 100644 --- a/Disco.Web/Areas/API/Controllers/DocumentTemplatePackageController.cs +++ b/Disco.Web/Areas/API/Controllers/DocumentTemplatePackageController.cs @@ -76,7 +76,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; 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) throw; 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) throw; 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 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) @@ -455,7 +455,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Controllers/JobController.cs b/Disco.Web/Areas/API/Controllers/JobController.cs index f78c4d2a..4b590985 100644 --- a/Disco.Web/Areas/API/Controllers/JobController.cs +++ b/Disco.Web/Areas/API/Controllers/JobController.cs @@ -306,7 +306,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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) throw; 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, TechUserId = CurrentUser.UserId, Timestamp = DateTime.Now, - Comments = string.Format("# Added Flag\r\n**{0}**\r\n{1}", flagStatus.Item1, string.IsNullOrWhiteSpace(Reason) ? "" : Reason) + Comments = $"# Added Flag\r\n**{flagStatus.Item1}**\r\n{(string.IsNullOrWhiteSpace(Reason) ? "" : Reason)}" }; Database.JobLogs.Add(jobLog); @@ -1542,7 +1542,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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) throw; 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) throw; 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.Count == 1) - reference = string.Format("Job {0}", locRef.References[0].JobId); + reference = $"Job {locRef.References[0].JobId}"; else - reference = string.Format("{0} jobs", locRef.References.Count); + reference = $"{locRef.References.Count} jobs"; } return new Models.Job.DeviceHeldLocationModel() diff --git a/Disco.Web/Areas/API/Controllers/JobQueueController.cs b/Disco.Web/Areas/API/Controllers/JobQueueController.cs index 4c366f30..9d6980a4 100644 --- a/Disco.Web/Areas/API/Controllers/JobQueueController.cs +++ b/Disco.Web/Areas/API/Controllers/JobQueueController.cs @@ -71,7 +71,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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) throw; 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) throw; 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) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } #endregion @@ -295,7 +295,7 @@ namespace Disco.Web.Areas.API.Controllers var invalidSubjects = subjects.Where(s => s.Item2 == null).ToList(); 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(); @@ -364,7 +364,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } #endregion diff --git a/Disco.Web/Areas/API/Controllers/JobQueueJobController.cs b/Disco.Web/Areas/API/Controllers/JobQueueJobController.cs index 20440af7..b49decd3 100644 --- a/Disco.Web/Areas/API/Controllers/JobQueueJobController.cs +++ b/Disco.Web/Areas/API/Controllers/JobQueueJobController.cs @@ -50,7 +50,7 @@ namespace Disco.Web.Areas.API.Controllers throw new Exception("Invalid Job Queue Job Id"); } 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 return Json("OK", JsonRequestBehavior.AllowGet); } @@ -59,7 +59,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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"); } 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 return Json("OK", JsonRequestBehavior.AllowGet); } @@ -113,7 +113,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } #endregion @@ -195,7 +195,7 @@ namespace Disco.Web.Areas.API.Controllers var jobQueueJob = job.OnAddQueue(Database, jobQueueToken.JobQueue, CurrentUser, Comment, SLAExpires, Priority); 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)] @@ -223,7 +223,7 @@ namespace Disco.Web.Areas.API.Controllers 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 diff --git a/Disco.Web/Areas/API/Controllers/PluginController.cs b/Disco.Web/Areas/API/Controllers/PluginController.cs index bcc46954..41b094ac 100644 --- a/Disco.Web/Areas/API/Controllers/PluginController.cs +++ b/Disco.Web/Areas/API/Controllers/PluginController.cs @@ -85,7 +85,7 @@ namespace Disco.Web.Areas.API.Controllers if (Plugins.PluginInstalled(libraryItem.Id)) 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); diff --git a/Disco.Web/Areas/API/Controllers/SystemController.cs b/Disco.Web/Areas/API/Controllers/SystemController.cs index 93743dbb..e6171907 100644 --- a/Disco.Web/Areas/API/Controllers/SystemController.cs +++ b/Disco.Web/Areas/API/Controllers/SystemController.cs @@ -275,7 +275,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Controllers/UserFlagController.cs b/Disco.Web/Areas/API/Controllers/UserFlagController.cs index 5e92b91a..14cd8570 100644 --- a/Disco.Web/Areas/API/Controllers/UserFlagController.cs +++ b/Disco.Web/Areas/API/Controllers/UserFlagController.cs @@ -75,7 +75,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; 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) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } [DiscoAuthorize(Claims.Config.UserFlag.Configure)] @@ -174,7 +174,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } [DiscoAuthorize(Claims.Config.UserFlag.Configure)] @@ -207,7 +207,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } #endregion @@ -371,7 +371,7 @@ namespace Disco.Web.Areas.API.Controllers if (redirect.HasValue && redirect.Value) throw; else - return Json(string.Format("Error: {0}", ex.Message), JsonRequestBehavior.AllowGet); + return Json($"Error: {ex.Message}", JsonRequestBehavior.AllowGet); } } diff --git a/Disco.Web/Areas/API/Models/DeviceModel/_ComponentModel.cs b/Disco.Web/Areas/API/Models/DeviceModel/_ComponentModel.cs index 7da95ee3..e39c537a 100644 --- a/Disco.Web/Areas/API/Models/DeviceModel/_ComponentModel.cs +++ b/Disco.Web/Areas/API/Models/DeviceModel/_ComponentModel.cs @@ -17,7 +17,7 @@ namespace Disco.Web.Areas.API.Models.DeviceModel Id = dc.Id, Description = dc.Description, 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() }; } diff --git a/Disco.Web/Areas/API/Models/DocumentTemplate/ImporterUndetectedDataIdLookupModel.cs b/Disco.Web/Areas/API/Models/DocumentTemplate/ImporterUndetectedDataIdLookupModel.cs index f8708a81..300ea89d 100644 --- a/Disco.Web/Areas/API/Models/DocumentTemplate/ImporterUndetectedDataIdLookupModel.cs +++ b/Disco.Web/Areas/API/Models/DocumentTemplate/ImporterUndetectedDataIdLookupModel.cs @@ -13,7 +13,7 @@ namespace Disco.Web.Areas.API.Models.DocumentTemplate return new ImporterUndetectedDataIdLookupModel { 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) @@ -21,7 +21,7 @@ namespace Disco.Web.Areas.API.Models.DocumentTemplate return new ImporterUndetectedDataIdLookupModel { 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) @@ -29,7 +29,7 @@ namespace Disco.Web.Areas.API.Models.DocumentTemplate return new ImporterUndetectedDataIdLookupModel { value = item.Id, - label = string.Format("{0} - {1}", item.Id, item.DisplayName) + label = $"{item.Id} - {item.DisplayName}" }; } diff --git a/Disco.Web/Areas/Config/Models/DeviceModel/_IndexModelItem.cs b/Disco.Web/Areas/Config/Models/DeviceModel/_IndexModelItem.cs index 85abbd6f..8011af3b 100644 --- a/Disco.Web/Areas/Config/Models/DeviceModel/_IndexModelItem.cs +++ b/Disco.Web/Areas/Config/Models/DeviceModel/_IndexModelItem.cs @@ -15,7 +15,7 @@ namespace Disco.Web.Areas.Config.Models.DeviceModel public override string ToString() { if (string.IsNullOrEmpty(Name)) - return string.Format("{0} {1}", Manufacturer, Model); + return $"{Manufacturer} {Model}"; else return Name; } diff --git a/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs b/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs index 76826bc5..82be2e0c 100644 --- a/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs +++ b/Disco.Web/Areas/Config/Models/DocumentTemplate/CreateModel.cs @@ -67,7 +67,7 @@ namespace Disco.Web.Areas.Config.Models.DocumentTemplate { 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(); } } diff --git a/Disco.Web/Areas/Config/Models/JobPreferences/IndexModel.cs b/Disco.Web/Areas/Config/Models/JobPreferences/IndexModel.cs index 1039bf7d..d03b3fd1 100644 --- a/Disco.Web/Areas/Config/Models/JobPreferences/IndexModel.cs +++ b/Disco.Web/Areas/Config/Models/JobPreferences/IndexModel.cs @@ -70,7 +70,7 @@ namespace Disco.Web.Areas.Config.Models.JobPreferences var current = LongRunningJobDaysThreshold; if (!options.Any(o => o.Key == current)) { - options.Add(new KeyValuePair(current, string.Format("{0} Days", current))); + options.Add(new KeyValuePair(current, $"{current} Days")); options = options.OrderBy(o => o.Key).ToList(); } @@ -106,7 +106,7 @@ namespace Disco.Web.Areas.Config.Models.JobPreferences var current = StaleJobMinutesThreshold; if (!options.Any(o => o.Key == current)) { - options.Add(new KeyValuePair(current, string.Format("{0} Minutes", current))); + options.Add(new KeyValuePair(current, $"{current} Minutes")); options = options.OrderBy(o => o.Key).ToList(); } diff --git a/Disco.Web/Areas/Services/Controllers/ClientController.cs b/Disco.Web/Areas/Services/Controllers/ClientController.cs index b93f20fe..893e88a0 100644 --- a/Disco.Web/Areas/Services/Controllers/ClientController.cs +++ b/Disco.Web/Areas/Services/Controllers/ClientController.cs @@ -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] @@ -136,7 +136,7 @@ namespace Disco.Web.Areas.Services.Controllers 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) diff --git a/Disco.Web/Controllers/DeviceController.cs b/Disco.Web/Controllers/DeviceController.cs index aabbe474..25a2ab28 100644 --- a/Disco.Web/Controllers/DeviceController.cs +++ b/Disco.Web/Controllers/DeviceController.cs @@ -240,7 +240,7 @@ namespace Disco.Web.Controllers .FirstOrDefault(d => d.SerialNumber == id); if (m.Device == null) - throw new ArgumentException(string.Format("Unknown Device: [{0}]", id), "id"); + throw new ArgumentException($"Unknown Device: [{id}]", "id"); // No Necessary - Yet... //if (!string.IsNullOrWhiteSpace(m.Device.ComputerName)) diff --git a/Disco.Web/Controllers/InitialConfigController.cs b/Disco.Web/Controllers/InitialConfigController.cs index 12113de4..173575a9 100644 --- a/Disco.Web/Controllers/InitialConfigController.cs +++ b/Disco.Web/Controllers/InitialConfigController.cs @@ -150,11 +150,11 @@ namespace Disco.Web.Controllers 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 { - 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) { - 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(); 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(); var currentSubjects = UserService.AdministratorSubjectIds; diff --git a/Disco.Web/Controllers/JobController.cs b/Disco.Web/Controllers/JobController.cs index 8ba01e26..87f52b05 100644 --- a/Disco.Web/Controllers/JobController.cs +++ b/Disco.Web/Controllers/JobController.cs @@ -69,7 +69,7 @@ namespace Disco.Web.Controllers if (queueToken == null) 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))); // UI Extensions @@ -326,7 +326,7 @@ namespace Disco.Web.Controllers .FirstOrDefault(j => j.Id == id.Value); if (m.Job == null) - throw new ArgumentException(string.Format("Unknown Job: [{0}]", id), "id"); + throw new ArgumentException($"Unknown Job: [{id}]", "id"); // Validate Authorization switch (m.Job.JobTypeId) @@ -695,14 +695,14 @@ namespace Disco.Web.Controllers else { 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); } } } 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); } else @@ -874,14 +874,14 @@ namespace Disco.Web.Controllers else { 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); } } } 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); } else diff --git a/Disco.Web/Controllers/PluginWebHandlerController.cs b/Disco.Web/Controllers/PluginWebHandlerController.cs index f5d21d2f..2d7f7bb8 100644 --- a/Disco.Web/Controllers/PluginWebHandlerController.cs +++ b/Disco.Web/Controllers/PluginWebHandlerController.cs @@ -32,7 +32,7 @@ namespace Disco.Web.Controllers catch (AccessDeniedException accessDeniedException) { if (UserService.CurrentUserId != null) - AuthorizationLog.LogAccessDenied(UserService.CurrentUserId, string.Format("{0} [{1}]", accessDeniedException.Resource, Request.RawUrl), accessDeniedException.Message); + AuthorizationLog.LogAccessDenied(UserService.CurrentUserId, $"{accessDeniedException.Resource} [{Request.RawUrl}]", accessDeniedException.Message); return new HttpUnauthorizedResult(); } diff --git a/Disco.Web/Controllers/SearchController.cs b/Disco.Web/Controllers/SearchController.cs index 1433026a..545c8ac8 100644 --- a/Disco.Web/Controllers/SearchController.cs +++ b/Disco.Web/Controllers/SearchController.cs @@ -88,7 +88,7 @@ namespace Disco.Web.Controllers break; } } - m.FriendlyTerm = string.Format("Device Model: {0}", term); + m.FriendlyTerm = $"Device Model: {term}"; m.Success = false; m.ErrorMessage = "Invalid Device Model Id"; break; @@ -105,7 +105,7 @@ namespace Disco.Web.Controllers break; } } - m.FriendlyTerm = string.Format("Device Profile: {0}", term); + m.FriendlyTerm = $"Device Profile: {term}"; m.Success = false; m.ErrorMessage = "Invalid Device Profile Id"; break; @@ -122,7 +122,7 @@ namespace Disco.Web.Controllers break; } } - m.FriendlyTerm = string.Format("Device Batch: {0}", term); + m.FriendlyTerm = $"Device Batch: {term}"; m.Success = false; m.ErrorMessage = "Invalid Device Batch Id"; break; @@ -239,7 +239,7 @@ namespace Disco.Web.Controllers var flag = Database.UserFlags.Find(userFlagId); if (flag != null) { - m.FriendlyTerm = string.Format("User Flag: {0}", flag.ToString()); + m.FriendlyTerm = $"User Flag: {flag.ToString()}"; m.Users = Services.Searching.Search.SearchUserFlag(Database, flag.Id); break; } @@ -256,7 +256,7 @@ namespace Disco.Web.Controllers var flag = Database.DeviceFlags.Find(deviceFlagId); if (flag != null) { - m.FriendlyTerm = string.Format("Device Flag: {0}", flag.ToString()); + m.FriendlyTerm = $"Device Flag: {flag.ToString()}"; m.Devices = Services.Searching.Search.SearchDeviceFlag(Database, flag.Id); break; } diff --git a/Disco.Web/Extensions/HtmlExtensions.cs b/Disco.Web/Extensions/HtmlExtensions.cs index 99c1740d..f4ea9d45 100644 --- a/Disco.Web/Extensions/HtmlExtensions.cs +++ b/Disco.Web/Extensions/HtmlExtensions.cs @@ -126,7 +126,7 @@ namespace Disco.Web { int jobId; if (int.TryParse(match.Groups[2].Value, out jobId)) - return string.Format("{0}", match.Value, jobId, urlHelper.Action(MVC.Job.Show(jobId))); + return $"{match.Value}"; else return match.Value; }); @@ -149,7 +149,7 @@ namespace Disco.Web if (!ActiveDirectory.IsValidDomainAccountId(userId)) return match.Value; - return string.Format("{0}", match.Value, ActiveDirectory.FriendlyAccountId(userId), urlHelper.Action(MVC.User.Show(userId))); + return $"{match.Value}"; } catch (Exception) { @@ -166,7 +166,7 @@ namespace Disco.Web if (string.IsNullOrWhiteSpace(deviceSerialNumber)) return match.Value; - return string.Format("{0}", match.Value, deviceSerialNumber, urlHelper.Action(MVC.Device.Show(deviceSerialNumber))); + return $"{match.Value}"; }); } catch (Exception) diff --git a/Disco.Web/Global.asax.cs b/Disco.Web/Global.asax.cs index 3477fa50..050ad389 100644 --- a/Disco.Web/Global.asax.cs +++ b/Disco.Web/Global.asax.cs @@ -126,7 +126,7 @@ namespace Disco.Web private static Lazy _Version = new Lazy(() => { var AssemblyVersion = typeof(DiscoApplication).Assembly.GetName().Version; - return string.Format("{0}.{1}.{2:0000}.{3:0000}", AssemblyVersion.Major, AssemblyVersion.Minor, AssemblyVersion.Build, AssemblyVersion.Revision); + return $"{AssemblyVersion.Major}.{AssemblyVersion.Minor}.{AssemblyVersion.Build:0000}.{AssemblyVersion.Revision:0000}"; }); public static string Version { diff --git a/Disco.Web/Models/InitialConfig/CompleteModel.cs b/Disco.Web/Models/InitialConfig/CompleteModel.cs index 63e6d3ce..1dc54a2d 100644 --- a/Disco.Web/Models/InitialConfig/CompleteModel.cs +++ b/Disco.Web/Models/InitialConfig/CompleteModel.cs @@ -58,7 +58,7 @@ namespace Disco.Web.Models.InitialConfig wReq.KeepAlive = false; // End Added: 2013-02-08 G# wReq.Method = WebRequestMethods.Http.Get; - wReq.UserAgent = string.Format("Disco/{0} (Initial Config; Org: {1})", DiscoApplication.Version, DiscoApplication.OrganisationName); + wReq.UserAgent = $"Disco/{DiscoApplication.Version} (Initial Config; Org: {DiscoApplication.OrganisationName})"; using (HttpWebResponse wRes = (HttpWebResponse)wReq.GetResponse()) { if (wRes.StatusCode == HttpStatusCode.OK) @@ -67,7 +67,7 @@ namespace Disco.Web.Models.InitialConfig } else { - DiscoIctComAuWebResult = new Exception(string.Format("Server returned response: [{0}] {1}", wRes.StatusCode, wRes.StatusDescription)); + DiscoIctComAuWebResult = new Exception($"Server returned response: [{wRes.StatusCode}] {wRes.StatusDescription}"); } } } diff --git a/Disco.Web/Models/InitialConfig/FileStoreModel.cs b/Disco.Web/Models/InitialConfig/FileStoreModel.cs index 57a52d98..2d4ffb63 100644 --- a/Disco.Web/Models/InitialConfig/FileStoreModel.cs +++ b/Disco.Web/Models/InitialConfig/FileStoreModel.cs @@ -67,7 +67,7 @@ namespace Disco.Web.Models.InitialConfig } catch (Exception ex) { - return new ValidationResult(string.Format("Unable to Create Directory '{0}'; [{1}] {2}", info.FullName, ex.GetType().Name, ex.Message)); + return new ValidationResult($"Unable to Create Directory '{info.FullName}'; [{ex.GetType().Name}] {ex.Message}"); } } } diff --git a/Disco.Web/Models/Job/CreateModel.cs b/Disco.Web/Models/Job/CreateModel.cs index cd6e2118..3312442e 100644 --- a/Disco.Web/Models/Job/CreateModel.cs +++ b/Disco.Web/Models/Job/CreateModel.cs @@ -132,7 +132,7 @@ namespace Disco.Web.Models.Job if (SubTypes != null) { var subTypes = SubTypes; - return JobTypes.SelectMany(jt => jt.JobSubTypes).Where(m => subTypes.Contains(String.Format("{0}_{1}", m.JobTypeId, m.Id))).ToList(); + return JobTypes.SelectMany(jt => jt.JobSubTypes).Where(m => subTypes.Contains($"{m.JobTypeId}_{m.Id}")).ToList(); } return null; } @@ -146,7 +146,7 @@ namespace Disco.Web.Models.Job if (!string.IsNullOrEmpty(model.Type) && model.SubTypes != null) { - var typeId = string.Format("{0}_", model.Type); + var typeId = $"{model.Type}_"; model.SubTypes = model.SubTypes.Where(m => m.StartsWith(typeId)).ToList(); if (model.SubTypes.Count == 0) { diff --git a/Disco.Web/Models/Job/ListModel.cs b/Disco.Web/Models/Job/ListModel.cs index b9ea4c09..7e718772 100644 --- a/Disco.Web/Models/Job/ListModel.cs +++ b/Disco.Web/Models/Job/ListModel.cs @@ -13,7 +13,7 @@ namespace Disco.Web.Models.Job { get { - return string.Format("{0} ({1})", Title, JobTable.Items.Count()); + return $"{Title} ({JobTable.Items.Count()})"; } } }