NHibernate MappingException - c#

I have been interested in learning NHibernate, so i search a course, and i found one in Pluralsight, but when i go to follow the examples i get this exception and i don't know why i get this exception... and it's kind of annoying because where i search i can't find more info about the exception or an up-to-date guide of NHibernate. So my question is:
a) for the exception itself, why it occurs
b) if you can recommend me a site or a course or anything up to date to learn NHibernate.
Thanks in advance.
I leave the code here:
Customer.cs:
namespace NHibernateDemo
{
public class Customer
{
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
}
Customer.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:hibernate-mapping-2.2"
assembly="NHibernateDemo"
namespace="NHibernateDemo">
<class name="Customer">
<id name="Id">
<generator class="native"/>
</id>
<property name="FirstName"/>
<property name="LastName"/>
</class>
</hibernate-mapping>
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
namespace NHibernateDemo
{
class Program
{
static void Main(string[] args)
{
var cfg = new Configuration();
cfg.DataBaseIntegration(x =>
{
x.ConnectionString = "Server=localhost;Database=NHibernateDemo;Integrated Security=SSPI;";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
});
// Here is where i get the MappingException. It says that it can't compile the Customer.hbm.xml file.
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sessionFactory = cfg.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
var customers = session.CreateCriteria<Customer>()
.List<Customer>();
foreach (var customer in customers)
{
Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
}
tx.Commit();
}
Console.WriteLine("Press <ENTER> to exit...");
Console.ReadLine();
}
}
}
}
Message of the exception:
"Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml"
StackTrace:
NHibernate.MappingException: Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml ---> System.InvalidOperationException: Error en el documento XML (1, 2). ---> System.InvalidOperationException: No se esperaba <hibernate-mapping xmlns='urn:hibernate-mapping-2.2'>.
en Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderHbmMapping.Read109_hibernatemapping()
--- Fin del seguimiento de la pila de la excepción interna ---
en System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
en System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document, XmlSerializer serializer)
en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document)
en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
--- Fin del seguimiento de la pila de la excepción interna ---
en NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
en NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
en NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
en NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
en NHibernateDemo.Program.Main(String[] args) en d:\Sistema\Documents\Visual Studio 2015\Projects\NHibernateDemo\NHibernateDemo\Program.cs:línea 28

