Skip to content

Commit

Permalink
Improve Serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
LoneWandererProductions committed Jun 8, 2024
1 parent bb82c4c commit b2fa02c
Show file tree
Hide file tree
Showing 10 changed files with 201 additions and 93 deletions.
Binary file modified CommonLibraryGuiTests/Image/example Polaris.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified CommonLibraryGuiTests/Image/example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 0 additions & 20 deletions CommonLibraryTests/PluginLoadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,26 +57,6 @@ public void GetFilesByExtensionFullPathInvalidPathReturnsNull()
Assert.IsNull(result);
}

/// <summary>
/// Gets the files by extension full path0 valid path no files returns empty list.
/// </summary>
[TestMethod]
public void GetFilesByExtensionFullPath0ValidPathNoFilesReturnsEmptyList()
{
// Arrange
var validPath = System.IO.Path.GetTempPath();
var extension = ".dll";

// Act
var result = InvokePrivateStaticMethod<IEnumerable<string>>(typeof(PluginLoad), "GetFilesByExtensionFullPath", validPath, extension);

// Assert
Assert.IsNotNull(result);
Assert.IsFalse(result.Any());
}

// Additional test methods to cover more scenarios can be added here

/// <summary>
/// Loads all no plugins found returns false.
/// </summary>
Expand Down
3 changes: 2 additions & 1 deletion CommonLibraryTests/Projections.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public void ProjectionTo2D()
const float fNear = 0.1f;
const float fFar = 1000.0f;
const float fFov = 90.0f;
const double fAspectRatio = (double)screenHeight / screenWidth;
//since a error was fixed this one will be switched just for this
const double fAspectRatio = (double)screenWidth / screenHeight;
var fFovRad = 1.0f / Math.Tan(fFov * 0.5f / 180.0f * 3.14159f);

Projection3DRegister.Width = screenWidth;
Expand Down
19 changes: 2 additions & 17 deletions CommonLibraryTests/Serialize.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,6 @@ public void TestSerializeDictionaryNullDictionaryThrowsException()
Serializer.Serialize.SaveDctObjectToXml((Dictionary<string, string>)null, path);
}

/// <summary>
/// Tests the serialize dictionary empty dictionary throws exception.
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestSerializeDictionaryEmptyDictionaryThrowsException()
{
// Arrange
var dictionary = new Dictionary<string, string>();
const string path = "test.xml";

// Act
Serializer.Serialize.SaveDctObjectToXml(dictionary, path);
}

/// <summary>
/// Tests the serialize dictionary valid dictionary creates XML file.
/// </summary>
Expand Down Expand Up @@ -135,8 +120,8 @@ public void TestSerializeDictionaryValidDictionaryCreatesXmlFile()
/// Tests the serialize dictionary invalid path throws exception.
/// </summary>
[TestMethod]
[ExpectedException(typeof(FileHandlerException))]
public void Test_SerializeDictionaryInvalidPathThrowsException()
[ExpectedException(typeof(Serializer.Serialize.SerializationException))]
public void TestSerializeDictionaryInvalidPathThrowsException()
{
// Arrange
var dictionary = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } };
Expand Down
2 changes: 1 addition & 1 deletion CoreLibrary.sln.DotSettings.user
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=22cef65f_002D8313_002D4418_002Db3ab_002D8f58fe7f8b2f/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" Name="CommonCtrl" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=22cef65f_002D8313_002D4418_002Db3ab_002D8f58fe7f8b2f/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="CommonCtrl" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
&lt;Solution /&gt;&#xD;
&lt;/SessionState&gt;</s:String>
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=fda52545_002De1eb_002D4d94_002D9d07_002Dd3c4be883354/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="SpeedConvertCif" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
Expand Down
2 changes: 1 addition & 1 deletion Mathematics/Projection3DRegister.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public static class Projection3DRegister
/// <value>
/// A, as Aspect Ratio
/// </value>
internal static double A => (double)Height / Width;
internal static double A => (double)Width / Height ;

/// <summary>
/// field of view, degree
Expand Down
88 changes: 53 additions & 35 deletions Serializer/DeSerialize.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using FileHandler;
using System.Text;

