Can I use NHibernate.Cfg.Configuration in Fluent-NHibernate when building a session factory? - nhibernate

I want to use the NHibernate configuration for FluentNhibernate when building a session.
This how I am constructing my factory session:
lock (_factorylock)
{
if (_factory == null)
{
nHibernateConfig = delegate
{
GetConfiguration();
};
nHibernateConfig.Invoke(GetConfiguration());
var cfg = Fluently.Configure().
Database(MsSqlConfiguration.MsSql2012)
.ExposeConfiguration( nHibernateConfig)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>());
_factory = cfg.BuildSessionFactory();
}
}
I am not sure about the delegate that I am using as well as the invoke method that I am calling there.
The method GetConfiguration looks like this:
private static NHibernate.Cfg.Configuration GetConfiguration()
{
var configuration = new NHibernate.Cfg.Configuration();
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var configFile = Directory.GetFiles(baseDirectory, ConfigFile, SearchOption.AllDirectories).FirstOrDefault();
return configuration.Configure(configFile);
}
and of course, I have the xml config that contains a connection string:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2012Dialect, NHibernate</property>
<property name="connection.connection_string">Database=authentication; Port=3306; Server=127.0.0.1; Uid=root; Pwd=; persistsecurityinfo=True;SslMode=none </property>
<property name="adonet.batch_size">100</property>
</session-factory>
</hibernate-configuration>

Figured it out.
There is no need for the delege and the GetConfiguration method.
All that I had to do was to insatiate the configuration object
var configuration = new Configuration();
configuration.Configure();
var cfg = Fluently.Configure(configuration)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>());
_factory = cfg.BuildSessionFactory();
worked like a charm and my code is a lot cleaner.

Related

HibernateConfigException An exception occurred parsing configuration

I created the console application using Nhibernate.
I created hibernate.cfg.xml file
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"
assembly="NHibernateDemo"
namespace="NHibernateDemo">
<session-factory>
<property name="connection.connection_string_name">default</property>
<property name="connection.driver_class">Nhibernate.Driver.SqlClientDriver</property>
<property name="dialect">Nhibernate.Dialect.MsSql2008Dialect</property>
<mapping assembly ="NHibernateDemo" />
</session-factory>
</hibernate-configuration>
and it's my code
using System;
using System.Linq;
using System.Reflection;
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Linq;
namespace NHibernateDemo
{
internal class Program
{
static void Main(string[] args)
{
NHibernateProfiler.Initialize();
var cfg = new Configuration();
cfg.Configure("hibernate.cfg.xml");
var sessionFactory = cfg.BuildSessionFactory();
int newId;
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
var newCustomer = CreateCustomer();
Console.WriteLine("Before saving:");
Console.WriteLine(newCustomer);
session.Save(newCustomer);
newId = newCustomer.Id;
tx.Commit();
}
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
var newCustomer = session.Load<Customer>(newId);
Console.WriteLine("\nAfter saving:");
Console.WriteLine(newCustomer);
session.Save(newCustomer);
tx.Commit();
}
Console.WriteLine("Enter any key to exit...");
Console.ReadKey();
}
private static Customer CreateCustomer()
{
return new Customer
{
FirstName = "Jonh",
LastName = "Doe",
Points = 100,
HasGoldStatus = true,
// MemberSince = new DateTime(2012, 1, 1),
CreditRating = CustomerCreditRating.Neutral,
AverageRating = 42.44454647,
Adress = new Location()
{
Street = "123 Somewhere Avenue",
City = "Nowhere",
Province = "Alberta",
Country = "Canada"
}
};
}
}
}
but when I tried to debug my application, I got HibernateConfigException The 'assembly' attribute is not declared
How to fix that?
UPD if I remove attributes assembly and namespace from hibernate.cfg.xml file I get other error
MappingException was unhandled
UPD2 My mapping file (Build Action = Embedded Resource)
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NHibernateDemo"
namespace="NHibernateDemo">
<class name="Customer">
<id name="Id">
<generator class="native" />
</id>
<property name="FirstName"/>
<property name="LastName"/>
<property name="AverageRating"/>
<property name="Points"/>
<property name="HasGoldStatus"/>
<property name="MemberSince" type="UtcDateTime"/>
<property name="CreditRating" type="CustomerCreditRatingType"/>
<component name="Adress">
<property name="Street"/>
<property name="City"/>
<property name="Province"/>
<property name="Country"/>
</component>
</class>
</hibernate-mapping>
You need to add the assambly in code:
var cfg = new Configuration();
cfg.AddAssembly("NHibernateDemo");
cfg.Configure("hibernate.cfg.xml");

RavenB select database