the problem is that it can't find the file to compile it, so :
try manually copying the file into your bin directory ( Debug or Release or .. )
make sure your NHibernateDemo.Customer.hbm.xml properties are Build Action : Embedded resource and Copy to Output Directory : Copy Always
if you still have the problem, try adding : cfg.AddFile("NHibernateDemo.Customer.hbm.xml") ( or the path to your hbm.xml file )
if you still have the problem, then try :
cfg.addFile(AssemblyLocation() + "NHibernateDemo.Customer.hbm.xml"); ( or the path to your hbm.xml file, where AssemblyLocation() is :
private string AssemblyLocation()
{
var codebase = new Uri(Assembly.GetExecutingAssembly().CodeBase);
return Path.GetDirectoryName(codebase.LocalPath);
}
cfg.AddAssembly isn't necessary so you might consider removing it if none of the above works :P

I found (thanks to Fréderic) that the problem was a line in the hbm.xml file. This line was the one that have make the problem occur: <hibernate-mapping xmlns="urn:hibernate-mapping-2.2". I forgot a 'n' in front of the 'hibernate' word and because of that it can't parse the file.
Thanks to Taki and Fréderic for the time.

Related

What could cause a deserialization in a deployed service to fail while it succeeds localy?

I added a second method to my WCF service. It essentially does the same job as the other one except that it receives an xml document, deserialise it, and call the other method. It works perfectly locally, my XML is deserialized and the call succeeds. However, now that I have deployed it on my on-premise server, the call returns a 500 error because the deserialization failed.
My XML document has namespaces associated with every node, the root, and sub-root element have the "ns1" et all the others "ns2" prefix. To do the deserialization I (for now at least) hardcoded the namespaces for each node.
The troncated xml document:
<ns1:ValiderEtEnrichirGlobalEchangePartage
xmlns:ns1="API:WebApi"
xmlns:ns0="http://www.ra.fr/API/Transport/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns1:messageGlobal>
<ns0:AuteurEchange>...</ns0:AuteurEchange>
<ns0:Documents>
<ns0:DocumentEchangePartage>...</ns0:DocumentEchangePartage>
</ns0:Documents>
<ns0:ExpediteurEchange>...</ns0:ExpediteurEchange>
</ns1:messageGlobal>
</ns1:ValiderEtEnrichirGlobalEchangePartage>
The deserialising process in the service's method:
public GlobalEchangePartageValide ValiderEtEnrichirGlobalEchangePartageXML(string xmlMessageGlobal)
{
XmlRootAttribute xroot = new XmlRootAttribute();
xroot.ElementName="ValiderEtEnrichirGlobalEchangePartage";
xroot.Namespace="API:WebApi";
XmlSerializer serializer = new XmlSerializer(typeof(ValiderEtEnrichirGlobalEchangePartage),xroot );
StringReader stringReader = new StringReader(xmlMessageGlobal);
ValiderEtEnrichirGlobalEchangePartage messageGlobal = (ValiderEtEnrichirGlobalEchangePartage)serializer.Deserialize(stringReader);
return ValiderEtEnrichirGlobalEchangePartage(messageGlobal.GlobalEchangePartage);
}
The class coresponding to the xml root element:
[XmlRootAttribute("ValiderEtEnrichirGlobalEchangePartage")]
public class ValiderEtEnrichirGlobalEchangePartage
{
[XmlElement(ElementName=("messageGlobal"))]
public GlobalEchangePartage GlobalEchangePartage { get; set; }
}
The class of xml sub root element:
[DataContract(Namespace = NamespacesConstantes.NAMESPACE_TRANSPORT)]
public class GlobalEchangePartage
{
[DataMember]
[XmlElement(ElementName = ("AuteurEchange"), Namespace = "http://www.ra.fr/API/Transport/")]
public Auteur AuteurEchange { get; set; }
[DataMember]
[XmlElement(ElementName = ("ExpediteurEchange"), Namespace = "http://www.ra.fr/API/Transport/")]
public Auteur ExpediteurEchange { get; set; }
[DataMember]
[XmlArray(ElementName="Documents", Namespace = "http://www.ra.fr/API/Transport/")]
[XmlArrayItem("DocumentEchangePartage")]
public List<DocumentEchangePartage> Documents { get; set; }
}
The error I get is in French very ambiguous but can be approximatively translated by :
WCF error : System.ServiceModel.Dispatcher.NetDispatcherFaultException: The formatting module generated an exception when trying to deserialize the
message: an error occurred when trying to deserialize the
API:WebApi:xmlMessageGlobal parameter. The InnerException message was 'An
error occurred when deserializing the System.String object. Ending (TN :
last /final ) element 'xmlMessageGlobal' from the namespace 'API:WebApi'
expected. Found element 'ns1:ValiderEtEnrichirGlobalEchangePartage' from the
namespace "API:WebApi'.
Original :
WCF error : System.ServiceModel.Dispatcher.NetDispatcherFaultException: Le
module de formatage a généré une exception en tentant de désérialiser le
message : Une erreur s'est produite en tentant de désérialiser le paramètre
API:WebApi:xmlMessageGlobal. Le message InnerException était 'Une
erreur s'est produite lors de la désérialisation de l'objet de type
System.String. Élément de fin 'xmlMessageGlobal' provenant de l'espace de
noms 'API:WebApi' attendu. Trouvé élément
'ns1:ValiderEtEnrichirGlobalEchangePartage' provenant de l'espace de noms
'API:WebApi'.'.
Notice how it says that 'xmlMessageGlobal' is expected in the XML document while it is the variable's name ...
Thanks (for reading) a lot !
PS : If the French error message could be put in something that collapses it, I would appreciate, i didn't find a way to do it.
The problem encountered was indeed a deserialization problem. However, it wasn't about the piece of code I had written, it was when the string parameter was beeing received. Because my xml doc was an wrapped in another xml document (the request) there was issues in the processing. By base64 encoding my XML in my Logic App, and decoding it in the service i was able to fix the deserialization issue.
TLDR : be careful when you send xml through a String parameter.

NHibernate MySqlException

I am trying use NHibernate to my MySQL but I have still issue with connection on my localhost database.
Exeptions:
MySql.Data.MySqlClient.MySqlException
HResult=0x80004005
Message=Unable to connect to any of the specified MySQL hosts.
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection()
at NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare()
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper)
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactoryImplementor sessionFactory)
at NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at TestE.Model.NHibernateHelper.get_Session() in C:\Users\hajek\source\repos\TestE\TestE\NHibernateHelper.cs:line 24
at TestE.Dao.DaoBase1..ctor() in C:\Users\hajek\source\repos\TestE\TestE\Dao\DaoBase.cs:line 20
at TestE.Dao.ItemDao..ctor() in C:\Users\hajek\source\repos\TestE\TestE\Dao\ItemDao.cs:line 13
at TestE.Program.Main(String[] args) in C:\Users\hajek\source\repos\TestE\TestE\Program.cs:line 16
Inner Exception 1:
WaitHandleCannotBeOpenedException: No handle of the given name exists.
Code:
namespace TestE.Model
{
public class NHibernateHelper
{
private static ISessionFactory factory;
private static MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
public static ISession Session
{
get
{
if (factory == null)
{
Configuration cfg = new Configuration();
factory = cfg.Configure("hibernate.cfg.xml").BuildSessionFactory();
}
return factory.OpenSession();
}
}
}
}
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it
for your own use before compile tests in VisualStudio.
-->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="TestE">
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
<property name="connection.connection_string">
Database=todo_list;Data Source=localhost;User Id=root;Password=root;
Protocol=memory;Old Guids=True;
</property>
<property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
</session-factory>
</hibernate-configuration>
Configuration is located in ~/bin/debug and Nhibernate can see it but still can not connect to database.
----- Sorry for my English Language.------
By default, shared memory is not enabled on Windows. This may be why your connection is failing.
Remove Protocol=memory; from your connection string to use a regular TCP/IP connection.

