Serialize converters were added

This commit is contained in:
Evgeny Redikultsev
2024-09-08 17:47:46 +05:00
parent 408e9f6999
commit 6e0b7b8070
60 changed files with 1713 additions and 443 deletions

View File

@@ -0,0 +1,27 @@
using Newtonsoft.Json;
using StructureHelperCommon.Models.Projects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.DTOs
{
[JsonObject(IsReference = true)]
public class FileVersionDTO : IFileVersion
{
[JsonProperty("Id")]
public Guid Id { get; set; }
[JsonProperty("VersionNumber")]
public int VersionNumber { get; set; }
[JsonProperty("SubVersionNumber")]
public int SubVersionNumber { get; set; }
public FileVersionDTO(Guid id)
{
Id = id;
}
}
}

View File

@@ -0,0 +1,41 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models;
using StructureHelperCommon.Models.Projects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.DTOs
{
public class FileVersionDTOConvertStrategy : IConvertStrategy<FileVersion, FileVersionDTO>
{
private IUpdateStrategy<IFileVersion> updateStrategy;
public IShiftTraceLogger TraceLogger { get; set; }
public FileVersionDTOConvertStrategy(IUpdateStrategy<IFileVersion> updateStrategy)
{
this.updateStrategy = updateStrategy;
}
public FileVersionDTOConvertStrategy() : this(new FileVersionUpdateStrategy())
{
}
public FileVersionDTO ConvertTo(FileVersion source)
{
FileVersionDTO fileVersion = new(source.Id);
updateStrategy.Update(fileVersion, source);
return fileVersion;
}
public FileVersion ConvertFrom(FileVersionDTO source)
{
FileVersion fileVersion = new(source.Id);
updateStrategy.Update(fileVersion, source);
return fileVersion;
}
}
}

View File

@@ -0,0 +1,35 @@
using Newtonsoft.Json;
using StructureHelperCommon.Models.Analyses;
using StructureHelperCommon.Models.Projects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.DTOs
{
public class ProjectDTO : IProject
{
[JsonProperty("Id")]
public Guid Id { get; set; }
[JsonIgnore]
public string FullFileName { get; set; }
[JsonIgnore]
public bool IsNewFile { get; set; }
[JsonIgnore]
public bool IsActual { get; set; }
[JsonProperty("VisualAnalyses")]
public List<IVisualAnalysis> VisualAnalyses { get; private set; }
[JsonIgnore]
public string FileName { get; set; }
public ProjectDTO(Guid id)
{
Id = id;
}
}
}

View File

@@ -15,4 +15,8 @@
<ProjectReference Include="..\StructureHelperLogics\StructureHelperLogics.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="NewFolder\" />
</ItemGroup>
</Project>

View File

