NHibernate: single lazy load property - nhibernate

Update: I'm now convinced that the problem lies in the fact that Document is configured as non lazy. The problem is that I don't control the base class and that means I can't change the base props to virtual...
After reading the docs, I'm under the assumption that I should be able to have a non lazy class with a lazy property. Is this possible? Here's the code I'm using for mapping my class:
public class DocumentoMapping : ClassMap<Documento> {
public DocumentoMapping()
{
Setup();
}
private void Setup()
{
Table("Documentos");
Not.LazyLoad();
Id(doc => doc.Id, "IdDocumentos")
.GeneratedBy.Identity()
.Default(0);
Map(doc => doc.NomeDocumento)
.Not.Nullable();
Map(doc => doc.Descricao);
Map(doc => doc.Bytes, "Documento")
.CustomSqlType("image")
.CustomType<Byte[]>()
.LazyLoad()
.Length(2000000000);
Component(doc => doc.Acao,
accao =>
{
accao.Map(a => a.Login);
accao.Map(a => a.Data);
accao.Map(a => a.UserAD)
.CustomSqlType("int")
.CustomType<ADs>();
})
.Not.LazyLoad();
Map(doc => doc.IdPedidoAssistencia)
.Column("IdPats")
.Not.LazyLoad();
}
}
And here's the code for my class:
public class Documento : Entity, IHasAssignedId<int>{
public virtual Byte[] Bytes { get; private set; }
public Documento()
{
NomeDocumento = Descricao = "";
Acao = new Acao("none", DateTime.Now, ADs.Sranet);
}
public Documento(string nomeDocumento, string descricao, Acao acao)
{
Contract.Requires(!String.IsNullOrEmpty(nomeDocumento));
Contract.Requires(!String.IsNullOrEmpty(descricao));
Contract.Requires(acao != null);
Contract.Ensures(!String.IsNullOrEmpty(NomeDocumento));
Contract.Ensures(!String.IsNullOrEmpty(Descricao));
Contract.Ensures(Acao != null);
NomeDocumento = nomeDocumento;
Descricao = descricao;
Acao = acao;
}
[DomainSignature]
public String NomeDocumento { get; private set; }
[DomainSignature]
public String Descricao { get; private set; }
[DomainSignature]
public Acao Acao { get; private set; }
internal Int32 IdPedidoAssistencia { get; set; }
internal static Documento CriaNovo(String nomeDocumento, String descricao, Byte[] bytes, Acao acao)
{
Contract.Requires(!String.IsNullOrEmpty(nomeDocumento));
Contract.Requires(!String.IsNullOrEmpty(descricao));
Contract.Requires(bytes != null);
Contract.Requires(acao != null);
var documento = new Documento(nomeDocumento, descricao, acao) { Bytes = bytes };
return documento;
}
public void ModificaBytes(Byte[] bytes)
{
Contract.Requires(bytes != null);
Bytes = bytes;
}
public void SetAssignedIdTo(int assignedId)
{
Id = assignedId;
}
[ContractInvariantMethod]
private void Invariants()
{
Contract.Invariant(NomeDocumento != null);
Contract.Invariant(Descricao != null);
Contract.Invariant(Acao != null);
}
}
Base classes are the just for the basic stuff, ie, setting Id and injecting base code for instance comparison. At first sight, I can't really see anything wrong with this code. I mean, the property is virtual, the mapping says it should be virtual, so why does loading it with Get forces a complete load of the properties? For instance, this code:
var d = sess.Get(148);
Ends up generating sql for loading all the properties on the table. Did I get this wrong?
thanks!

Yes, it's confirmed: in order to have lazy load properties on a class, the class will also need to be lazy.

Related

Setting up examples in Swagger

I am using Swashbuckle.AspNetCore.Swagger (1.0.0) and Swashbuckle.AspNetCore.SwaggerGen (1.0.0). I am trying to add default examples to my API following Default model example in Swashbuckle (Swagger). I created a new class file and added,
public class SwaggerDefaultValue : Attribute
{
public string ParameterName { get; set; }
public string Value { get; set; }
public SwaggerDefaultValue(string parameterName, string value)
{
this.ParameterName = parameterName;
this.Value = value;
}
}
public class AddDefaultValues : IOperationFilter
{
public void Apply(Operation operation, DataTypeRegistry dataTypeRegistry, ApiDescription apiDescription)
{
foreach (var param in operation.Parameters)
{
var actionParam = apiDescription.ActionDescriptor.GetParameters().First(p => p.ParameterName == param.Name);
if (actionParam != null)
{
var customAttribute = actionParam.ActionDescriptor.GetCustomAttributes<SwaggerDefaultValue>().FirstOrDefault();
if (customAttribute != null)
{
param.DefaultValue = customAttribute.Value;
}
}
}
}
}
but I get this error - AddDefaultValues does not implement interface member IOperationFilter.Apply(Operation, OperationFilterContext)
That link you are following is not for the Swashbuckle.AspNetCore version
Look in the correct project for the proper examples:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/search?q=IOperationFilter&unscoped_q=IOperationFilter