nhibernate set custom generator class in mapping file

i try to implement a custom generator class like this:
Creating a custom id generator for nHibernate
This example is in fluent Nhibernate and not what I want exactly. I want it for nhibernate with mapping.
I have the following lines of Code:
namespace webportale_ger_webservice.Routinen
{
public class NextKey : TableGenerator
{
private const Int32 SeedValue = 1048576;
public override object Generate(ISessionImplementor sessionimpl, object obj)
{
var session = NHibernateHelper.GetSession();
int counter = Convert.ToInt32(base.Generate(sessionimpl, obj));
return counter + SeedValue + 1;
}
}
}
Now I want to give this generator class the ID-property of the mapping document, like this:
<hibernate-mapping assembly="webportale ger webservice" namespace="webportale_ger_webservice.Model" xmlns="urn:nhibernate-mapping-2.2">
<class name="SPTPL" table="SPTPL" lazy="false" >
<id name="AR" column="AR" generator="webportale_ger_webservice.Routinen.NextKey"/>
But it doesn't work with generator="webportale_ger_webservice.Routinen.NextKey", the error message is the following:
NHibernate.Id.IdentifierGenerationException: Could not interpret id generator strategy: webportale_ger_webservice.Routinen.NextKey
bei NHibernate.Id.IdentifierGeneratorFactory.GetIdentifierGeneratorClass(String strategy, Dialect dialect)
bei NHibernate.Id.IdentifierGeneratorFactory.Create(String strategy, IType type, IDictionary`2 parms, Dialect dialect)
bei NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
bei NHibernate.Cfg.Configuration.BuildSessionFactory()
bei webportale_ger_webservice.DatabaseInterface.NHibernateHelper..cctor() in C:\Quellen\VSWebNeoBackEnd\VSWebNeoBackEnd\VSWebNeoBackEnd\project india webservice\DatabaseInterface\NHibernateHelper.cs:Zeile 34.
--- Ende der internen Ausnahmestapelüberwachung ---
bei webportale_ger_webservice.DatabaseInterface.NHibernateHelper.GetSession()
bei webportale_ger_webservice.india_webservice.InsertSP_Leistungsort(String vornameStr, String nachnameStr, String strasseStr, String hnrzusatzStr, Int32 hausnrStr, String plzStr, String ortStr, String mailStr, String dateStr, String telStr, String argef, String bemerkungStr, String arstrasse, String arplz) in C:\Quellen\VSWebNeoBackEnd\VSWebNeoBackEnd\VSWebNeoBackEnd\project india webservice\webportale_ger_webservice.asmx.cs:Zeile 382.
Does anyone know how to define the class correctly in mapping documents?
thank you.
In case, we provide a type, it is better to use full type name - mostly including the assembly name. So this should work:
<class name="SPTPL" table="SPTPL" lazy="false" >
//<id name="AR" column="AR" generator="webportale_ger_webservice.Routinen.NextKey"/>
<id name="AR" column="AR" generator="webportale_ger_webservice.Routinen.NextKey,webportale_ger_webservice"/>
Expecting that the assembly name is webportale_ger_webservice

System.accessviolationexception in nunit test

I'm using Visual Studio 2012 / C# with nUnit test, and get System.AccessViolationException on simple test...
When I launch the "Execute Test" option, the test returns OK.
When I launch the "Debug Test" option, I get System.AccessViolationException.
Screen Capture of the Exception - Sorry french one !
Adding "break on all exceptions" option, I get this (again, sorry, french) :
L'assembly nommé 'nunit.engine.api' a été chargé à partir de
'file:///C:/USERS/ALAIN/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/11.0/EXTENSIONS/CZBUZRPC.SXP/nunit.engine.api.DLL'
à l'aide du contexte LoadFrom. L'utilisation de ce contexte peut provoquer un
comportement inattendu lors des opérations de sérialisation, de conversion et de
résolution de dépendance. Dans la grande majorité des cas, il est recommandé
d'éviter le contexte LoadFrom. Pour ce faire, il suffit d'installer les assemblys
dans le Global Assembly Cache ou dans le répertoire ApplicationBase et d'utiliser
Assembly.Load lors du chargement explicite des assemblys.
I think something in my config is not good. I'm pretty sure the source is good and has no hidden bug.
Any help will help.
Here is the code :
Class1.cs
using System;
namespace ClassLibrary1
{
public class Class1
{
public String test = "1";
public Class1()
{
}
public void Test()
{
test = "2";
}
}
}
UnitTest1.cs
using ClassLibrary1;
using NUnit.Framework;
namespace UnitTestProject1
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
Class1 classe = new Class1();
Assert.AreEqual(classe.test, "1");
classe.Test();
Assert.AreEqual(classe.test, "2");
}
}
}

My created executable file will not run because it can't find the XML-files

I have been working on a big project, and today I tried to make an executable from it with microsoft visual studio 2010. This worked, but when try to run it the program will stop. This is probably because my function "public List load(int levelnumber)" cant find a projectpath. Because this one is made meanwhile compiling. My XML are in C:\test4\myLevels\ and my exe is in my C:\test folder. I put the myLevels folder with the XML files in the C:\test4\ folder by myself. Sorry for my bad english. Any help is welcome!
Error (in dutch, no idea how to change this to english):
Bestanden die helpen bij het beschrijven van het probleem:
C:\Users\woutr\AppData\Local\Temp\WER9F14.tmp.WERInternalMetadata.xml
C:\Users\woutr\AppData\Local\Temp\WERD03.tmp.appcompat.txt
C:\Users\woutr\AppData\Local\Temp\WERD81.tmp.mdmp Lees de
onlineprivacyverklaring: go.microsoft.com/fwlink/?linkid=104288&clcid=0x0413
Als de onlineprivacyverklaring niet beschikbaar is, lees dan onze
offlineprivacyverklaring: C:\Windows\system32\nl-NL\erofflps.txt
Photo of how the error looks like: imgur.com/77iAOGe
XML class:
public class XML
{
public void Save(List<Sprite> sprites, int levelnumber)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Sprite>));
CreateDirectory("myLevels");
using (TextWriter textWriter = new StreamWriter(#"myLevels\level_" + levelnumber + ".xml"))
{
serializer.Serialize(textWriter, sprites);
}
}
public List<Sprite> load(int levelnumber)
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Sprite>));
using (TextReader textReader = new StreamReader(#"myLevels\level_" + levelnumber + ".xml"))
{
List<Sprite> sprites = (List<Sprite>)deserializer.Deserialize(textReader);
return sprites;
}
}
private void CreateDirectory(string path)
{
if (!Directory.Exists(path))
{
DirectoryInfo dir = Directory.CreateDirectory(path);
}
}
}

Categories

Resources