NHibernate Validator not integrating with Fluent NHibernate - nhibernate

I'm having some trouble getting NHV to work with Fluent NHibernate. A unit test that I have that has an entity that SHOULD be failing validation ends up throwing an ADO exception. I have NHV configured the following way:
private static void Init()
{
_SessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(connectionString)
.ShowSql())
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<SessionFactory>()
.ExportTo(pathToExportMappingsTo))
.ProxyFactoryFactory("NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu")
.ExposeConfiguration(ConfigureNhibernateValidator)
.BuildSessionFactory();
}
private static void ConfigureNhibernateValidator(Configuration config)
{
var nhvConfiguration = new NHibernate.Validator.Cfg.Loquacious.FluentConfiguration();
nhvConfiguration
.SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal)
.Register(Assembly.Load("Business.Objects")
.ValidationDefinitions())
.IntegrateWithNHibernate
.RegisteringListeners();
ValidatorEngine validatorEngine = new ValidatorEngine();
validatorEngine.Configure(nhvConfiguration);
ValidatorInitializer.Initialize(config, validatorEngine);
}
I've looked over this configuration several times now and scoured the internet to try and find out what's wrong with this. I've also looked at examples provided in the NHV source but I haven't been able to figure out why my unit test does not throw an InvalidStateException. I have a unit test to validate the same entity that should be failing that validates it directly via the validation engine and this works.
Does anyone see anything wrong with the above configuration?
I'm using NHibernate 3.1, NHibernate Validator 1.3 and Fluent NHibernate 1.2.0.712

I debugged this and it seemed that when it went to validate my entity it was initialize my validator engine again. I corrected this by changing the ConfigureNhibernateValidator(Configuration config) method above to the following (the key here was to set the SharedEngineProvider):
private static void ConfigureNhibernateValidator(Configuration config)
{
var provider = new NHibernateSharedEngineProvider();
NHibernate.Validator.Cfg.Environment.SharedEngineProvider = provider;
var nhvConfiguration = new NHibernate.Validator.Cfg.Loquacious.FluentConfiguration();
nhvConfiguration
.SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal)
.Register(Assembly.Load("Business.Objects")
.ValidationDefinitions())
.IntegrateWithNHibernate
.AvoidingDDLConstraints()
.RegisteringListeners();
ValidatorEngine validatorEngine = NHibernate.Validator.Cfg.Environment.SharedEngineProvider.GetEngine();
validatorEngine.Configure(nhvConfiguration);
ValidatorInitializer.Initialize(config, validatorEngine);
}

Related

Fluently.Configure throws "Database was not configured through Database method" exception

I am trying to get an in-house application up and running for debugging and when I start the solution, it fails calling the Fluently.Configure() method. Digging into the exception, I see the potential reason as "Database was not configured through Database method."
public static ISessionFactory IdCardSessionFactoryWeb
{
get
{
if (_idCardSessionFactoryWeb != null) return _idCardSessionFactoryWeb;
var cfg = new Configuration();
cfg.DataBaseIntegration(x =>
{
x.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
x.Driver<SybaseAdoNet4Driver>();
x.Dialect<SybaseAdoNet4Dialect>();
x.Batcher<SybaseASEBatcherFactory>();
});
_idCardSessionFactoryWeb = Fluently.Configure(cfg)
.ExposeConfiguration(c => c
.SetInterceptor(new ABCInterceptor())
.SetProperty(Environment.ShowSql, "true")
.SetProperty(Environment.WrapResultSets, "true")
.SetProperty("command_timeout", timeout)
.SetProperty("current_session_context_class", "web"))
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Batch>())
.BuildSessionFactory();
return _idCardSessionFactoryWeb;
}
}
Looks like I needed to update the nuget package, and then restart my solution.

Using JsonPatchDocument With PatchAsync In Blazor Client

In my Blazor Client project, I have the following code:
#using Microsoft.AspNetCore.JsonPatch
...
var doc = new JsonPatchDocument<Movie>()
.Replace(o => o.Title, "New Title");
await Http.PatchAsync("api/patch/" + MovieId, doc);
This won't compile with the following error:
Error CS1503 Argument 2: cannot convert from
'Microsoft.AspNetCore.JsonPatch.JsonPatchDocument'
to 'System.Net.Http.HttpContent'
After some research, I've installed Newtonsoft.Json but I'm unsure how to configure the project to use it, or if indeed this is the correct solution for getting JsonPatchDocument working in a Blazor Project?
If JsonPatchDocument is not supported by Blazor, how can I implement a HTTP Patch request?
I just had a different but related issue. You are correct that you need to be using Newtonsoft.Json instead of System.Text.Json on the client application. Here is an extension method that will turn your JsonPatchDocument into an HttpContent.
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> PatchAsync<T>(this HttpClient client,
string requestUri,
JsonPatchDocument<T> patchDocument)
where T : class
{
var writer = new StringWriter();
var serializer = new JsonSerializer();
serializer.Serialize(writer, patchDocument);
var json = writer.ToString();
var content = new StringContent(json, Encoding.UTF8, "application/json-patch+json");
return await client.PatchAsync(requestUri, content);
}
I know it's late but I hope it's helpful.

How to Mock NserviceBus SendLocal using Moq