Trouble mocking a private method

So, I am having an issue mocking a private method. From everything I have seen it should work, but isn't.
Let's start with the basics - Here is the code under test
public sealed class UnderTest
{
private bool MockPrivate(string name)
{
[snip]
}
private string MethodUnderTest(ParameterHolder parameters)
{
if (!this.MockPrivate(parameters.Parameter2))
{
return null;
}
[Snip]
}
[Snip]
}
public sealed class ParameterHolder
{
public ParameterHolder (bool parameter1, string parameter2)
{
this.Parameter1 = parameter1;
this.Parameter2 = parameter2;
}
public bool Parameter1
{
get;
private set;
}
public string Parameter2
{
get;
private set;
}
}
Here is the test method
public void Test_UnderTest_MethodUnderTest()
{
UnderTest testClass;
ParameterHolder parameters;
dynamic h;
testClass = new UnderTest();
parameters = Isolate.Fake.Instance<ParameterHolder>(Members.CallOriginal);
Isolate.WhenCalled(() => parameters.Parameter1).WillReturn(true);
Isolate.WhenCalled(() => parameters.Parameter2).WillReturn("parameter2value");
h = testClass.AsDynamic();
Isolate.WhenCalled(() => h.MockPrivate((string)null)).WillReturn(true);
Assert.IsNotNull(h.MethodUnderTest(parameters));
}
I have also tried to change the isolate call to:
Isolate.WhenCalled(() => h.MockPrivate("parameter2value").WillReturn(true);
and
Isolate.WhenCalled(() => h.MockPrivate(parameters.Parameter2).WillReturn(true);
In all the cases, the MockPrivate method gets executed, instead of returning the mocked True value.
Any help would be appreciated.
Ok, did some more checking and this is the correct way:
Isolate.NonPublic.WhenCalled(testClass, "MockPrivate").WillReturn(true);

NInject kernel GetAll returns empty

I've two projects (class library projects) which implement one interface:
The first one:
public class MailPlugin : Extensibility.IProductorPlugin
{
...
}
The second one:
public class FileSystemPlugin : Extensibility.IProductorPlugin
{
...
}
Extensibility.IProductorPlugin, is a interface of a third project:
namespace Extensibility
{
public delegate void NotifyDigitalInputs(List<Domain.DigitalInput> digital_inputs);
public interface IProductorPlugin
{
String Name { get; }
String Description { get; }
String Version { get; }
List<Domain.Channel> AvailableChannels { get; }
IEnumerable<Guid> TypeGuids { get; }
event NotifyDigitalInputs OnDigitalInputs;
}
}
In my composition root, I've created this class:
namespace UI
{
public sealed class NinjectServiceLocator
{
private static readonly Lazy<NinjectServiceLocator> lazy = new Lazy<NinjectServiceLocator>(() => new NinjectServiceLocator());
public static NinjectServiceLocator Instance { get { return lazy.Value; } }
public Ninject.IKernel Kernel { get; private set; }
private NinjectServiceLocator()
{
using (var k = this.Kernel = new Ninject.StandardKernel())
{
k.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(Extensibility.IProductorPlugin))
.BindAllInterfaces()
);
}
}
}
}
So, when I want to look for all plugins, I just perform this:
protected void initialize()
{
foreach (Extensibility.IProductorPlugin productor_plugin in NinjectServiceLocator.Instance.Kernel.GetAll(typeof(Extensibility.IProductorPlugin)))
{
using (var channel_tile = new DevExpress.XtraBars.Docking2010.Views.WindowsUI.Tile() { Group = "Plugin Channels" })
{
foreach (Domain.Channel channel in productor_plugin.AvailableChannels)
{
channel_tile.Elements.Add(new DevExpress.XtraEditors.TileItemElement() { Text = channel.Name });
channel_tile.Elements.Add(new DevExpress.XtraEditors.TileItemElement() { Text = channel.Description });
this.tileContainer1.Items.Add(channel_tile);
}
}
}
}
However, GetAll returns anything.
What am I doing wrong?
I'll appreciate a lot your help.
Thanks for all.
try removing the using() from around the Kernel instantiation. a using will dispose the object at the end of the scope, which we don't want for a kernel.
using (var k = this.Kernel = new Ninject.StandardKernel())

Auditing user using NHibernate Envers fluentconfiguration