@@ -1,124 +1,113 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using StructureHelperCommon.Models;
namespace DataAccess
{
using Newtonsoft.Json;
using StructureHelperCommon.Models;
using System;
using System.Collections.Generic;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;
class Program
{
static void Main(string[] args)
{
var logger = new TraceLogger();
// class Program
// {
// static void Main(string[] args)
// {
// var logger = new TraceLogger();
// Create objects with complex relationships
var parent1 = new Parent { Name = "Parent_1" };
var parent2 = new Parent { Name = "Parent_2" };
// // Create objects with complex relationships
// var parent1 = new Parent { Name = "Parent_1" };
// var parent2 = new Parent { Name = "Parent_2" };
var detail1 = new Detail { Description = "Detail_1", InternalNote = "Secret Note 1" };
var detail2 = new Detail { Description = "Detail_2", InternalNote = "Secret Note 2" };
var detail3 = new Detail { Description = "Detail_3", InternalNote = "Secret Note 3" };
// var detail1 = new Detail { Description = "Detail_1", InternalNote = "Secret Note 1" };
// var detail2 = new Detail { Description = "Detail_2", InternalNote = "Secret Note 2" };
// var detail3 = new Detail { Description = "Detail_3", InternalNote = "Secret Note 3" };
var subDetail1 = new SubDetail { Info = "SubDetail_1" };
// var subDetail1 = new SubDetail { Info = "SubDetail_1" };
// Set up relationships
parent1.Details.Add(detail1);
parent1.Details.Add(detail2);
// // Set up relationships
// parent1.Details.Add(detail1);
// parent1.Details.Add(detail2);
parent2.Details.Add(detail2); // Shared detail
parent2.Details.Add(detail3);
// parent2.Details.Add(detail2); // Shared detail
// parent2.Details.Add(detail3);
detail3.SubDetails.Add(subDetail1);
// detail3.SubDetails.Add(subDetail1);
// Serialize with custom converters and trace logging
string json = Serialize(new List<Parent> { parent1, parent2 }, logger);
Console.WriteLine("Serialized JSON:");
Console.WriteLine(json);
// // Serialize with custom converters and trace logging
// string json = Serialize(new List<Parent> { parent1, parent2 }, logger);
// Console.WriteLine("Serialized JSON:");
// Console.WriteLine(json);
// Deserialize with custom converters and trace logging
var deserializedParents = Deserialize<List<Parent>>(json, logger);
// // Deserialize with custom converters and trace logging
// var deserializedParents = Deserialize<List<Parent>>(json, logger);
Console.WriteLine("\nDeserialized Objects:");
foreach (var parent in deserializedParents)
{
Console.WriteLine($"Parent: {parent.Name}, Id: {parent.Id}");
foreach (var detail in parent.Details)
{
Console.WriteLine($" Detail: {detail.Description}, Id: {detail.Id}");
}
}
}
// Console.WriteLine("\nDeserialized Objects:");
// foreach (var parent in deserializedParents)
// {
// Console.WriteLine($"Parent: {parent.Name}, Id: {parent.Id}");
// foreach (var detail in parent.Details)
// {
// Console.WriteLine($" Detail: {detail.Description}, Id: {detail.Id}");
// }
// }
// }
static string Serialize(object obj, TraceLogger logger)
{
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new ParentConverter(logger), // Add the specific converter
// Add other converters if needed
},
Formatting = Formatting.Indented
};
// static string Serialize(object obj, TraceLogger logger)
// {
// var settings = new JsonSerializerSettings
// {
// Converters = new List<JsonConverter>
// {
// new ParentConverter(logger), // Add the specific converter
// // Add other converters if needed
// },
// Formatting = Formatting.Indented
// };
return JsonConvert.SerializeObject(obj, settings);
}
// return JsonConvert.SerializeObject(obj, settings);
// }
static T Deserialize<T>(string json, TraceLogger logger)
{
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new ParentConverter(logger), // Add the specific converter
// Add other converters if needed
}
};
// static T Deserialize<T>(string json, TraceLogger logger)
// {
// var settings = new JsonSerializerSettings
// {
// Converters = new List<JsonConverter>
// {
// new ParentConverter(logger), // Add the specific converter
// // Add other converters if needed
// }
// };
return JsonConvert.DeserializeObject<T>(json, settings);
}
}
// return JsonConvert.DeserializeObject<T>(json, settings);
// }
// }
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class Parent
{
public Guid Id { get; set; } = Guid.NewGuid();
[JsonProperty("parent_name")]
public string Name { get; set; }
//public class Parent
// {
// public Guid Id { get; set; } = Guid.NewGuid();
public List<Detail> Details { get; set; } = new List<Detail>();
}
// [JsonProperty("parent_name")]
// public string Name { get; set; }
public class Detail
{
public Guid Id { get; set; } = Guid.NewGuid();
// public List<Detail> Details { get; set; } = new List<Detail>();
// }
[JsonPropertyName("detail_description")] // Compatible with System.Text.Json
public string Description { get; set; }
// public class Detail
// {
// public Guid Id { get; set; } = Guid.NewGuid();
[JsonIgnore] // This property will be ignored during serialization
public string InternalNote { get; set; }
// [JsonPropertyName("detail_description")] // Compatible with System.Text.Json
// public string Description { get; set; }
public List<SubDetail> SubDetails { get; set; } = new List<SubDetail>();
}
// [JsonIgnore] // This property will be ignored during serialization
// public string InternalNote { get; set; }
public class SubDetail
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Info { get; set; }
}
// public List<SubDetail> SubDetails { get; set; } = new List<SubDetail>();
// }
// public class SubDetail
// {
// public Guid Id { get; set; } = Guid.NewGuid();
// public string Info { get; set; }
// }
}