context.Verify throws exception: object reference not set to the instance of the object
var context = new Mock<IMessagehandlerContext>();
context.Setup(x => x.SendLocal(It.IsAny<object>()))
.Returns(Task.CompletedTask);
context.Verify(b => b.SendLocal(It.IsAny<objec>()), Times.Exactly(1))
Instead of mocking IMessageHandlerContext, I'd suggest you use TestableMessageHandlerContext from NServiceBus.Testing nuget package. Checkout the documentation here .
A sample of how to use it is as follows:
[Test]
public async Task ShouldReplyWithResponseMessage()
{
var handler = new MyReplyingHandler();
var context = new TestableMessageHandlerContext();
await handler.Handle(new MyRequest(), context)
.ConfigureAwait(false);
Assert.AreEqual(1, context.RepliedMessages.Length);
Assert.IsInstanceOf<MyResponse>(context.RepliedMessages[0].Message);
}

DataContractSerializerOperationBehavior is not found when trying to use DataContractResolver

I am trying to use DataContractResolver as an alternative to KnownTypes in WCF.
I have the following code and I've used it before on the server side. But on the client side, the code returns null when trying to find DataContractSerializerOperationBehavior in operation behaviors collection.
public override IMyService CreateProxy(Uri url)
{
ServiceEndpoint endpoint = CreateEndpoint(url);
var channelFactory = new ChannelFactory<IMyService>(endpoint);
InjectResolver(channelFactory.Endpoint);
return channelFactory.CreateChannel();
}
private void InjectResolver(ServiceEndpoint endpoint)
{
foreach (OperationDescription operation in endpoint.Contract.Operations)
{
var behavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
behavior.DataContractResolver = new DerivedTypeResolver(); // behavior is null here!
}
}
Why is the behavior missing?
UPDATE: I found out the real issue is that WCF was using XmlSerializer instead of DataContractSerializer. Is there a way to force a DataContractSerializer instead? Does WCF choose the serializer based on the wsdl? Considering I don't (yet) have the capacity to change the server side, what is my option? XmlSerializer behavior doesn't seem to have a similar option of resolving the type myself.
See here for example on how to create DataContractSerializerOperationBehavior if it does not exist:
private void DataContractBehavior()
{
WSHttpBinding b = new WSHttpBinding(SecurityMode.Message);
Uri baseAddress = new Uri("http://localhost:1066/calculator");
ServiceHost sh = new ServiceHost(typeof(Calculator), baseAddress);
sh.AddServiceEndpoint(typeof(ICalculator), b, "");
// Find the ContractDescription of the operation to find.
ContractDescription cd = sh.Description.Endpoints[0].Contract;
OperationDescription myOperationDescription = cd.Operations.Find("Add");
// Find the serializer behavior.
DataContractSerializerOperationBehavior serializerBehavior =
myOperationDescription.Behaviors.
Find<DataContractSerializerOperationBehavior>();
// If the serializer is not found, create one and add it.
if (serializerBehavior == null)
{
serializerBehavior = new DataContractSerializerOperationBehavior(myOperationDescription);
myOperationDescription.Behaviors.Add(serializerBehavior);
}
// Change the settings of the behavior.
serializerBehavior.MaxItemsInObjectGraph = 10000;
serializerBehavior.IgnoreExtensionDataObject = true;
sh.Open();
Console.WriteLine("Listening");
Console.ReadLine();
}
example from https://msdn.microsoft.com/en-us/library/system.servicemodel.description.datacontractserializeroperationbehavior.aspx

NHibernate 3.2: SchemaExport not working with SQLite

I'm using an in-memory db for some quick unit tests, using the following code:
public class MemoryDb
{
private static Configuration configuration;
private static ISessionFactory sessionFactory;
static MemoryDb()
{
configuration = new NHibernate.Cfg.Configuration();
configuration.DataBaseIntegration(x =>
{
x.Driver<SQLite20Driver>();
x.Dialect<SQLiteDialect>();
x.ConnectionProvider<DriverConnectionProvider>();
x.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
x.IsolationLevel = IsolationLevel.ReadCommitted;
x.ConnectionString = "Data Source=:memory:;";
x.Timeout = 255;
x.BatchSize = 100;
x.LogFormattedSql = true;
x.LogSqlInConsole = true;
x.AutoCommentSql = false;
});
configuration.AddMapping(DbHelper.GetAutoMappings());
sessionFactory = configuration.BuildSessionFactory();
}
public static ISession GetSession()
{
var session = sessionFactory.OpenSession();
new SchemaExport(configuration).Execute(true, true, false, session.Connection, null);
return session;
}
}
The problem is that the schema export doesn't seem to be working. On of my tests looks like this:
[Fact]
public void ShouldFindDuplicateByEmail()
{
using (var session = MemoryDb.GetSession())
{
var repo = new NHibernateCustomerRepository(session);
var customer = new Customer();
customer.EmailAddress = "test#test.com";
repo.Save(customer);
var duplicates = repo.FindDuplicates(customer);
Assert.Equal(1, duplicates.Length);
}
}
The test fails with the error no such table: Customers. This all worked with Fluent NHibernate and NHibernate 3.1. I know it's not an issue with the mappings themselves, because the actual application works when I run it against an existing SQL Server db. It only fails when running the tests. Any thoughts?
Edit: If I change only the connection string such that it writes to a file (i.e. x.ConnectionString = "data source=" + Path.GetTempFileName();, the whole thing works. I'm guessing either the schema isn't run correctly against the in-memory db, or it's getting a new in-memory db each time I execute a session command, but have no clue how to figure this out.
I found the answer here: https://forum.hibernate.org/viewtopic.php?p=2397541#p2397541
I had to add the following to the db configuration:
x.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;
Otherwise, NHibernate releases the connection after each statement is flushed, thereby getting rid of the in-memory database with the schema.