namespace Serializer
{
Expand All @@ -24,6 +26,43 @@ namespace Serializer
/// </summary>
public static class DeSerialize
{
/// <summary>
/// Logs the provided message. For demonstration purposes, this logs to the console.
/// In a real application, use a proper logging framework.
/// </summary>
/// <param name="message">The message to log.</param>
private static void Log(string message)
{
Trace.WriteLine($"[{DateTime.Now}] {message}");
}

/// <summary>
/// Validates that the file exists and is not empty.
/// </summary>
/// <param name="path">The file path.</param>
private static void ValidateFilePath(string path)
{
if (!FileHandleSearch.FileExists(path))
{
throw new ArgumentException($"{SerialResources.ErrorPath} {path}");
}

if (!FileContent(path))
{
throw new ArgumentException($"{SerialResources.ErrorFileEmpty} {path}");
}
}

/// <summary>
/// Checks if the file has content.
/// </summary>
/// <param name="path">The file path.</param>
/// <returns>True if file has content, false otherwise.</returns>
private static bool FileContent(string path)
{
return new FileInfo(path).Length != 0;
}

/// <summary>
/// Load the object from XML.
/// </summary>
Expand All @@ -36,13 +75,15 @@ public static class DeSerialize

try
{
using var reader = new StreamReader(path);
return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
using var reader = new StreamReader(path, Encoding.UTF8);
var result = new XmlSerializer(typeof(T)).Deserialize(reader) as T;
Log($"Object of type {typeof(T)} successfully deserialized from {path}");
return result;
}
catch (Exception ex) when (ex is InvalidOperationException or XmlException or NullReferenceException
or UnauthorizedAccessException or ArgumentException or IOException)
{
throw new Exception($"{SerialResources.ErrorSerializerXml} {ex.Message}", ex);
throw new Serialize.DeserializationException($"{SerialResources.ErrorSerializerXml} {ex.Message}", ex);
}
}

Expand All @@ -60,12 +101,14 @@ public static class DeSerialize
{
var serializer = new XmlSerializer(typeof(List<T>));
using var stream = new FileStream(path, FileMode.Open);
return (List<T>)serializer.Deserialize(stream);
var result = (List<T>)serializer.Deserialize(stream);
Log($"List of type {typeof(T)} successfully deserialized from {path}");
return result;
}
catch (Exception ex) when (ex is InvalidOperationException or XmlException or NullReferenceException
or UnauthorizedAccessException or ArgumentException or IOException)
{
throw new Exception($"{SerialResources.ErrorSerializerXml} {ex.Message}", ex);
throw new Serialize.DeserializationException($"{SerialResources.ErrorSerializerXml} {ex.Message}", ex);
}
}

Expand All @@ -82,44 +125,19 @@ public static Dictionary<TKey, TValue> LoadDictionaryFromXml<TKey, TValue>(strin

try
{
using var reader = new StreamReader(path);
using var reader = new StreamReader(path, Encoding.UTF8);
var list = (List<Item>)new XmlSerializer(typeof(List<Item>)).Deserialize(reader);

return list.ToDictionary(
var result = list.ToDictionary(
item => Deserialize<TKey>(item.Key),
item => Deserialize<TValue>(item.Value));
Log($"Dictionary with key type {typeof(TKey)} and value type {typeof(TValue)} successfully deserialized from {path}");
return result;
}
catch (Exception ex) when (ex is InvalidOperationException or XmlException or NullReferenceException
or UnauthorizedAccessException or ArgumentException or IOException)
{
throw new Exception($"{SerialResources.ErrorSerializerXml} {ex.Message}", ex);
}
}

/// <summary>
/// Basic check if File is empty
/// </summary>
/// <param name="path">Name of the File</param>
/// <returns>Status if File has actual content and some Debug Messages for easier Debugging</returns>
private static bool FileContent(string path)
{
return new FileInfo(path).Length != 0;
}

/// <summary>
/// Validates the file path.
/// </summary>
/// <param name="path">The path to validate.</param>
private static void ValidateFilePath(string path)
{
if (!FileHandleSearch.FileExists(path))
{
throw new ArgumentException($"{SerialResources.ErrorPath} {path}");
}

if (!FileContent(path))
{
throw new ArgumentException($"{SerialResources.ErrorFileEmpty} {path}");
throw new Serialize.DeserializationException($"{SerialResources.ErrorSerializerXml} {ex.Message}", ex);
}
}

Expand Down
92 changes: 92 additions & 0 deletions Serializer/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: Serializer
* FILE: Serializer/Exceptions.cs
* PURPOSE: Serialize, Deserialize Exceptions
* PROGRAMER: Peter Geinitz (Wayfarer)
*/

// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBeInternal

using System;

namespace Serializer
{
/// <summary>
/// Holds all Exceptions
/// </summary>
public static partial class Serialize
{
/// <inheritdoc />
/// <summary>
/// Serialization Exception
/// </summary>
/// <seealso cref="T:System.Exception" />
public sealed partial class SerializationException
{
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:Serializer.Serialize.SerializationException" /> class.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (<see langword="Nothing" /> in Visual Basic) if no inner exception is specified.</param>
internal SerializationException(string message, Exception innerException)
: base(message, innerException)
{
}

/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:Serializer.Serialize.SerializationException" /> class.
/// </summary>
public SerializationException()
{
}

/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:Serializer.Serialize.SerializationException" /> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public SerializationException(string message) : base(message)
{
}
}

/// <inheritdoc />
/// <summary>
/// Custom exception for deserialization errors.
/// </summary>
public sealed class DeserializationException : Exception
{
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:Serializer.Serialize.DeserializationException" /> class.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (<see langword="Nothing" /> in Visual Basic) if no inner exception is specified.</param>
internal DeserializationException(string message, Exception innerException)
: base(message, innerException)
{
}

/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:Serializer.Serialize.DeserializationException" /> class.
/// </summary>
public DeserializationException()
{
}

/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:Serializer.Serialize.DeserializationException" /> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public DeserializationException(string message) : base(message)
{
}
}
}
}
Loading

0 comments on commit b2fa02c

Please sign in to comment.