View File

@@ -1,49 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataAccess.FileDialogs
{
public class FileDialogOpener
{
public void OpenFileAndRead()
{
// Create an instance of OpenFileDialog
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
// Set filter options and filter index
openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false; // Set to true if you want to allow multiple file selection
openFileDialog.Title = "Select a File";
// Show the dialog and get result
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the path of the selected file
string selectedFilePath = openFileDialog.FileName;
// Read the content of the file
try
{
string fileContent = File.ReadAllText(selectedFilePath);
Console.WriteLine($"File Content of '{selectedFilePath}':");
Console.WriteLine(fileContent);
}
catch (IOException ex)
{
Console.WriteLine($"An error occurred while reading the file: {ex.Message}");
}
}
else
{
Console.WriteLine("File selection was cancelled.");
}
}
}
}
}

View File

@@ -10,10 +10,6 @@ namespace DataAccess.FileDialogs
{
internal class FileStorage
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
public class FileStorageManager
{
@@ -109,30 +105,30 @@ class Program
[STAThread] // Required for OpenFileDialog
static void Main()
{
var fileStorageManager = new FileStorageManager();
//var fileStorageManager = new FileStorageManager();
// Open files and add them to the storage
fileStorageManager.OpenFile();
//// Open files and add them to the storage
//fileStorageManager.OpenFile();
// List all opened files
Console.WriteLine("\nOpened Files:");
fileStorageManager.ListOpenedFiles();
//// List all opened files
//Console.WriteLine("\nOpened Files:");
//fileStorageManager.ListOpenedFiles();
// Example: Read content of the first opened file (if any)
var openedFiles = new List<Guid>(fileStorageManager._openedFiles.Keys);
if (openedFiles.Count > 0)
{
var firstFileId = openedFiles[0];
Console.WriteLine($"\nReading content of the first opened file (ID: {firstFileId}):");
string content = fileStorageManager.ReadFileContent(firstFileId);
Console.WriteLine(content);
}
//// Example: Read content of the first opened file (if any)
//var openedFiles = new List<Guid>(fileStorageManager._openedFiles.Keys);
//if (openedFiles.Count > 0)
//{
// var firstFileId = openedFiles[0];
// Console.WriteLine($"\nReading content of the first opened file (ID: {firstFileId}):");
// string content = fileStorageManager.ReadFileContent(firstFileId);
// Console.WriteLine(content);
//}
// Close all files
foreach (var fileId in openedFiles)
{
fileStorageManager.CloseFile(fileId);
}
//// Close all files
//foreach (var fileId in openedFiles)
//{
// fileStorageManager.CloseFile(fileId);
//}
}
}

View File

@@ -0,0 +1,90 @@
using DataAccess.DTOs;
using DataAccess.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using StructureHelperCommon.Infrastructures.Settings;
using StructureHelperCommon.Models;
using StructureHelperCommon.Models.Projects;
using StructureHelperCommon.Services.FileServices;
namespace DataAccess.Infrastructures
{
public class FileOpenLogic : IFileOpenLogic
{
private string fileName;
public IShiftTraceLogger? TraceLogger { get; set; }
private bool GetFilePath()
{
var inputData = new OpenFileInputData()
{
FilterString = "StructureHelper project file (*.shpj)|*.shpj|All Files (*.*)|*.*",
TraceLogger = TraceLogger
};
var fileDialog = new FileOpener(inputData);
var fileDialogResult = fileDialog.OpenFile();
if (fileDialogResult.IsValid != true)
{
return false;
}
fileName = fileDialogResult.FilePath;
return true;
}
public OpenProjectResult OpenFile()
{
var result = new OpenProjectResult()
{
IsValid = true
};
if (GetFilePath() == false)
{
result.IsValid = false;
return result;
}
if (! File.Exists(fileName))
{
result.IsValid = false;
TraceLogger?.AddMessage($"File {fileName} does not exists", TraceLogStatuses.Error);
return result;
}
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new FileVersionDTOJsonConverter(TraceLogger), // Add the specific converter
// Add other converters if needed
},
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.All,
MissingMemberHandling = MissingMemberHandling.Ignore,
TypeNameHandling = TypeNameHandling.All,
NullValueHandling = NullValueHandling.Include
};
using (StreamReader file = File.OpenText(fileName))
{
JsonSerializer serializer = new JsonSerializer();
var fileVersion = (FileVersionDTO)serializer.Deserialize(file, typeof(FileVersionDTO));
var checkLogic = new CheckFileVersionLogic()
{
FileVersion = fileVersion,
TraceLogger = TraceLogger
};
var checkResult = checkLogic.Check();
if (checkResult == false)
{
result.IsValid = false;
result.Description += checkLogic.CheckResult;
}
else
{
var currentVersion = ProgramSetting.GetCurrentFileVersion();
TraceLogger.AddMessage($"File version is {fileVersion.VersionNumber}.{fileVersion.SubVersionNumber}, current version is {currentVersion.VersionNumber}.{currentVersion.SubVersionNumber}");
}
}
return result;
}
}
}

