Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

paulopatto

Erro com NHibernate

Recommended Posts

Estou seguindo este tutorial na NET: http://www.linhadecodigo.com.br/Artigo.aspx?id=546&pag=2 e estou me deparando com a seguinte exceção no C#

System.TypeInitializationException was unhandled by user code
  Message="The type initializer for 'QuickStart.HibernateUtil' threw an exception."
  Source="App_Code.vzvuj67j"
  TypeName="QuickStart.HibernateUtil"
  StackTrace:
	   at QuickStart.HibernateUtil.BuildDatabase()
	   at _Default.Page_Load(Object sender, EventArgs e) in c:\Documents and Settings\Murilo\Meus documentos\Programacao\QuickStart\Default.aspx.cs:line 15
	   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
	   at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
	   at System.Web.UI.Control.OnLoad(EventArgs e)
	   at System.Web.UI.Control.LoadRecursive()
	   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Bem como sou iniciante na plataforma .NET esse pode até ser um erro bobo e ainda não consigo tratar de forma apropriada todas a exceptions. Bem em todo caso vou postar os códigos. Essa é uma aplicação WEB e como eu já disse estou até o momento na tentativa e erro.

 

 

 

 

 

 

 

 

//*************Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
	protected void Page_Load(object sender, EventArgs e)
	{
		QuickStart.HibernateUtil.BuildDatabase();
	}
}
//*************HibernateUtil.cs
#region Sessao Using
using System;
using System.Data;
using NHibernate;
using NHibernate.Cfg;
using MySql;
using MySql.Data;
#endregion

namespace QuickStart {
	public sealed class HibernateUtil
	{
		private const string CurrentSessionKey = "nhibernate.current_session";
		private static readonly ISessionFactory sessionFactory;
		private static NHibernate.Cfg.Configuration config;

		static HibernateUtil()
		{
			config = new NHibernate.Cfg.Configuration();
			sessionFactory = config.Configure().BuildSessionFactory();
		}

		public static NHibernate.Cfg.Configuration GetConfig() { return config; }

		public static ISession GetCurrentSession()
		{
			System.Web.HttpContext context = System.Web.HttpContext.Current;
			ISession currentSession = context.Items[CurrentSessionKey] as ISession;
			if (currentSession == null)
			{
				currentSession = sessionFactory.OpenSession();
				context.Items[CurrentSessionKey] = currentSession;
			}
			return currentSession;
		}

		public static NHibernate.ISession OpenSession() { return sessionFactory.OpenSession(); }

		public static void CloseSession()
		{
			System.Web.HttpContext context = System.Web.HttpContext.Current;
			ISession currentSession = context.Items[CurrentSessionKey] as ISession;
			if (currentSession == null) { return; }
			currentSession.Close();
			context.Items.Remove(CurrentSessionKey);
		}

		public static void CloseSessionFactory() { if (sessionFactory != null) { sessionFactory.Close(); } }

		public static void BuildDatabase()
		{
			try { new NHibernate.Tool.hbm2ddl.SchemaExport(config).Create(true, true); }
			catch (NHibernate.Exceptions.GenericADOException e) { Console.WriteLine("Erro desconhecido! e.StackTrace"); Console.WriteLine(e.StackTrace); }
		}
	}
}
//User.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0" namespace="Cs" assembly="Cs">
  <class name="Cs.User, Cs" table="users">
	<id name="Id" column="LogonId" type="String" length="20">
	  <generator class="assigned" />
	</id>

	<property name="UserName" column="Name" type="String" length="40" />
	<property name="Password" type="String" length="18" />
	<property name="EmailAddress" type="String" length="40" />
	<property name="LastLogon" type="DateTime"/>
  </class>
</hibernate-mapping>
//Web.Config
<?xml version="1.0"?>
<!-- 
	Note: As an alternative to hand editing this file you can use the 
	web admin tool to configure settings for your application. Use
	the Website->Asp.Net Configuration option in Visual Studio.
	A full list of settings and comments can be found in 
	machine.config.comments usually located in 
	\Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
	<!--Sessão de configuração do NHibernate 2.0.1-->
	<configSections>
		<section name="hibernate-configuration" type="System.Configuration.NameValueSectionHandler, System,
			 Version=1.0.3300.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
	</configSections>
	<appSettings/>
	<connectionStrings/>
	<system.web>
		<!-- 
			Set compilation debug="true" to insert debugging 
			symbols into the compiled page. Because this 
			affects performance, set this value to true only 
			during development.
		-->
		<compilation debug="true">
			<assemblies>
				<add assembly="MySql.Data, Version=5.2.5.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
				<add assembly="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
		<!--
			The <authentication> section enables configuration 
			of the security authentication mode used by 
			ASP.NET to identify an incoming user. 
		-->
		<authentication mode="Windows"/>
		<!--
			The <customErrors> section enables configuration 
			of what to do if/when an unhandled error occurs 
			during the execution of a request. Specifically, 
			it enables developers to configure html error pages 
			to be displayed in place of a error stack trace.

		<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
			<error statusCode="403" redirect="NoAccess.htm" />
			<error statusCode="404" redirect="FileNotFound.htm" />
		</customErrors>
		-->
	</system.web>
	<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
	<!--
		<session-factory>
			<property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
			<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
			<property name="connection.connection_string">Database=lab; Data Source=localhost; User Id=root; Password=root</property>
			<mapping assembly="QuickStart"/>
	  <mapping assembly="Cs" />
		</session-factory>
	-->
	<add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
	<add key="hibernate.dialect" value="NHibernate.Dialect.MySQL5Dialect" />
	<add key="hibernate.connection.driver_class" value="NHibernate.Driver.MySqlDataDriver" />
	<add key="connection.connection_string" value="Database=lab; Data Source=localhost; User Id=root; Password=root" />
	</hibernate-configuration>
</configuration>

//User.cs
namespace Cs
{
	public class User
	{
		private string id;
		private string userName;
		private string password;
		private string emailAddress;
		private System.DateTime lastLogon;

		public User() { }

		public string Id
		{
			get { return this.id; }
			set { this.id = value; }
		}
		public string UserName {
			get { return this.userName; }
			set { this.userName = value; }
		}
		public string Password
		{
			get { return this.password; }
			set { this.password = value; }
		}
		public string EmailAddress
		{
			get { return this.emailAddress; }
			set { this.emailAddress = value; }
		}
		public System.DateTime LastLogon
		{
			get { return this.lastLogon; }
			set { this.lastLogon = value; }
		}
	}
}

 

OBS.:Classes no mesmo namespace. Ou tem seus namespace explicitamente referênciados

OBS.:Nome dos arquivos na primeira linha do código

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.