Skip to content

Commit

Permalink
Common: Further Improvements/Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
gus33000 committed Oct 15, 2023
1 parent 1ef4375 commit d2fc91e
Show file tree
Hide file tree
Showing 54 changed files with 147 additions and 177 deletions.
10 changes: 5 additions & 5 deletions src/Applications/UUPDownload/Downloading/ReportProgress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ private static string GetProgressBarString(int perc)
return "[" + bases + "]";
}

public void Dispose()
{
mutex.Dispose();
}

public void Report(GeneralDownloadProgress e)
{
_ = mutex.WaitOne();
Expand Down Expand Up @@ -118,10 +123,5 @@ public void Report(GeneralDownloadProgress e)

mutex.ReleaseMutex();
}

public void Dispose()
{
throw new NotImplementedException();
}
}
}
6 changes: 3 additions & 3 deletions src/Cabinet/Cabinet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public override string ToString()

public class Cabinet
{
private readonly byte[] CabinetMagic = new byte[] { (byte)'M', (byte)'S', (byte)'C', (byte)'F' };
private readonly byte[] CabinetMagic = "MSCF"u8.ToArray();

private readonly CabinetHeader cabinetHeader;
private readonly IReadOnlyCollection<CabinetVolume> volumes;
Expand Down Expand Up @@ -429,7 +429,7 @@ public void ExtractAllFiles(string OutputDirectory, Action<int, string> progress
{
byte[] magic = cabinetBinaryReader.ReadBytes(2);

if (StructuralComparisons.StructuralComparer.Compare(magic, new byte[] { (byte)'C', (byte)'K' }) != 0)
if (StructuralComparisons.StructuralComparer.Compare(magic, "CK"u8.ToArray()) != 0)
{
throw new Exception("Bad Cabinet: Invalid Signature for MSZIP block");
}
Expand Down Expand Up @@ -554,7 +554,7 @@ public byte[] ReadFile(string FileName)
{
byte[] magic = cabinetBinaryReader.ReadBytes(2);

if (StructuralComparisons.StructuralComparer.Compare(magic, new byte[] { (byte)'C', (byte)'K' }) != 0)
if (StructuralComparisons.StructuralComparer.Compare(magic, "CK"u8.ToArray()) != 0)
{
throw new Exception("Bad Cabinet: Invalid Signature for MSZIP block");
}
Expand Down
8 changes: 4 additions & 4 deletions src/Cabinet/Structures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@ internal enum CFFILEATTRIBUTES : ushort
A_NAME_IS_UTF = 1 << 8,
}

internal DateTime GetDateTime()
internal readonly DateTime GetDateTime()
{
return new DateTime(((date >> 9) & 0b1111_111) + 1980, (date >> 5) & 0b1111, date & 0b1111_1, (time >> 11) & 0b1111_1, (time >> 5) & 0b1111_11, (time & 0b1111_1) * 2);
}

internal FileAttributes GetFileAttributes()
internal readonly FileAttributes GetFileAttributes()
{
FileAttributes a = 0;

Expand All @@ -129,12 +129,12 @@ internal FileAttributes GetFileAttributes()
return a;
}

internal bool IsFileNameUTF8()
internal readonly bool IsFileNameUTF8()
{
return (attribs & CFFILEATTRIBUTES.A_NAME_IS_UTF) != 0;
}

internal bool ShouldBeExecutedAfterExtraction()
internal readonly bool ShouldBeExecutedAfterExtraction()
{
return (attribs & CFFILEATTRIBUTES.A_EXEC) != 0;
}
Expand Down
4 changes: 1 addition & 3 deletions src/CompDB/Applications/AppxApplicabilityEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,7 @@ private static double CalculateScaleFactorScore(int target, int candidate)
/// <returns></returns>
internal static double GetScaleFactorScore(int target, int candidate)
{
return (double)(BuiltInScaleFactorScores.ContainsKey(target) && BuiltInScaleFactorScores[target].ContainsKey(candidate)
? BuiltInScaleFactorScores[target][candidate]
: CalculateScaleFactorScore(target, candidate));
return (double)(BuiltInScaleFactorScores.TryGetValue(target, out Dictionary<int, double> scaleFactorScoreDictionary) && scaleFactorScoreDictionary.TryGetValue(candidate, out double scaleFactorScore) ? scaleFactorScore : CalculateScaleFactorScore(target, candidate));
}
}
}
6 changes: 3 additions & 3 deletions src/CompDB/CompDB.cs
Original file line number Diff line number Diff line change
Expand Up @@ -274,12 +274,12 @@ public Features Features
get; set;
}
[XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
public string xsi
public string Xsi
{
get; set;
}
[XmlAttribute(AttributeName = "xsd", Namespace = "http://www.w3.org/2000/xmlns/")]
public string xsd
public string Xsd
{
get; set;
}
Expand Down Expand Up @@ -339,7 +339,7 @@ public string Name
get; set;
}
[XmlAttribute(AttributeName = "xmlns", Namespace = "http://schemas.microsoft.com/embedded/2004/10/ImageUpdate")]
public string xmlns
public string Xmlns
{
get; set;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

namespace UnifiedUpdatePlatform.Services.WindowsUpdate.Downloads
{
public static class UpdateUtils
public static partial class UpdateUtils
{
public static string[] GetFilenameForCEUIFile(CExtendedUpdateInfoXml.File file2, IEnumerable<CompDBXmlClass.PayloadItem> payloadItems)
{
Expand Down Expand Up @@ -151,7 +151,7 @@ private static
// Get edition + language
case (true, true):
{
if (((!hasEdition && !hasLang) || (!hasEdition && hasLang && langMatching) || (!hasLang && hasEdition && editionMatching) || (hasEdition && hasLang && langMatching && editionMatching)) && !IsNeutral)
if ((!hasEdition && !hasLang || !hasEdition && hasLang && langMatching || !hasLang && hasEdition && editionMatching || hasEdition && hasLang && langMatching && editionMatching) && !IsNeutral)
{
_ = specificCompDBs.Add(cdb);
_ = selectedCompDBs.Add(cdb);
Expand Down Expand Up @@ -497,7 +497,7 @@ await Task.WhenAll(
}

string name = $"{buildstr.Replace(" ", ".").Replace("(", "").Replace(")", "")}_{MachineType.ToString().ToLower()}fre_{update.Xml.UpdateIdentity.UpdateID.Split("-").Last()}";
Regex illegalCharacters = new(@"[\\/:*?""<>|]");
Regex illegalCharacters = invalidCharactersRegex();
name = illegalCharacters.Replace(name, "");
string OutputFolder = pOutputFolder;
if (UseAutomaticDownloadFolder)
Expand All @@ -510,20 +510,14 @@ await Task.WhenAll(

do
{
IEnumerable<FileExchangeV3FileDownloadInformation> fileUrls = await FE3Handler.GetFileUrls(update);

if (fileUrls == null)
{
throw new Exception("Getting file urls failed.");
}

IEnumerable<FileExchangeV3FileDownloadInformation> fileUrls = await FE3Handler.GetFileUrls(update) ?? throw new Exception("Getting file urls failed.");
if (!Directory.Exists(OutputFolder))
{
_ = Directory.CreateDirectory(OutputFolder);
}

string tmpname = update.Xml.LocalizedProperties.Title + " (" + MachineType.ToString() + ").uupmcreplay";
illegalCharacters = new Regex(@"[\\/:*?""<>|]");
illegalCharacters = invalidCharactersRegex();
tmpname = illegalCharacters.Replace(tmpname, "");
string filename = Path.Combine(OutputFolder, tmpname);

Expand Down Expand Up @@ -556,7 +550,7 @@ await Task.WhenAll(
string payloadHash = pkg.Payload.PayloadItem[0].PayloadHash;
if (payloadHash == boundFile.Item1.AdditionalDigest.Text || payloadHash == boundFile.Item1.Digest)
{
if (pkg.ID.Contains("-") && pkg.ID.Contains(".inf", StringComparison.InvariantCultureIgnoreCase))
if (pkg.ID.Contains('-') && pkg.ID.Contains(".inf", StringComparison.InvariantCultureIgnoreCase))
{
path = pkg.ID.Split("-")[1].Replace(".inf", ".cab").Replace(".INF", ".CAB");
}
Expand Down Expand Up @@ -587,5 +581,8 @@ await Task.WhenAll(

return OutputFolder;
}

[GeneratedRegex("[\\\\/:*?\"<>|]")]
private static partial Regex invalidCharactersRegex();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,8 @@ public HttpDownloader(string downloadFolderPath, int downloadThreads = 4, bool v
{
HttpClientHandler filter = new()
{
#if NET5_0_OR_GREATER
AutomaticDecompression = DecompressionMethods.All,
MaxConnectionsPerServer = 512,
#else
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
#endif
};

if (proxy != null || !useSystemProxy)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static Guid Class5GuidFromString(string input)
private static byte[] GetPartialHash(string input)
{
byte[] partialHash;
using (SHA1CryptoServiceProvider sha1Csp = new())
using (SHA1 sha1Csp = SHA1.Create())
{
_ = sha1Csp.TransformBlock(hwidIv, 0, hwidIv.Length, null, 0);
byte[] dataBin = Encoding.Unicode.GetBytes(input);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ internal void Init()
isInitialized = true;
}

protected static int getCllSettingsAsInt(Settings setting)
protected static int GetCllSettingsAsInt(Settings setting)
{
int asInt = (int)setting;
return asInt;
Expand All @@ -80,7 +80,7 @@ private bool CanExtend()
{
int vectorSize = (int)Math.Floor(Math.Log10(currentVector) + 1);

return baseVector.Length + 1 + vectorSize + 1 + 1 <= getCllSettingsAsInt(Settings.MAXCORRELATIONVECTORLENGTH);
return baseVector.Length + 1 + vectorSize + 1 + 1 <= GetCllSettingsAsInt(Settings.MAXCORRELATIONVECTORLENGTH);
}

private bool CanIncrement(int newVector)
Expand All @@ -92,7 +92,7 @@ private bool CanIncrement(int newVector)
int vectorSize = (int)Math.Floor(Math.Log10(newVector) + 1);

// Get the length of the existing string + length of the new extension + the length of the dot
return baseVector.Length + vectorSize + 1 <= getCllSettingsAsInt(Settings.MAXCORRELATIONVECTORLENGTH);
return baseVector.Length + vectorSize + 1 <= GetCllSettingsAsInt(Settings.MAXCORRELATIONVECTORLENGTH);
}

internal string Extend()
Expand Down Expand Up @@ -135,7 +135,7 @@ internal string Increment()

private bool IsValid(string vector)
{
if (vector.Length > getCllSettingsAsInt(Settings.MAXCORRELATIONVECTORLENGTH))
if (vector.Length > GetCllSettingsAsInt(Settings.MAXCORRELATIONVECTORLENGTH))
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,24 +69,15 @@ public async Task DecryptBufferToStreamAsync(byte[] buffer, Stream to, int buffe
using ICryptoTransform dec = aes.CreateDecryptor(key, newIv);
using MemoryStream ms = new(buffer, 0, bufferLength);
using CryptoStream cs = new(ms, dec, CryptoStreamMode.Read);

#if NET5_0_OR_GREATER
await cs.CopyToAsync(to, cancellationToken);
#else
await cs.CopyToAsync(to);
#endif
}

public async Task DecryptStreamFullAsync(Stream encryptedFile, Stream decryptedFile, ulong encryptedSize,
CancellationToken cancellationToken = default)
{
int readBytes;
byte[] buffer = new byte[esrp.EncryptionBufferSize];
#if NET5_0_OR_GREATER
while ((readBytes = await encryptedFile.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken)) > 0)
#else
while ((readBytes = await encryptedFile.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) > 0)
#endif
{
bool needsPaddingMode = encryptedSize == (ulong)encryptedFile.Position;
long previousSumBlockLength = encryptedFile.Position - readBytes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,7 +989,7 @@ public SecurityData SecurityData
public class SecurityData
{
[XmlElement(ElementName = "base64Binary", Namespace = Constants.ClientWebServiceServerNamespace)]
public string base64Binary
public string Base64Binary
{
get; set;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private static async Task<string> GetBearerTokenForScope(string email, string pa
if (oLocationBit.Contains("access_token"))
{
retVal = oLocationBit[(oLocationBit.IndexOf("access_token") + 13)..];
if (retVal.Contains("&"))
if (retVal.Contains('&'))
{
retVal = retVal[..retVal.IndexOf('&')];
}
Expand Down
30 changes: 15 additions & 15 deletions src/VirtualHardDiskLib/NativeMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

namespace VirtualHardDiskLib
{
internal static class NativeMethods
internal static partial class NativeMethods
{
[Flags]
public enum ATTACH_VIRTUAL_DISK_FLAG
Expand Down Expand Up @@ -83,18 +83,18 @@ public enum VIRTUAL_DISK_ACCESS_MASK
public static readonly Guid VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT =
new("EC984AEC-A0F9-47e9-901F-71415A66345B");

[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern int AttachVirtualDisk(IntPtr VirtualDiskHandle, IntPtr SecurityDescriptor,
[LibraryImport("virtdisk.dll")]
public static partial int AttachVirtualDisk(IntPtr VirtualDiskHandle, IntPtr SecurityDescriptor,
ATTACH_VIRTUAL_DISK_FLAG Flags, int ProviderSpecificFlags, ref ATTACH_VIRTUAL_DISK_PARAMETERS Parameters,
IntPtr Overlapped);

[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern int DetachVirtualDisk(IntPtr VirtualDiskHandle, DETACH_VIRTUAL_DISK_FLAG Flags,
[LibraryImport("virtdisk.dll")]
public static partial int DetachVirtualDisk(IntPtr VirtualDiskHandle, DETACH_VIRTUAL_DISK_FLAG Flags,
int ProviderSpecificFlags);

[DllImport("kernel32.dll", SetLastError = true)]
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
public static partial bool CloseHandle(IntPtr hObject);

[DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
public static extern int OpenVirtualDisk(ref VIRTUAL_STORAGE_TYPE VirtualStorageType, string Path,
Expand Down Expand Up @@ -140,24 +140,24 @@ public struct VIRTUAL_STORAGE_TYPE
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindFirstVolume([MarshalAs(UnmanagedType.LPWStr)] StringBuilder volumeName, int bufferLength);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindVolumeClose(IntPtr findVolumeHandle);
public static partial bool FindVolumeClose(IntPtr findVolumeHandle);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindNextVolume(IntPtr findVolumeHandle, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder volumeName, int bufferLength);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPWStr)] string fileName, GENERIC_ACCESS_RIGHTS_FLAGS desiredAccess, FILE_SHARE_MODE_FLAGS shareMode, IntPtr securityAttribute, CREATION_DISPOSITION_FLAGS creationDisposition, int flagsAndAttributes, IntPtr templateFile);
[LibraryImport("kernel32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial IntPtr CreateFile([MarshalAs(UnmanagedType.LPWStr)] string fileName, GENERIC_ACCESS_RIGHTS_FLAGS desiredAccess, FILE_SHARE_MODE_FLAGS shareMode, IntPtr securityAttribute, CREATION_DISPOSITION_FLAGS creationDisposition, int flagsAndAttributes, IntPtr templateFile);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeviceIoControl(IntPtr deviceHandle, IO_CONTROL_CODE controlCode, IntPtr inBuffer, uint inBufferSize, ref STORAGE_DEVICE_NUMBER outBuffer, uint outBufferSize, ref uint bytesReturned, IntPtr overlapped);
public static partial bool DeviceIoControl(IntPtr deviceHandle, IO_CONTROL_CODE controlCode, IntPtr inBuffer, uint inBufferSize, ref STORAGE_DEVICE_NUMBER outBuffer, uint outBufferSize, ref uint bytesReturned, IntPtr overlapped);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string mountPoint, [MarshalAs(UnmanagedType.LPWStr)] string volumeName);
public static partial bool SetVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string mountPoint, [MarshalAs(UnmanagedType.LPWStr)] string volumeName);

public static IntPtr INVALID_HANDLE_VALUE = -1;

Expand Down
12 changes: 6 additions & 6 deletions src/VirtualHardDiskLib/VHDUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ internal static int MountVirtualDisk(string vhdfile)
attachResult));
}

int num = _findVhdPhysicalDriveNumber(handle);
int num = FindVhdPhysicalDriveNumber(handle);

// close handle to disk
_ = NativeMethods.CloseHandle(handle);
Expand Down Expand Up @@ -151,7 +151,7 @@ internal static void DismountVirtualDisk(string vhdfile)
_ = NativeMethods.CloseHandle(handle);
}

private static int _findVhdPhysicalDriveNumber(IntPtr vhdHandle)
private static int FindVhdPhysicalDriveNumber(IntPtr vhdHandle)
{
int bufferSize = 260;
StringBuilder vhdPhysicalPath = new(bufferSize);
Expand All @@ -161,7 +161,7 @@ private static int _findVhdPhysicalDriveNumber(IntPtr vhdHandle)
return driveNumber;
}

private static string _findVhdVolumePath(int vhdPhysicalDrive)
private static string FindVhdVolumePath(int vhdPhysicalDrive)
{
StringBuilder volumeName = new(260);
IntPtr findVolumeHandle;
Expand Down Expand Up @@ -198,7 +198,7 @@ private static string _findVhdVolumePath(int vhdPhysicalDrive)
return found ? volumeName.ToString() : ""; //when It returns "" then the error occurs
}

private static void _mountVhdToDriveLetter(string vhdVolumePath, string mountPoint)
private static void MountVhdToDriveLetter(string vhdVolumePath, string mountPoint)
{
if (vhdVolumePath[^1] != Path.DirectorySeparatorChar)
{
Expand All @@ -214,8 +214,8 @@ private static void _mountVhdToDriveLetter(string vhdVolumePath, string mountPoi
internal static void AttachDriveLetterToDiskAndPartitionId(int diskid, int partid, char driveletter)
{
RemoveFileExplorerAutoRun(driveletter);
string volpath = _findVhdVolumePath(diskid);
_mountVhdToDriveLetter(volpath, driveletter + ":\\");
string volpath = FindVhdVolumePath(diskid);
MountVhdToDriveLetter(volpath, driveletter + ":\\");
}

/// <summary>
Expand Down
Loading

0 comments on commit d2fc91e

Please sign in to comment.