View File

@@ -0,0 +1,114 @@
using DataAccess.DTOs;
using DataAccess.JsonConverters;
using Newtonsoft.Json;
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Infrastructures.Settings;
using StructureHelperCommon.Models;
using StructureHelperCommon.Models.Projects;
using StructureHelperCommon.Services.FileServices;
namespace DataAccess.Infrastructures
{
public class FileSaveLogic : IFileSaveLogic
{
private IFileVersion version;
private Dictionary<(Guid id, Type type), ISaveable> refDictinary;
public IShiftTraceLogger? TraceLogger { get; set; }
public void SaveFile(IProject project)
{
if (project.IsNewFile == true)
{
var result = SelectFileName(project);
if (result.IsValid == false)
{
TraceLogger?.AddMessage(result.Description);
return;
}
project.FullFileName = result.FileName;
project.IsNewFile = false;
}
SaveToFile(project);
}
private SaveFileResult SelectFileName(IProject project)
{
FileDialogSaver saver = new();
saver.InputData = new SaveDialogInputData()
{
FilterString = "StructureHelper project file (*.shpj)|*.shpj|All Files (*.*)|*.*",
InitialDirectory = project.FullFileName,
};
saver.TraceLogger = TraceLogger;
var saveResult = saver.SaveFile();
return saveResult;
}
private void SaveToFile(IProject project)
{
version = ProgramSetting.GetCurrentFileVersion();
refDictinary = new Dictionary<(Guid id, Type type), ISaveable>();
FileVersionDTO versionDTO = GetVersionDTO();
var versionString = Serialize(versionDTO, TraceLogger);
try
{
File.WriteAllText(project.FullFileName, versionString);
TraceLogger?.AddMessage($"File {project.FullFileName} was saved successfully", TraceLogStatuses.Service);
}
catch (Exception ex)
{
TraceLogger?.AddMessage(ex.Message, TraceLogStatuses.Error);
}
}
private FileVersionDTO GetVersionDTO()
{
FileVersionDTOConvertStrategy fileVersionDTOConvertStrategy = new()
{
TraceLogger = TraceLogger
};
DictionaryConvertStrategy<FileVersion, FileVersionDTO> dictionaryConvertStrategy = new()
{
ConvertStrategy = fileVersionDTOConvertStrategy,
ReferenceDictionary = refDictinary,
TraceLogger = TraceLogger
};
var versionDTO = dictionaryConvertStrategy.ConvertTo(version as FileVersion);
return versionDTO;
}
private static string Serialize(object obj, IShiftTraceLogger logger)
{
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new FileVersionDTOJsonConverter(logger), // Add the specific converter
// Add other converters if needed
},
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.All,
MissingMemberHandling = MissingMemberHandling.Ignore,
TypeNameHandling = TypeNameHandling.All,
NullValueHandling = NullValueHandling.Include
};
return JsonConvert.SerializeObject(obj, settings);
}
public void SaveFileAs(IProject project)
{
var tmpIsNew = project.IsNewFile;
var tmpFullFileName = project.FullFileName;
project.IsNewFile = true;
SaveFile(project);
if (project.IsNewFile == true)
{
project.IsNewFile = tmpIsNew;
project.FullFileName = tmpFullFileName;
}
}
}
}

