Browse Source

Add read-only property skipping in serializer

pull/165/head
Ionite 1 year ago
parent
commit
f5637cd1f3
No known key found for this signature in database
  1. 8
      StabilityMatrix.Avalonia/ViewModels/LoadableViewModelBase.cs
  2. 28
      StabilityMatrix.Tests/Avalonia/LoadableViewModelBaseTests.cs

8
StabilityMatrix.Avalonia/ViewModels/LoadableViewModelBase.cs

@ -30,6 +30,12 @@ public abstract class LoadableViewModelBase : ViewModelBase, IJsonLoadableState
private static bool ShouldIgnoreProperty(PropertyInfo property)
{
// Check not read-only
if (property.SetMethod is null)
{
Logger.Trace("Skipping {Property} - read-only", property.Name);
return true;
}
// Check not JsonIgnore
if (property.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Length > 0)
{
@ -58,6 +64,7 @@ public abstract class LoadableViewModelBase : ViewModelBase, IJsonLoadableState
/// For the following properties on this class, we will try to set from the JSON object:
/// <list type="bullet">
/// <item>Public</item>
/// <item>Not read-only</item>
/// <item>Not marked with [JsonIgnore]</item>
/// <item>Not a type within the SerializerIgnoredTypes</item>
/// <item>Not a name within the SerializerIgnoredNames</item>
@ -128,6 +135,7 @@ public abstract class LoadableViewModelBase : ViewModelBase, IJsonLoadableState
/// save all properties that are:
/// <list type="bullet">
/// <item>Public</item>
/// <item>Not read-only</item>
/// <item>Not marked with [JsonIgnore]</item>
/// <item>Not a type within the SerializerIgnoredTypes</item>
/// <item>Not a name within the SerializerIgnoredNames</item>

28
StabilityMatrix.Tests/Avalonia/LoadableViewModelBaseTests.cs

@ -21,6 +21,16 @@ public class TestLoadableViewModel : LoadableViewModelBase
public int Ignored { get; set; }
}
public class TestLoadableViewModelReadOnly : LoadableViewModelBase
{
public int ReadOnly { get; }
public TestLoadableViewModelReadOnly(int readOnly)
{
ReadOnly = readOnly;
}
}
public partial class TestLoadableViewModelObservable : LoadableViewModelBase
{
[ObservableProperty]
@ -200,4 +210,22 @@ public class LoadableViewModelBaseTests
Assert.AreEqual(123, loadedNested.Id);
Assert.AreEqual(0, loadedNested.Ignored);
}
[TestMethod]
public void TestLoadStateFromJsonObject_ReadOnly()
{
var vm = new TestLoadableViewModelReadOnly(456);
var state = vm.SaveStateToJsonObject();
// Check no properties were serialized
Assert.AreEqual(0, state.Count);
// Create a new instance and load the state
var vm2 = new TestLoadableViewModelReadOnly(123);
vm2.LoadStateFromJsonObject(state);
// Read only property should have been ignored
Assert.AreEqual(123, vm2.ReadOnly);
}
}

Loading…
Cancel
Save