I am trying to use NHibernate Envers to log an additional field "user". I have followed several code examples that seem to vary a bit when it comes to syntax, probably because some of them are a bit out of date. However I can't get it to work.
I'm getting this exception:
Only one property may have the attribute [RevisionNumber]!
My Custom Revision Entity:
public class CustomRevisionEntity
{
public virtual int Id { get; set; }
public virtual DateTime RevisionTimestamp { get; set; }
public virtual Guid UserIdentityId { get; set; }
public override bool Equals(object obj)
{
if (this == obj) return true;
var revisionEntity = obj as CustomRevisionEntity;
if (revisionEntity == null) return false;
var that = revisionEntity;
if (Id != that.Id) return false;
return RevisionTimestamp == that.RevisionTimestamp;
}
public override int GetHashCode()
{
var result = Id;
result = 31 * result + (int)(((ulong)RevisionTimestamp.Ticks) ^ (((ulong)RevisionTimestamp.Ticks) >> 32));
return result;
}
}
My IRevisionListener:
public class RevInfoListener : IRevisionListener
{
public void NewRevision(object revisionEntity)
{
var casted = revisionEntity as CustomRevisionEntity;
if (casted != null)
{
casted.UserIdentityId = Guid.NewGuid(); // TODO
}
}
}
First I use mapping by code to map the entity:
_modelMapper.Class<CustomRevisionEntity>(entity =>
{
entity.Property(x => x.Id);
entity.Property(x => x.RevisionTimestamp);
entity.Property(x => x.UserIdentityId);
});
Then I configure Envers and NHibernate
var enversConf = new FluentConfiguration();
enversConf.SetRevisionEntity<CustomRevisionEntity>(x => x.Id, x => x.RevisionTimestamp, new RevInfoListener());
enversConf.Audit<OrganizationEntity>().Exclude(x => x.Version);
configuration.IntegrateWithEnvers(enversConf); // This is the nh-configuration
The last line gives me the exception:
Only one property may have the attribute [RevisionNumber]!
Anyone have any ideas? Myself I would speculate that the default revision entity is still used somehow and when I try to register my custom revision entity this happens.
The error message occurred because the Id property was being mapped twice.
In our mapping class we had this
_modelMapper.BeforeMapClass += (modelInspector, type, classCustomizer) => classCustomizer.Id(type.GetProperty("Id"), (idMapper) =>
{
idMapper.Access(Accessor.Property);
idMapper.Generator(Generators.GuidComb);
});
Then we tried mapping Id again as a property of the CustomRevisionEntity
The final mapping:
_modelMapper.Class<CustomRevisionEntity>(entity =>
{
entity.Id<int>(x => x.Id, mapper => mapper.Generator(Generators.Identity));
entity.Property(x => x.RevisionDate);
entity.Property(x => x.UserIdentityId);
});

AsProjection() throwing exception for async query

In a simple test scenario which can be setup using the following:
public class TestObj
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Summary
{
public string MyId { get; set; }
public string MyName { get; set; }
}
public class TestObjs_Summary : AbstractIndexCreationTask<TestObj, Summary>
{
public TestObjs_Summary()
{
Map = docs => docs.Select(d => new { MyId = d.Id, MyName = d.Name });
Store(x => x.MyId, FieldStorage.Yes);
Store(x => x.MyName, FieldStorage.Yes);
}
}
static IDocumentStore Setup()
{
var store = new DocumentStore() { Url="http://localhost:8080" };
store.Initialize();
IndexCreation.CreateIndexes(MethodInfo.GetCurrentMethod().DeclaringType.Assembly, store);
using (var session = store.OpenSession())
{
session.Store(new TestObj { Name = "Doc1" });
session.Store(new TestObj { Name = "Doc2" });
session.SaveChanges();
}
return store;
}
I can run a simple synchronous query against the index and get the expected results (2 rows output of type Summary):
using (var session = store.OpenSession())
{
var q = session.Query<Summary>("TestObjs/Summary").AsProjection<Summary>();
Dump("Sync:", q.ToList());
}
However, if I try the same thing using an asynchronous query:
using (var session = store.OpenAsyncSession())
{
var q = session.Query<Summary>("TestObjs/Summary").AsProjection<Summary>();
q.ToListAsync().ContinueWith(t => Dump("Async:", t.Result));
}
I get an InvalidCastException:
InnerException: System.InvalidCastException
Message=Unable to cast object of type 'TestObj' to type 'Summary'.
Source=Raven.Client.Lightweight
StackTrace:
at Raven.Client.Document.InMemoryDocumentSessionOperations.ConvertToEntity[T](String id, RavenJObject documentFound, RavenJObject metadata) in c:\Builds\RavenDB-Unstable\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:line 416
at Raven.Client.Document.InMemoryDocumentSessionOperations.TrackEntity[T](String key, RavenJObject document, RavenJObject metadata) in c:\Builds\RavenDB-Unstable\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:line 340
at Raven.Client.Document.SessionOperations.QueryOperation.Deserialize[T](RavenJObject result) in c:\Builds\RavenDB-Unstable\Raven.Client.Lightweight\Document\SessionOperations\QueryOperation.cs:line 130
...
I suspect this is a bug, but as a RavenDB newbie, I first wanted to rule out the possibility I have screwed something up here. Can anyone see why this code would be failing?
(Note: this was run on Build 721 and on 701 and both produce the same results)
Thanks for any assistance you can provide.
It looks like a bug. I don't see anything wrong in your code. I suggest you create an issue here: http://issues.hibernatingrhinos.com