View File

@@ -0,0 +1,10 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models.Projects;
namespace DataAccess.Infrastructures
{
public interface IFileOpenLogic : ILogic
{
OpenProjectResult OpenFile();
}
}

View File

@@ -0,0 +1,16 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models.Projects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Infrastructures
{
public interface IFileSaveLogic : ILogic
{
void SaveFile(IProject project);
void SaveFileAs(IProject project);
}
}

View File

@@ -0,0 +1,18 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models.Projects;
using StructureHelperCommon.Services.FileServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Infrastructures
{
public interface IProjectAccessLogic : ILogic
{
OpenProjectResult OpenProject();
void SaveProject(IProject project);
void SaveProjectAs(IProject project);
}
}

View File

@@ -0,0 +1,17 @@
using StructureHelperCommon.Models.Calculators;
using StructureHelperCommon.Models.Projects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Infrastructures
{
public class OpenProjectResult : IResult
{
public bool IsValid { get; set; } = true;
public string? Description { get; set; } = string.Empty;
public IProject Project { get; set; }
}
}

View File

@@ -0,0 +1,47 @@
using StructureHelperCommon.Models;
using StructureHelperCommon.Models.Projects;
using StructureHelperCommon.Services.FileServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Infrastructures
{
public class ProjectAccessLogic : IProjectAccessLogic
{
private IFileOpenLogic openLogic;
private IFileSaveLogic saveLogic;
public IShiftTraceLogger? TraceLogger { get; set; }
public ProjectAccessLogic(IFileOpenLogic openLogic, IFileSaveLogic saveLogic)
{
this.openLogic = openLogic;
this.saveLogic = saveLogic;
}
public ProjectAccessLogic() : this(new FileOpenLogic(), new FileSaveLogic())
{
}
public OpenProjectResult OpenProject()
{
openLogic.TraceLogger = TraceLogger;
return openLogic.OpenFile();
}
public void SaveProject(IProject project)
{
saveLogic.TraceLogger = TraceLogger;
saveLogic.SaveFile(project);
}
public void SaveProjectAs(IProject project)
{
saveLogic.TraceLogger = TraceLogger;
saveLogic.SaveFileAs(project);
}
}
}

View File

