Null handling for logger

pull/32/head
Pat Hartl 2023-11-10 20:53:28 -06:00
parent 73b542856a
commit 5237e88612
7 changed files with 47 additions and 47 deletions

View File

@ -146,7 +146,7 @@ namespace LANCommander.SDK
public AuthToken RefreshToken(AuthToken token) public AuthToken RefreshToken(AuthToken token)
{ {
Logger.LogTrace("Refreshing token..."); Logger?.LogTrace("Refreshing token...");
var request = new RestRequest("/api/Auth/Refresh") var request = new RestRequest("/api/Auth/Refresh")
.AddJsonBody(token); .AddJsonBody(token);
@ -173,11 +173,11 @@ namespace LANCommander.SDK
public bool ValidateToken(AuthToken token) public bool ValidateToken(AuthToken token)
{ {
Logger.LogTrace("Validating token..."); Logger?.LogTrace("Validating token...");
if (token == null) if (token == null)
{ {
Logger.LogTrace("Token is null!"); Logger?.LogTrace("Token is null!");
return false; return false;
} }
@ -186,7 +186,7 @@ namespace LANCommander.SDK
if (String.IsNullOrEmpty(token.AccessToken) || String.IsNullOrEmpty(token.RefreshToken)) if (String.IsNullOrEmpty(token.AccessToken) || String.IsNullOrEmpty(token.RefreshToken))
{ {
Logger.LogTrace("Token is empty!"); Logger?.LogTrace("Token is empty!");
return false; return false;
} }
@ -195,9 +195,9 @@ namespace LANCommander.SDK
var valid = response.StatusCode == HttpStatusCode.OK; var valid = response.StatusCode == HttpStatusCode.OK;
if (valid) if (valid)
Logger.LogTrace("Token is valid!"); Logger?.LogTrace("Token is valid!");
else else
Logger.LogTrace("Token is invalid!"); Logger?.LogTrace("Token is invalid!");
return response.StatusCode == HttpStatusCode.OK; return response.StatusCode == HttpStatusCode.OK;
} }
@ -254,7 +254,7 @@ namespace LANCommander.SDK
public GameSave UploadSave(string gameId, byte[] data) public GameSave UploadSave(string gameId, byte[] data)
{ {
Logger.LogTrace("Uploading save..."); Logger?.LogTrace("Uploading save...");
var request = new RestRequest($"/api/Saves/Upload/{gameId}", Method.POST) var request = new RestRequest($"/api/Saves/Upload/{gameId}", Method.POST)
.AddHeader("Authorization", $"Bearer {Token.AccessToken}"); .AddHeader("Authorization", $"Bearer {Token.AccessToken}");
@ -273,7 +273,7 @@ namespace LANCommander.SDK
public string GetKey(Guid id) public string GetKey(Guid id)
{ {
Logger.LogTrace("Requesting key allocation..."); Logger?.LogTrace("Requesting key allocation...");
var macAddress = GetMacAddress(); var macAddress = GetMacAddress();
@ -292,7 +292,7 @@ namespace LANCommander.SDK
public string GetAllocatedKey(Guid id) public string GetAllocatedKey(Guid id)
{ {
Logger.LogTrace("Requesting allocated key..."); Logger?.LogTrace("Requesting allocated key...");
var macAddress = GetMacAddress(); var macAddress = GetMacAddress();
@ -314,7 +314,7 @@ namespace LANCommander.SDK
public string GetNewKey(Guid id) public string GetNewKey(Guid id)
{ {
Logger.LogTrace("Requesting new key allocation..."); Logger?.LogTrace("Requesting new key allocation...");
var macAddress = GetMacAddress(); var macAddress = GetMacAddress();
@ -336,14 +336,14 @@ namespace LANCommander.SDK
public User GetProfile() public User GetProfile()
{ {
Logger.LogTrace("Requesting player's profile..."); Logger?.LogTrace("Requesting player's profile...");
return GetRequest<User>("/api/Profile"); return GetRequest<User>("/api/Profile");
} }
public string ChangeAlias(string alias) public string ChangeAlias(string alias)
{ {
Logger.LogTrace("Requesting to change player alias..."); Logger?.LogTrace("Requesting to change player alias...");
var response = PostRequest<object>("/api/Profile/ChangeAlias", alias); var response = PostRequest<object>("/api/Profile/ChangeAlias", alias);

View File

@ -41,11 +41,11 @@ namespace LANCommander.SDK
{ {
var game = Client.GetGame(gameId); var game = Client.GetGame(gameId);
Logger.LogTrace("Installing game {GameTitle} (GameId)", game.Title, game.Id); Logger?.LogTrace("Installing game {GameTitle} (GameId)", game.Title, game.Id);
var result = RetryHelper.RetryOnException<ExtractionResult>(maxAttempts, TimeSpan.FromMilliseconds(500), new ExtractionResult(), () => var result = RetryHelper.RetryOnException<ExtractionResult>(maxAttempts, TimeSpan.FromMilliseconds(500), new ExtractionResult(), () =>
{ {
Logger.LogTrace("Attempting to download and extract game"); Logger?.LogTrace("Attempting to download and extract game");
return DownloadAndExtract(game); return DownloadAndExtract(game);
}); });
@ -61,7 +61,7 @@ namespace LANCommander.SDK
var writeManifestSuccess = RetryHelper.RetryOnException(maxAttempts, TimeSpan.FromSeconds(1), false, () => var writeManifestSuccess = RetryHelper.RetryOnException(maxAttempts, TimeSpan.FromSeconds(1), false, () =>
{ {
Logger.LogTrace("Attempting to get game manifest"); Logger?.LogTrace("Attempting to get game manifest");
manifest = Client.GetGameManifest(game.Id); manifest = Client.GetGameManifest(game.Id);
@ -73,7 +73,7 @@ namespace LANCommander.SDK
if (!writeManifestSuccess) if (!writeManifestSuccess)
throw new Exception("Could not grab the manifest file. Retry the install or check your connection"); throw new Exception("Could not grab the manifest file. Retry the install or check your connection");
Logger.LogTrace("Saving scripts"); Logger?.LogTrace("Saving scripts");
ScriptHelper.SaveScript(game, ScriptType.Install); ScriptHelper.SaveScript(game, ScriptType.Install);
ScriptHelper.SaveScript(game, ScriptType.Uninstall); ScriptHelper.SaveScript(game, ScriptType.Uninstall);
@ -91,7 +91,7 @@ namespace LANCommander.SDK
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, "Could not execute post-install scripts"); Logger?.LogError(ex, "Could not execute post-install scripts");
} }
return result.Directory; return result.Directory;
@ -103,27 +103,27 @@ namespace LANCommander.SDK
try try
{ {
Logger.LogTrace("Running uninstall script"); Logger?.LogTrace("Running uninstall script");
PowerShellRuntime.RunScript(installDirectory, ScriptType.Uninstall); PowerShellRuntime.RunScript(installDirectory, ScriptType.Uninstall);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, "Error running uninstall script"); Logger?.LogError(ex, "Error running uninstall script");
} }
Logger.LogTrace("Attempting to delete the install directory"); Logger?.LogTrace("Attempting to delete the install directory");
if (Directory.Exists(installDirectory)) if (Directory.Exists(installDirectory))
Directory.Delete(installDirectory, true); Directory.Delete(installDirectory, true);
Logger.LogTrace("Deleted install directory {InstallDirectory}", installDirectory); Logger?.LogTrace("Deleted install directory {InstallDirectory}", installDirectory);
} }
private ExtractionResult DownloadAndExtract(Game game, string installDirectory = "") private ExtractionResult DownloadAndExtract(Game game, string installDirectory = "")
{ {
if (game == null) if (game == null)
{ {
Logger.LogTrace("Game failed to download, no game was specified"); Logger?.LogTrace("Game failed to download, no game was specified");
throw new ArgumentNullException("No game was specified"); throw new ArgumentNullException("No game was specified");
} }
@ -133,7 +133,7 @@ namespace LANCommander.SDK
var destination = Path.Combine(installDirectory, game.Title.SanitizeFilename()); var destination = Path.Combine(installDirectory, game.Title.SanitizeFilename());
Logger.LogTrace("Downloading and extracting {Game} to path {Destination}", game.Title, destination); Logger?.LogTrace("Downloading and extracting {Game} to path {Destination}", game.Title, destination);
try try
{ {
@ -173,11 +173,11 @@ namespace LANCommander.SDK
} }
else else
{ {
Logger.LogError(ex, "Could not extract to path {Destination}", destination); Logger?.LogError(ex, "Could not extract to path {Destination}", destination);
if (Directory.Exists(destination)) if (Directory.Exists(destination))
{ {
Logger.LogTrace("Cleaning up orphaned install files after bad install"); Logger?.LogTrace("Cleaning up orphaned install files after bad install");
Directory.Delete(destination, true); Directory.Delete(destination, true);
} }
@ -196,7 +196,7 @@ namespace LANCommander.SDK
extractionResult.Success = true; extractionResult.Success = true;
extractionResult.Directory = destination; extractionResult.Directory = destination;
Logger.LogTrace("Game {Game} successfully downloaded and extracted to {Destination}", game.Title, destination); Logger?.LogTrace("Game {Game} successfully downloaded and extracted to {Destination}", game.Title, destination);
} }
return extractionResult; return extractionResult;

View File

@ -23,7 +23,7 @@ namespace LANCommander.SDK.Helpers
.WithNamingConvention(PascalCaseNamingConvention.Instance) .WithNamingConvention(PascalCaseNamingConvention.Instance)
.Build(); .Build();
Logger.LogTrace("Deserializing manifest"); Logger?.LogTrace("Deserializing manifest");
var manifest = deserializer.Deserialize<GameManifest>(source); var manifest = deserializer.Deserialize<GameManifest>(source);
@ -34,17 +34,17 @@ namespace LANCommander.SDK.Helpers
{ {
var destination = GetPath(installDirectory); var destination = GetPath(installDirectory);
Logger.LogTrace("Attempting to write manifest to path {Destination}", destination); Logger?.LogTrace("Attempting to write manifest to path {Destination}", destination);
var serializer = new SerializerBuilder() var serializer = new SerializerBuilder()
.WithNamingConvention(PascalCaseNamingConvention.Instance) .WithNamingConvention(PascalCaseNamingConvention.Instance)
.Build(); .Build();
Logger.LogTrace("Serializing manifest"); Logger?.LogTrace("Serializing manifest");
var yaml = serializer.Serialize(manifest); var yaml = serializer.Serialize(manifest);
Logger.LogTrace("Writing manifest file"); Logger?.LogTrace("Writing manifest file");
File.WriteAllText(destination, yaml); File.WriteAllText(destination, yaml);
} }

View File

@ -16,14 +16,14 @@ namespace LANCommander.SDK.Helpers
{ {
try try
{ {
Logger.LogTrace($"Attempt #{attempts + 1}/{maxAttempts}..."); Logger?.LogTrace($"Attempt #{attempts + 1}/{maxAttempts}...");
attempts++; attempts++;
return action(); return action();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"Attempt failed!"); Logger?.LogError(ex, $"Attempt failed!");
if (attempts >= maxAttempts) if (attempts >= maxAttempts)
return @default; return @default;

View File

@ -20,7 +20,7 @@ namespace LANCommander.SDK.Helpers
// PowerShell will only run scripts with the .ps1 file extension // PowerShell will only run scripts with the .ps1 file extension
File.Move(tempPath, tempPath + ".ps1"); File.Move(tempPath, tempPath + ".ps1");
Logger.LogTrace("Writing script {Script} to {Destination}", script.Name, tempPath); Logger?.LogTrace("Writing script {Script} to {Destination}", script.Name, tempPath);
File.WriteAllText(tempPath, script.Contents); File.WriteAllText(tempPath, script.Contents);
@ -42,7 +42,7 @@ namespace LANCommander.SDK.Helpers
if (File.Exists(filename)) if (File.Exists(filename))
File.Delete(filename); File.Delete(filename);
Logger.LogTrace("Writing {ScriptType} script to {Destination}", type, filename); Logger?.LogTrace("Writing {ScriptType} script to {Destination}", type, filename);
File.WriteAllText(filename, script.Contents); File.WriteAllText(filename, script.Contents);
} }

View File

@ -24,11 +24,11 @@ namespace LANCommander.SDK
public static void RunCommand(string command, bool asAdmin = false) public static void RunCommand(string command, bool asAdmin = false)
{ {
Logger.LogTrace($"Executing command `{command}` | Admin: {asAdmin}"); Logger?.LogTrace($"Executing command `{command}` | Admin: {asAdmin}");
var tempScript = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".ps1"); var tempScript = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".ps1");
Logger.LogTrace($"Creating temp script at path {tempScript}"); Logger?.LogTrace($"Creating temp script at path {tempScript}");
File.WriteAllText(tempScript, command); File.WriteAllText(tempScript, command);
@ -39,7 +39,7 @@ namespace LANCommander.SDK
public static int RunScript(string path, bool asAdmin = false, string arguments = null, string workingDirectory = null) public static int RunScript(string path, bool asAdmin = false, string arguments = null, string workingDirectory = null)
{ {
Logger.LogTrace($"Executing script at path {path} | Admin: {asAdmin} | Arguments: {arguments}"); Logger?.LogTrace($"Executing script at path {path} | Admin: {asAdmin} | Arguments: {arguments}");
var wow64Value = IntPtr.Zero; var wow64Value = IntPtr.Zero;
@ -98,7 +98,7 @@ namespace LANCommander.SDK
// Concatenate scripts // Concatenate scripts
var sb = new StringBuilder(); var sb = new StringBuilder();
Logger.LogTrace("Concatenating scripts..."); Logger?.LogTrace("Concatenating scripts...");
foreach (var path in paths) foreach (var path in paths)
{ {
@ -106,16 +106,16 @@ namespace LANCommander.SDK
sb.AppendLine(contents); sb.AppendLine(contents);
Logger.LogTrace($"Added {path}!"); Logger?.LogTrace($"Added {path}!");
} }
Logger.LogTrace("Done concatenating!"); Logger?.LogTrace("Done concatenating!");
if (sb.Length > 0) if (sb.Length > 0)
{ {
var scriptPath = Path.GetTempFileName(); var scriptPath = Path.GetTempFileName();
Logger.LogTrace($"Creating temp script at path {scriptPath}"); Logger?.LogTrace($"Creating temp script at path {scriptPath}");
File.WriteAllText(scriptPath, sb.ToString()); File.WriteAllText(scriptPath, sb.ToString());

View File

@ -75,7 +75,7 @@ namespace LANCommander.SDK
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, "Redistributable {Redistributable} failed to install", redistributable.Name); Logger?.LogError(ex, "Redistributable {Redistributable} failed to install", redistributable.Name);
} }
finally finally
{ {
@ -94,13 +94,13 @@ namespace LANCommander.SDK
{ {
if (redistributable == null) if (redistributable == null)
{ {
Logger.LogTrace("Redistributable failed to download! No redistributable was specified"); Logger?.LogTrace("Redistributable failed to download! No redistributable was specified");
throw new ArgumentNullException("No redistributable was specified"); throw new ArgumentNullException("No redistributable was specified");
} }
var destination = Path.Combine(Path.GetTempPath(), redistributable.Name.SanitizeFilename()); var destination = Path.Combine(Path.GetTempPath(), redistributable.Name.SanitizeFilename());
Logger.LogTrace("Downloading and extracting {Redistributable} to path {Destination}", redistributable.Name, destination); Logger?.LogTrace("Downloading and extracting {Redistributable} to path {Destination}", redistributable.Name, destination);
try try
{ {
@ -134,11 +134,11 @@ namespace LANCommander.SDK
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, "Could not extract to path {Destination}", destination); Logger?.LogError(ex, "Could not extract to path {Destination}", destination);
if (Directory.Exists(destination)) if (Directory.Exists(destination))
{ {
Logger.LogTrace("Cleaning up orphaned files after bad install"); Logger?.LogTrace("Cleaning up orphaned files after bad install");
Directory.Delete(destination, true); Directory.Delete(destination, true);
} }
@ -155,7 +155,7 @@ namespace LANCommander.SDK
{ {
extractionResult.Success = true; extractionResult.Success = true;
extractionResult.Directory = destination; extractionResult.Directory = destination;
Logger.LogTrace("Redistributable {Redistributable} successfully downloaded and extracted to {Destination}", redistributable.Name, destination); Logger?.LogTrace("Redistributable {Redistributable} successfully downloaded and extracted to {Destination}", redistributable.Name, destination);
} }
return extractionResult; return extractionResult;