Skip to content

Fix deserialization for same type proxy association #2720

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 147 additions & 0 deletions src/NHibernate.Test/Async/NHSpecificTest/GH2673/Fixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by AsyncGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.GH2673
{
using System.Threading.Tasks;
[TestFixture(true)]
[TestFixture(false)]
public class FixtureAsync : TestCaseMappingByCode
{
private readonly bool _withLazyProperties;

public FixtureAsync(bool withLazyProperties)
{
_withLazyProperties = withLazyProperties;
}

protected override void OnSetUp()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
var role1 = new Role {Id = 1, Name = "role1"};
session.Save(role1);
var role2 = new Role {Id = 2, Name = "role2"};
session.Save(role2);

var r1 = new Resource() {Id = 1, Name = "r1", ResourceRole = role1};
session.Save(r1);

var r2 = new Resource() {Id = 2, Name = "r2", ResourceRole = role2};
session.Save(r2);

var r3 = new Resource() {Id = 3, Name = "r3", ResourceRole = role2};
session.Save(r3);

r1.Manager = r2;
r2.Manager = r3;
r3.Manager = r1;
transaction.Commit();
}
}

protected override void OnTearDown()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
session.CreateQuery("delete from System.Object").ExecuteUpdate();

transaction.Commit();
}
}

[Test]
public async Task DeserializeSameTypeAssociationWithInitializedProxyAndCircularReferencesAsync()
{
using (var session = OpenSession())
{
var r1 = await (session.LoadAsync<Resource>(1));
var r2 = await (session.LoadAsync<Resource>(2));
var r3 = await (session.LoadAsync<Resource>(3));

var list = await (session.QueryOver<Resource>()
.Fetch(SelectMode.Fetch, res => res.Manager)
.ListAsync());

try
{
var serialised = SpoofSerialization(list[0]);
SpoofSerialization(session);
}
catch (SerializationException)
{
//Lazy properties case throws due to circular references. See GH-2563
if (!_withLazyProperties)
throw;
}
}
}

[Test]
public async Task DeserializeSameTypeAssociationWithInitializedAndNotInitializedProxyAsync()
{
using (var session = OpenSession())
{
var r1 = await (session.GetAsync<Resource>(1));
var r2 = await (session.GetAsync<Resource>(2));
var r1Name = r1.Name;
var serialised = SpoofSerialization(r1);
Assert.That(serialised.Name, Is.EqualTo("r1"));
}
}

private T SpoofSerialization<T>(T obj)
{
var formatter = new BinaryFormatter
{
#if !NETFX
SurrogateSelector = new NHibernate.Util.SerializationHelper.SurrogateSelector()
#endif
};
var stream = new MemoryStream();
formatter.Serialize(stream, obj);

stream.Position = 0;

return (T) formatter.Deserialize(stream);
}

protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Resource>(
m =>
{
m.Table("ResTable");
m.Id(x => x.Id, (i) => i.Generator(Generators.Assigned));
m.Property(x => x.Name, x => x.Lazy(_withLazyProperties));
m.ManyToOne(x => x.Manager, x => x.ForeignKey("none"));
m.ManyToOne(x => x.ResourceRole, x => x.ForeignKey("none"));
});
mapper.Class<Role>(
m =>
{
m.Table("RoleTable");
m.Id(x => x.Id, (i) => i.Generator(Generators.Assigned));
m.Property(x => x.Name);
});
return mapper.CompileMappingForAllExplicitlyAddedEntities();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public async Task EntityAndCustomTypeInConditionalResultAsync()
using (var s = OpenSession())
await ((from x in s.Query<Entity1>()
let parent = x.Parent
//NH-3005 - Contditional on custom type
//NH-3005 - Conditional with custom type
where (parent.IsChiusa ? x.CustomType : parent.CustomType) == x.CustomType
select new
{
Expand Down
20 changes: 20 additions & 0 deletions src/NHibernate.Test/NHSpecificTest/GH2673/Entity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;

namespace NHibernate.Test.NHSpecificTest.GH2673
{
[Serializable]
public class Resource
{
public virtual int Id { get; set; }
public virtual Resource Manager { get; set; }
public virtual string Name { get; set; }
public virtual Role ResourceRole { get; set; }
}

[Serializable]
public class Role
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
}
136 changes: 136 additions & 0 deletions src/NHibernate.Test/NHSpecificTest/GH2673/Fixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.GH2673
{
[TestFixture(true)]
[TestFixture(false)]
public class Fixture : TestCaseMappingByCode
{
private readonly bool _withLazyProperties;

public Fixture(bool withLazyProperties)
{
_withLazyProperties = withLazyProperties;
}

protected override void OnSetUp()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
var role1 = new Role {Id = 1, Name = "role1"};
session.Save(role1);
var role2 = new Role {Id = 2, Name = "role2"};
session.Save(role2);

var r1 = new Resource() {Id = 1, Name = "r1", ResourceRole = role1};
session.Save(r1);

var r2 = new Resource() {Id = 2, Name = "r2", ResourceRole = role2};
session.Save(r2);

var r3 = new Resource() {Id = 3, Name = "r3", ResourceRole = role2};
session.Save(r3);

r1.Manager = r2;
r2.Manager = r3;
r3.Manager = r1;
transaction.Commit();
}
}

protected override void OnTearDown()
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
session.CreateQuery("delete from System.Object").ExecuteUpdate();

transaction.Commit();
}
}

[Test]
public void DeserializeSameTypeAssociationWithInitializedProxyAndCircularReferences()
{
using (var session = OpenSession())
{
var r1 = session.Load<Resource>(1);
var r2 = session.Load<Resource>(2);
var r3 = session.Load<Resource>(3);

var list = session.QueryOver<Resource>()
.Fetch(SelectMode.Fetch, res => res.Manager)
.List();

try
{
var serialised = SpoofSerialization(list[0]);
SpoofSerialization(session);
}
catch (SerializationException)
{
//Lazy properties case throws due to circular references. See GH-2563
if (!_withLazyProperties)
throw;
}
}
}

[Test]
public void DeserializeSameTypeAssociationWithInitializedAndNotInitializedProxy()
{
using (var session = OpenSession())
{
var r1 = session.Get<Resource>(1);
var r2 = session.Get<Resource>(2);
var r1Name = r1.Name;
var serialised = SpoofSerialization(r1);
Assert.That(serialised.Name, Is.EqualTo("r1"));
}
}

private T SpoofSerialization<T>(T obj)
{
var formatter = new BinaryFormatter
{
#if !NETFX
SurrogateSelector = new NHibernate.Util.SerializationHelper.SurrogateSelector()
#endif
};
var stream = new MemoryStream();
formatter.Serialize(stream, obj);

stream.Position = 0;

return (T) formatter.Deserialize(stream);
}

protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Resource>(
m =>
{
m.Table("ResTable");
m.Id(x => x.Id, (i) => i.Generator(Generators.Assigned));
m.Property(x => x.Name, x => x.Lazy(_withLazyProperties));
m.ManyToOne(x => x.Manager, x => x.ForeignKey("none"));
m.ManyToOne(x => x.ResourceRole, x => x.ForeignKey("none"));
});
mapper.Class<Role>(
m =>
{
m.Table("RoleTable");
m.Id(x => x.Id, (i) => i.Generator(Generators.Assigned));
m.Property(x => x.Name);
});
return mapper.CompileMappingForAllExplicitlyAddedEntities();
}
}
}
5 changes: 5 additions & 0 deletions src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,10 @@ public void GetObjectData(SerializationInfo info, StreamingContext context)
info.AddValue(nameof(_componentIdType), _componentIdType);
info.AddValue(nameof(_isClassProxy), _isClassProxy);
}

internal NHibernateProxyFactoryInfo Clone()
{
return new NHibernateProxyFactoryInfo(_entityName, _persistentClass, _interfaces, _getIdentifierMethod, _setIdentifierMethod, _componentIdType, _isClassProxy);
}
}
}
3 changes: 2 additions & 1 deletion src/NHibernate/Proxy/NHibernateProxyObjectReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ public object GetRealObject(StreamingContext context)
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(_proxyFactoryInfo), _proxyFactoryInfo);
//Save a copy as it seems IObjectReference deserialization can't properly handle multiple objects with the same reference
info.AddValue(nameof(_proxyFactoryInfo), _proxyFactoryInfo.Clone());
info.AddValue(nameof(_identifier), _identifier);
info.AddValue(nameof(_implementation), _implementation);
}
Expand Down