qol: interpolated strings

This commit is contained in:
Gary Sharp
2025-07-20 11:56:34 +10:00
parent 4e518d6684
commit 7faebe56a8
108 changed files with 342 additions and 350 deletions
@@ -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;
}
@@ -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}";
}
}
}
@@ -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}]";
}
}
}
@@ -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);
}
@@ -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)
+3 -3
View File
@@ -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<DocumentTemplate> AvailableDocumentTemplates(this Device d, DiscoDataContext Database, User User, DateTime TimeStamp)
{
@@ -250,7 +250,7 @@ namespace Disco.Services
public static string Status(this Device Device)
{
if (Device.DecommissionedDate.HasValue)
return string.Format("Decommissioned ({0})", Device.DecommissionReason.ReasonMessage());
return $"Decommissioned ({Device.DecommissionReason.ReasonMessage()})";
if (!Device.EnrolledDate.HasValue)
return "Not Enrolled";
@@ -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();
@@ -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<string, Tuple<string, string>> addresses = new Dictionary<string, Tuple<string, string>>();
foreach (var result in results.OrderBy(r => r.Timestamp))
addresses[((string)result.Arguments[1]).ToLower()] = new Tuple<string, string>((string)result.Arguments[4], (string)result.Arguments[5]);
Status.UpdateStatus(75, string.Format("Importing {0} details", addresses.Count));
Status.UpdateStatus(75, $"Importing {addresses.Count} details");
var devices = database.Devices.Include("DeviceDetails").ToList();
@@ -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))
@@ -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())
{
@@ -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);
@@ -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)
@@ -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;
@@ -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; }
@@ -73,7 +73,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var dNSName = SearchResult.Value<string>("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<int>("userAccountControl");
var isCriticalSystemObject = SearchResult.Value<bool>("isCriticalSystemObject");
@@ -123,7 +123,7 @@ namespace Disco.Services.Interop.ActiveDirectory
var dNSName = properties.Value<string>("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<int>("userAccountControl");
var isCriticalSystemObject = properties.Value<bool>("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))
{
@@ -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)
@@ -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);
}
@@ -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)
{
@@ -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));
}
@@ -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<bool>("isCriticalSystemObject"))
throw new ArgumentException(string.Format("The group [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", group.DistinguishedName), "DevicesLinkedGroup");
throw new ArgumentException($"The group [{group.DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", "DevicesLinkedGroup");
GroupId = group.Id;
@@ -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<string>("sAMAccountName"));
var id = $@"{scopeAccount.Domain.NetBiosName}\{scopeAccount.Value<string>("sAMAccountName")}";
accountDNCache[id] = scopeAccount.Value<string>("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<bool>("isCriticalSystemObject"))
throw new InvalidOperationException(string.Format("This group [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", adGroup.DistinguishedName));
throw new InvalidOperationException($"This group [{adGroup.DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it");
var adGroupEntryMembers = adGroupEntry.Entry.Properties["member"];
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<string>("sAMAccountName"));
var id = $@"{scopeAccount.Domain.NetBiosName}\{scopeAccount.Value<string>("sAMAccountName")}";
accountDNCache[id] = Tuple.Create(scopeAccount.Value<string>("distinguishedName"), scopeAccount.Value<string>("displayName") ?? scopeAccount.Value<string>("name"));
}
}
@@ -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<bool>("isCriticalSystemObject"))
throw new InvalidOperationException(string.Format("This group [{0}] is a Critical System Active Directory Object and Disco ICT refuses to modify it", adGroup.DistinguishedName));
throw new InvalidOperationException($"This group [{adGroup.DistinguishedName}] is a Critical System Active Directory Object and Disco ICT refuses to modify it");
// Update Description
var groupDescription = string.Format("Disco ICT: {0}", actionGroup.Item1.GroupDescription);
var groupDescription = $"Disco ICT: {actionGroup.Item1.GroupDescription}";
if (adGroupEntry.Entry.Properties.Value<string>("description") != groupDescription)
{
var adGroupEntryDescription = adGroupEntry.Entry.Properties["description"];
+6 -6
View File
@@ -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);
});
}
@@ -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()
@@ -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
@@ -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))
+7 -7
View File
@@ -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) ? "<no reason provided>" : Reason)
Comments = $"# Waiting on User Action\r\n{(string.IsNullOrWhiteSpace(Reason) ? "<no reason provided>" : 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) ? "<no comment provided>" : Resolution)
Comments = $"# User Action Resolved\r\n{(string.IsNullOrWhiteSpace(Resolution) ? "<no comment provided>" : 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 ?? "<none>", FaultDescription)
Comments = $"# Manual Warranty Claim Submitted\r\nProvider: **{ManualProviderName}**\r\nAddress: **{Address.Name}**\r\nReference: **{ManualProviderReference ?? "<none>"}**\r\n___\r\n```{FaultDescription}```"
};
Database.JobLogs.Add(jobLog);
}
@@ -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 ?? "<none>", FaultDescription)
Comments = $"# Manual Repair Request Submitted\r\nProvider: **{ManualProviderName}**\r\nAddress: **{Address.Name}**\r\nReference: **{ManualProviderReference ?? "<none>"}**\r\n___\r\n```{FaultDescription}```"
};
Database.JobLogs.Add(jobLog);
}
+1 -2
View File
@@ -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<JobSubType> SubTypes, bool AddComponents, User TechUser)
@@ -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)
@@ -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) ? "<no comment>" : jqj.RemovedComment)
Comments = $"# Removed from Queue\r\n**{queue.Name}**\r\n{(string.IsNullOrWhiteSpace(jqj.RemovedComment) ? "<no comment>" : 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
+3 -3
View File
@@ -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}");
}
}
@@ -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;
}
+2 -2
View File
@@ -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}");
}
}
@@ -56,10 +56,10 @@ namespace Disco.Services.Plugins.Features.UIExtension
page.WriteLiteral("\n<div id=\"layout_uiExtensions\">");
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<!-- BEGIN UI EXTENSION: {0} -->\n", extensionDescription));
string extensionDescription = HttpUtility.HtmlEncode($"{uiExtResult.Source.Id} @ {uiExtResult.Source.PluginManifest.Id} v{uiExtResult.Source.PluginManifest.Version.ToString(4)}");
page.WriteLiteral($"\n<!-- BEGIN UI EXTENSION: {extensionDescription} -->\n");
uiExtResult.ExecuteResult(page);
page.WriteLiteral(string.Format("\n<!-- END UI EXTENSION: {0} -->", extensionDescription));
page.WriteLiteral($"\n<!-- END UI EXTENSION: {extensionDescription} -->");
}
page.WriteLiteral("\n</div>");
page.WriteLiteral("\n<!-- END: Disco ICT UI Extensions -->");
+5 -5
View File
@@ -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<Assembly>() { 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");
}
}
@@ -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}]";
}
}
+1 -1
View File
@@ -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)}";
}
}
}
+2 -2
View File
@@ -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);
@@ -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}]");
}
/// <summary>
@@ -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()
{
+12 -12
View File
@@ -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<PluginAttribute>(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<string, DateTime> 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<string, object>() { { "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}]";
}
}
}
+1 -1
View File
@@ -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)
{
@@ -173,7 +173,7 @@ namespace Disco.Services.Plugins
var filters = methodInfo.GetCustomAttributes<FilterAttribute>(true).OfType<IAuthorizationFilter>().ToList();
foreach (var authorizer in filters.OfType<DiscoAuthorizeBaseAttribute>())
authorizer.AuthorizeResource = string.Format("[Plugin]::{0}::{1}", controllerDescription.Manifest.Id, methodInfo.Name);
authorizer.AuthorizeResource = $"[Plugin]::{controllerDescription.Manifest.Id}::{methodInfo.Name}";
return filters.ToArray();
}
+9 -9
View File
@@ -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);
}
}
}
@@ -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);
@@ -27,7 +27,7 @@ namespace Disco.Services.Plugins
{
get
{
return string.Format("Unknown Plugin Id: [{0}]", _pluginRequested);
return $"Unknown Plugin Id: [{_pluginRequested}]";
}
}
}
+5 -5
View File
@@ -187,8 +187,8 @@ namespace Disco.Services.Plugins
if (string.IsNullOrEmpty(packageTempFilePath))
{
// 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)
+1 -1
View File
@@ -130,7 +130,7 @@ namespace Disco.Services.Tasks
{
var existingGuid = _RunningTasks.Where(t => t.IsRunning && t.TaskType == taskType).Select(t => t.SessionId).FirstOrDefault();
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);
}
+1 -1
View File
@@ -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)
@@ -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<UserFlagAssignment> 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;
}
@@ -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();
+4 -4
View File
@@ -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("<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />", bundleUrl);
return $"<link href=\"{bundleUrl}\" rel=\"stylesheet\" type=\"text/css\" />";
case "text/javascript":
return string.Format("<script src=\"{0}\" type=\"text/javascript\"></script>", bundleUrl);
return $"<script src=\"{bundleUrl}\" type=\"text/javascript\"></script>";
default:
throw new ArgumentException("Unsupported Bundle Content Type", "BundleUrl");
}
+3 -3
View File
@@ -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()
+1 -1
View File
@@ -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);
}