@@ -1,95 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StructureHelperCommon.Models;
using System;
using System.Reflection;
namespace DataAccess.JsonConverters
{
public abstract class BaseConverter<T> : JsonConverter<T>
{
private IShiftTraceLogger traceLogger;
protected BaseConverter(IShiftTraceLogger logger)
{
traceLogger = logger;
}
public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
{
traceLogger.AddMessage($"Serializing {typeof(T).Name} (ID: {GetId(value)})");
// Use JsonSerializer's default behavior to handle attributes like [JsonIgnore] and [JsonProperty]
var jo = new JObject();
foreach (var prop in typeof(T).GetProperties())
{
if (!ShouldIgnoreProperty(prop))
{
string propertyName = GetPropertyName(prop);
var propValue = prop.GetValue(value);
jo.Add(propertyName, JToken.FromObject(propValue, serializer));
}
}
jo.WriteTo(writer);
}
// Helper method to check if a property should be ignored
private bool ShouldIgnoreProperty(PropertyInfo prop)
{
// Check for [JsonIgnore] attribute
var jsonIgnoreAttribute = prop.GetCustomAttribute<JsonIgnoreAttribute>();
return jsonIgnoreAttribute != null;
}
// Helper method to get the property name, considering [JsonProperty] and [JsonPropertyName] attributes
private string GetPropertyName(PropertyInfo prop)
{
// Check for [JsonProperty] attribute (for Newtonsoft.Json)
var jsonPropertyAttribute = prop.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonPropertyAttribute != null)
{
return jsonPropertyAttribute.PropertyName;
}
// Check for [JsonPropertyName] attribute (for System.Text.Json compatibility)
var jsonPropertyNameAttribute = prop.GetCustomAttribute<System.Text.Json.Serialization.JsonPropertyNameAttribute>();
if (jsonPropertyNameAttribute != null)
{
return jsonPropertyNameAttribute.Name;
}
// Default to the property name if no attributes are found
return prop.Name;
}
public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
{
traceLogger.AddMessage($"Deserializing {typeof(T).Name}");
// Use JsonSerializer's default behavior to handle attributes during deserialization
JObject jo = JObject.Load(reader);
T obj = Activator.CreateInstance<T>();
foreach (var prop in typeof(T).GetProperties())
{
if (!ShouldIgnoreProperty(prop) && jo.TryGetValue(GetPropertyName(prop), out JToken value))
{
var propValue = value.ToObject(prop.PropertyType, serializer);
prop.SetValue(obj, propValue);
}
}
traceLogger.AddMessage($"Deserialized {typeof(T).Name} (ID: {GetId(obj)})");
return obj;
}
// Method to get the ID for logging purposes, assumes all classes have an 'Id' property of type Guid.
private Guid GetId(object obj)
{
var idProp = obj.GetType().GetProperty("Id");
return idProp != null ? (Guid)idProp.GetValue(obj) : Guid.Empty;
}
}
}

View File

@@ -0,0 +1,48 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StructureHelperCommon.Models;
using System;
using System.Reflection;
namespace DataAccess.JsonConverters
{
public abstract class BaseJsonConverter<T> : JsonConverter<T>
{
private IWriteJsonLogic<T> writeJsonLogic;
private IReadJsonLogic<T> readJsonLogic;
public IShiftTraceLogger TraceLogger { get; set; }
protected BaseJsonConverter(IShiftTraceLogger logger, IWriteJsonLogic<T> writeJsonLogic, IReadJsonLogic<T> readJsonLogic)
{
this.writeJsonLogic = writeJsonLogic;
this.readJsonLogic = readJsonLogic;
TraceLogger = logger;
}
protected BaseJsonConverter(IShiftTraceLogger logger)
: this (logger,
new WriteJsonLogic<T>() { TraceLogger = logger},
new ReadJsonLogic<T>() { TraceLogger = logger})
{
}
public override void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer)
{
writeJsonLogic.TraceLogger = TraceLogger;
writeJsonLogic.WriteJson(writer, value, serializer);
}
public override T ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
readJsonLogic.TraceLogger = TraceLogger;
return readJsonLogic.ReadJson(reader, objectType, existingValue, hasExistingValue, serializer);
}
}
}

View File