var store = new DocumentStore()
{
Url = #"http://localhost"
};
store.Initialize();
Blog blog = new Blog()
{
Title = "Hello RavenDB",
Category = "RavenDB",
Content = "This is a blog about RavenDB",
Comments = new BlogComment[]{
new BlogComment() { Title = "Unrealistic", Content= "This example is unrealistic"},
new BlogComment() { Title = "Nice", Content= "This example is nice"}
}
};
using (IDocumentSession session = store.OpenSession())
{
session.Store(blog);
session.SaveChanges();
}
The above code saves data to the default database. (It is a web application.) But I want it save data to another database that I created the raven management studio (web page). Where do i specify the database name? Also please tell me how I can save the connection string with the database name in the config file. This is how I would save it to config file without the database name
<connectionStrings>
<add name="Local" connectionString="DataDir = ~\Data"/>
<add name="Server" connectionString="Url = http://localhost:8080"/>
</connectionStrings>
All of your questions are explained in the documentation:
new DocumentStore
{
ConnectionStringName = "Local"
}
<connectionStrings>
<add name="Local" connectionString="DataDir=~\Data;Database=MyDatabaseName"/>
<add name="Server" connectionString="Url=http://localhost:8080;Database=MyDatabaseName"/>
</connectionStrings>
The other answers are ok, but for efficiency you really only want one instance of DocumentStore for your application, unless you are running multiple Raven servers and then it would be acceptable to have one per server.
If you are just connecting to different databases on the same server, you should use:
var store = new DocumentStore(...your connection string or inline options...);
using (var session = store.OpenSession("the database name")
{
...
}
You can keep your connection strings data as you shown, best with the databases names at the end:
<connectionStrings>
<add name="Core" connectionString="Url=http://localhost:8082/databases/Core"
providerName="My primary database." />
<add name="Backup" connectionString="Url=http://localhost:8082/databases/Backup"
providerName="My backup stuff." />
</connectionStrings>
Next you can implement singleton class which will keep all your handlers for defined sources, for example:
public class DocumentStoreProvider : IDocumentStoreProvider
{
private static readonly IDictionary<string, IDocumentStore> _documentStores = new Dictionary<string, IDocumentStore>();
private static readonly DocumentStoreProvider _instance = new DocumentStoreProvider();
private DocumentStoreProvider()
{
var connectionStrings = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings connectionString in connectionStrings)
{
var name = connectionString.Name;
var connection = connectionString.ConnectionString;
IDocumentStore currentStore = new DocumentStore { ConnectionStringName = name };
currentStore.Initialize();
currentStore.DatabaseCommands.EnsureDatabaseExists(name);
IndexCreation.CreateIndexes(Assembly.Load("Your.Assembly.Containing.Indexes"), currentStore);
_documentStores.Add(name, currentStore);
}
}
public static DocumentStoreProvider Instance
{
get { return _instance; }
}
public IDocumentStore GetDocumentStore(string key)
{
return _documentStores[key];
}
}
The usage can be following:
using (var session = DocumentStoreProvider.Instance.GetDocumentStore("Backup").OpenSession())
{
/* do stuff for chosen database... */
session.Store(something);
session.SaveChanges();
}

nhibernate 3.2 how to turn off show_sql

I am using nhibernate 3.2, I dont know by default show_sql is turned on or off, but decided to turn it off in my configuration anyway.
I dont know how to turn show_sql off, but I have following 2 lines in my configuration file. are they the same?
db.LogFormattedSql = false;
db.LogSqlInConsole = false;
public static Configuration Initialize()
{
var configuration = new Configuration();
configuration
.Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
.DataBaseIntegration(db =>
{
db.ConnectionStringName = "test";
db.Dialect<MySQLDialect>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.LogFormattedSql = false;
db.LogSqlInConsole = false;
})
.AddAssembly(typeof(User).Assembly)
.CurrentSessionContext<LazySessionContext>();
var mapper = new ConventionModelMapper();
mapper.WithConventions(configuration);
return configuration;
}
LogSqlInConsole enables or disables SQL console logging.
LogFormattedSql enables or disables formatting of that SQL.

NHibernate Validator not integrating with Fluent 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);
}

Why is am I getting a duplicate class mapping error

in my nhibernate session helper class, I load my entities into the configuration like:
static NHibernateHelper()
{
try
{
Configuration cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof (Category).Assembly);
cfg.AddAssembly(typeof (Product).Assembly);
SessionFactory = cfg.Configure().BuildSessionFactory();
}
catch (Exception ex)
{
}
}
It works fine if I only have 1 cfg.AddAssembly, but loading both Category and Product results in an error?
Are they both in a same assembly (Category and Product). If they are, then you just need one AddAssembly.
i think you are calling Configure twice try removing the first cfg.Configure();
this is how it should look :
static NHibernateHelper(){
try{
Configuration cfg = new Configuration();
cfg.AddAssembly(typeof (Category).Assembly);
cfg.AddAssembly(typeof (Product).Assembly);
SessionFactory = cfg.Configure().BuildSessionFactory();
}
catch (Exception ex){
}}