@@ -8,7 +8,7 @@ using System.Threading.Tasks;
namespace DataAccess.JsonConverters
{
public class CrossSectionJsonConverter : BaseConverter<CrossSectionDTO>
public class CrossSectionJsonConverter : BaseJsonConverter<CrossSectionDTO>
{
public CrossSectionJsonConverter(IShiftTraceLogger logger) : base(logger)
{

View File

@@ -0,0 +1,17 @@
using DataAccess.DTOs;
using StructureHelperCommon.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.JsonConverters
{
public class FileVersionDTOJsonConverter : BaseJsonConverter<FileVersionDTO>
{
public FileVersionDTOJsonConverter(IShiftTraceLogger logger) : base(logger)
{
}
}
}

View File

@@ -0,0 +1,22 @@
using StructureHelperCommon.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.JsonConverters
{
/// <inheritdoc/>
public class GetIdFromObjectLogic : IGetIdFromObjectLogic
{
/// <inheritdoc/>
public IShiftTraceLogger? TraceLogger { get; set; }
/// <inheritdoc/>
public Guid GetId(object obj)
{
var idProp = obj.GetType().GetProperty("Id");
return idProp != null ? (Guid)idProp.GetValue(obj) : Guid.Empty;
}
}
}

View File

@@ -0,0 +1,38 @@
using Newtonsoft.Json;
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.JsonConverters
{
public class GetPropertyNameLogic : IGetPropertyNameLogic
{
public IShiftTraceLogger? TraceLogger { get; set; }
// Helper method to get the property name, considering [JsonProperty] and [JsonPropertyName] attributes
public string GetPropertyName(PropertyInfo prop)
{
// Check for [JsonProperty] attribute (for Newtonsoft.Json)
var jsonPropertyAttribute = prop.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonPropertyAttribute != null)
{
return jsonPropertyAttribute.PropertyName;
}
// Check for [JsonPropertyName] attribute (for System.Text.Json compatibility)
var jsonPropertyNameAttribute = prop.GetCustomAttribute<System.Text.Json.Serialization.JsonPropertyNameAttribute>();
if (jsonPropertyNameAttribute != null)
{
return jsonPropertyNameAttribute.Name;
}
// Default to the property name if no attributes are found
return prop.Name;
}
}
}

View File

@@ -0,0 +1,12 @@
using StructureHelperCommon.Infrastructures.Interfaces;
namespace DataAccess.JsonConverters
{
/// <summary>
/// Logic to get the ID for logging purposes, assumes all classes have an 'Id' property of type Guid.
/// </summary>
public interface IGetIdFromObjectLogic : ILogic
{
Guid GetId(object obj);
}
}

View File

@@ -0,0 +1,13 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using System.Reflection;
namespace DataAccess.JsonConverters
{
/// <summary>
/// Helper logic to get the property name, considering [JsonProperty] and [JsonPropertyName] attributes
/// </summary>
public interface IGetPropertyNameLogic : ILogic
{
string GetPropertyName(PropertyInfo prop);
}
}

View File

@@ -0,0 +1,23 @@
using Newtonsoft.Json;
using StructureHelperCommon.Infrastructures.Interfaces;
namespace DataAccess.JsonConverters
{
/// <summary>
/// Helper logic for JSON converter
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IReadJsonLogic<T> : ILogic
{
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="objectType"></param>
/// <param name="existingValue"></param>
/// <param name="hasExistingValue"></param>
/// <param name="serializer"></param>
/// <returns></returns>
T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer);
}
}

View File

@@ -0,0 +1,13 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using System.Reflection;
namespace DataAccess.JsonConverters
{
/// <summary>
/// Helper logic to check if a property should be ignored
/// </summary>
public interface IShouldIgnorePropertyLogic : ILogic
{
bool ShouldIgnoreProperty(PropertyInfo prop);
}
}

View File

@@ -0,0 +1,10 @@
using Newtonsoft.Json;
using StructureHelperCommon.Infrastructures.Interfaces;
namespace DataAccess.JsonConverters
{
public interface IWriteJsonLogic<T> : ILogic
{
void WriteJson(JsonWriter writer, T value, JsonSerializer serializer);
}
}

View File

@@ -0,0 +1,56 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using StructureHelperCommon.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.JsonConverters
{
public class ReadJsonLogic<T> : IReadJsonLogic<T>
{
private IShouldIgnorePropertyLogic shouldIgnorePropertyLogic;
private IGetPropertyNameLogic getPropertyNameLogic;
private IGetIdFromObjectLogic getIdFromObjectLogic;
public IShiftTraceLogger? TraceLogger { get; set; }
public ReadJsonLogic(IShouldIgnorePropertyLogic shouldIgnorePropertyLogic,
IGetPropertyNameLogic getPropertyNameLogic,
IGetIdFromObjectLogic getIdFromObjectLogic)
{
this.shouldIgnorePropertyLogic = shouldIgnorePropertyLogic;
this.getPropertyNameLogic = getPropertyNameLogic;
this.getIdFromObjectLogic = getIdFromObjectLogic;
}
public ReadJsonLogic()
: this(new ShouldIgnorePropertyLogic(),
new GetPropertyNameLogic(),
new GetIdFromObjectLogic())
{
}
public T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
{
TraceLogger?.AddMessage($"Deserializing {typeof(T).Name}");
shouldIgnorePropertyLogic.TraceLogger = getPropertyNameLogic.TraceLogger = getIdFromObjectLogic.TraceLogger = TraceLogger;
// Use JsonSerializer's default behavior to handle attributes during deserialization
JObject jo = JObject.Load(reader);
T obj = Activator.CreateInstance<T>();
foreach (var prop in typeof(T).GetProperties())
{
if (! shouldIgnorePropertyLogic.ShouldIgnoreProperty(prop) && jo.TryGetValue(getPropertyNameLogic.GetPropertyName(prop), out JToken value))
{
var propValue = value.ToObject(prop.PropertyType, serializer);
prop.SetValue(obj, propValue);
}
}
TraceLogger?.AddMessage($"Deserialized {typeof(T).Name} (ID: {getIdFromObjectLogic.GetId(obj)})");
return obj;
}
}
}

View File

@@ -0,0 +1,22 @@
using Newtonsoft.Json;
using StructureHelperCommon.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.JsonConverters
{
public class ShouldIgnorePropertyLogic : IShouldIgnorePropertyLogic
{
public IShiftTraceLogger? TraceLogger { get; set; }
public bool ShouldIgnoreProperty(PropertyInfo prop)
{
// Check for [JsonIgnore] attribute
var jsonIgnoreAttribute = prop.GetCustomAttribute<JsonIgnoreAttribute>();
return jsonIgnoreAttribute != null;
}
}
}

View File

@@ -0,0 +1,54 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.JsonConverters
{
public class WriteJsonLogic<T> : IWriteJsonLogic<T>
{
private IShouldIgnorePropertyLogic shouldIgnorePropertyLogic;
private IGetPropertyNameLogic getPropertyNameLogic;
private IGetIdFromObjectLogic getIdFromObjectLogic;
public IShiftTraceLogger? TraceLogger { get; set; }
public WriteJsonLogic(IShouldIgnorePropertyLogic shouldIgnorePropertyLogic,
IGetPropertyNameLogic getPropertyNameLogic,
IGetIdFromObjectLogic getIdFromObjectLogic)
{
this.shouldIgnorePropertyLogic = shouldIgnorePropertyLogic;
this.getPropertyNameLogic = getPropertyNameLogic;
this.getIdFromObjectLogic = getIdFromObjectLogic;
}
public WriteJsonLogic()
: this(new ShouldIgnorePropertyLogic(),
new GetPropertyNameLogic(),
new GetIdFromObjectLogic())
{
}
public void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
{
TraceLogger?.AddMessage($"Serializing {typeof(T).Name} (ID: {getIdFromObjectLogic.GetId(value)})");
shouldIgnorePropertyLogic.TraceLogger = getPropertyNameLogic.TraceLogger = getIdFromObjectLogic.TraceLogger = TraceLogger;
// Use JsonSerializer's default behavior to handle attributes like [JsonIgnore] and [JsonProperty]
var jo = new JObject();
foreach (var prop in typeof(T).GetProperties())
{
if (!shouldIgnorePropertyLogic.ShouldIgnoreProperty(prop))
{
string propertyName = getPropertyNameLogic.GetPropertyName(prop);
var propValue = prop.GetValue(value);
jo.Add(propertyName, JToken.FromObject(propValue, serializer));
}
}
jo.WriteTo(writer);
}
}
}