locked
How to configure NHibernate at web.config with ASP.NET RRS feed

  • Question

  • User-284754267 posted
    Hi All,

    Any help would be much appreciated. It took long time to solve this issue. But I haven't got the solution.
    In my ASP.NET web application,I used NHibernate.dll and configuration is read from the Web.config file as follows.
    At Web.config
    <httpModules>
    <add name="CurrentSessionModule" type="Globals.CurrentSessionModule, Globals"/>
    </httpModules>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="connection.connection_string">Server=localhost;initial catalog=TESTDB;Integrated Security=SSPI</property>
    <property name="current_session_context_class">web</property>
    <property name="default_schema">dbo</property>
    <mapping assembly="LAT.Domain"/>
    </session-factory>
    </hibernate-configuration>

    At CurrentSessionModule.cs

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Web;
    using DataAccess;
    using NHibernate;
    using NHibernate.Cfg;
    using NHibernate.Context;

    namespace Globals
    {
    public class CurrentSessionModule : IHttpModule
    {


    public void Dispose()
    {
    }
    public void Init(HttpApplication context)
    {
    context.BeginRequest += delegate
    {
    string session = Global.SessionFactory.OpenSession();
    CurrentSessionContext.Bind(session);
    };
    context.EndRequest += delegate
    {
    CurrentSessionContext.Unbind(Global.SessionFactory);

    };
    }

    I reference this website( http://dotnetslackers.com/articles/aspn ... P-NET.aspx)
    but the main different between my project and the ref website is Global.asax
    my Global.asax

    <%@ Import namespace="System.Collections.Generic"%>
    <%@ Import namespace="System.Xml"%>
    <%@ Import namespace="System.IO"%>
    <%@ Import namespace="System.Web.Configuration"%>
    <%@ Application Language="C#" Inherits="Globals.LATApplication"%>

    <script runat="server">


    private static void LogData(string url, string httpSessionId, string Id)
    {
    if (!WebConfigurationManager.AppSettings["debugMode"].ToLower().Equals("none"))
    try{
    string fname = WebConfigurationManager.AppSettings["debugSessionLogFile"];
    XmlDocument doc = new XmlDocument();
    if (File.Exists(fname))
    doc.Load(fname);
    else
    doc.LoadXml("<SessionLog><Statistics HttpSessions=\"0\" NHibernateSessions=\"0\"/><Entries/></SessionLog>");
    XmlElement entry = doc.CreateElement("Entry");
    doc.DocumentElement.GetElementsByTagName("Entries")[0].AppendChild(entry);
    XmlAttribute att = doc.CreateAttribute("Time");
    att.Value = DateTime.Now.ToString();
    entry.Attributes.Append(att);
    att = doc.CreateAttribute("Url");
    att.Value = url;
    entry.Attributes.Append(att);
    XmlElement ele = doc.CreateElement("HttpSession");
    ele.InnerText = httpSessionId;
    entry.AppendChild(ele);
    ele = doc.CreateElement("NHibernateSession");
    ele.InnerText = Id;
    entry.AppendChild(ele);
    doc.Save(fname);
    }
    catch{}
    }


    void Application_Start(object sender, EventArgs e)
    {
    // Code that runs on application startup
    if (!WebConfigurationManager.AppSettings["debugMode"].ToLower().Equals("none"))
    {
    string fname = WebConfigurationManager.AppSettings["debugSessionLogFile"];
    try
    {
    if (File.Exists(fname))
    File.Delete(fname);
    }
    catch { }
    LogData("*Application Starting*", "*", "*");
    }


    }

    void Application_End(object sender, EventArgs e)
    {
    // Code that runs on application shutdown
    LogData("*Application Ending*", "*", "*");
    }

    void Application_Error(object sender, EventArgs e)
    {
    // Code that runs when an unhandled error occurs
    try
    {
    Exception ex = HttpContext.Current.Server.GetLastError();
    string err = ex.Message;
    string ierr = "";
    if (ex.InnerException != null)
    ierr = ex.InnerException.Message;
    LogData("*Application Error*", "*" + err + "*", "*" + ierr + "*");
    }
    catch (Exception except)
    {
    LogData("*Application Error*", "*" + except.Message + "*", "*Application_Error Error*");
    }
    }

    void Session_Start(object sender, EventArgs e)
    {
    // Code that runs when a new session is started
    LogData("*Session Starting*", Session.SessionID, "*");
    }

    void Session_End(object sender, EventArgs e)
    {
    LogData("*Session Ending*", Session.SessionID, "*");
    }

    </script>


    When I run the web application, I got the error " Illeglly attempt to associate a proxy with two open session".
    I am not really sure how that would happen. I try some solution but haven't solved the issues.

    Can anyone help me with this?

    Regards
    Su Hlaing
    Thursday, December 23, 2010 8:05 PM

Answers

  • User-284754267 posted

    Hi All,

    Now I already solved my issues regarding NHibernate in .net.

    I got the solution from the following website and it gave me some concepts to solve my issues and I got clear understanding in NHibernate after reading this documentation.

    http://nhforge.org/doc/nh/en/index.html#transactions

    I just changed the coding in some method at NhibernateHelper.cs

    public static ISession GetCurrentSession()

            {

                HttpContext context = HttpContext.Current;

                ISession currentSession = context.Items[CurrentSessionKey] as ISession;

     

                if (currentSession == null)

                {

                    currentSession = SessionFactory.OpenSession();

                    context.Items[CurrentSessionKey] = currentSession;

                }

             

                return currentSession;

            }

     

    public static void CloseSessionFactory()

            {

                if (SessionFactory != null)

                {

                    SessionFactory.Close();

                }

            }

     

    public static void CloseSession()

            {

                HttpContext context = HttpContext.Current;

                ISession currentSession = context.Items[CurrentSessionKey] as ISession;

     

                if (currentSession == null)

                {

                    // No current session

                    return;

                }

     

                currentSession.Close();

                context.Items.Remove(CurrentSessionKey);

            }

    I hope someone can reference my solution to save their time.

    Thanks.

    Su Hlaing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 7, 2011 1:07 AM

All replies

  • User1639443224 posted

     The first thing you’ve to do is tell ASP.NET that you’re going to configure NHibernate.

    This is done by declaring a section element under configSections.

    <configuration>   
    <configSections>      
    <section name="hibernate-configuration"         
    type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"          
    />  
    </configSections> 
    </configuration>

    The previous step enables you to declare a hibernate-configuration element under the configuration node without any complaints by the ASP.NET configuration parser.

    <configuration>    
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">     
    <session-factory>     
    </session-factory> 
    </hibernate> 
    </configuration>

    Adding a basic set of properties used in almost every project.

    <session-factory> 
    
       <property name="connection.provider"> 
          NHibernate.Connection.DriverConnectionProvider 
       </property> 
       <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property> 
       <property name="connection.connection_string"> 
          <!-- Insert the database connection string here -->
       </property> 
    </session-factory>
    




     

    Friday, December 24, 2010 4:04 AM
  • User-284754267 posted

     

    Hi,

    Thanks for your reply. My existing configuration at web.config is same as what you mentioned. But I got the error when i executed the method to load the DB which is using NHiberante mapping.  the error I got is " Illeglly attempt to associate a proxy with two open session".

    So I checked Global.asax. I didn't find any error or any wrong configuration.

    So I don't know how to figure it out.

    Any more detail would be much appreciated.

    Thanks and Regards

    Su Hlaing

     

    Monday, December 27, 2010 10:39 PM
  • User-284754267 posted

    Hi All,

    Now I already solved my issues regarding NHibernate in .net.

    I got the solution from the following website and it gave me some concepts to solve my issues and I got clear understanding in NHibernate after reading this documentation.

    http://nhforge.org/doc/nh/en/index.html#transactions

    I just changed the coding in some method at NhibernateHelper.cs

    public static ISession GetCurrentSession()

            {

                HttpContext context = HttpContext.Current;

                ISession currentSession = context.Items[CurrentSessionKey] as ISession;

     

                if (currentSession == null)

                {

                    currentSession = SessionFactory.OpenSession();

                    context.Items[CurrentSessionKey] = currentSession;

                }

             

                return currentSession;

            }

     

    public static void CloseSessionFactory()

            {

                if (SessionFactory != null)

                {

                    SessionFactory.Close();

                }

            }

     

    public static void CloseSession()

            {

                HttpContext context = HttpContext.Current;

                ISession currentSession = context.Items[CurrentSessionKey] as ISession;

     

                if (currentSession == null)

                {

                    // No current session

                    return;

                }

     

                currentSession.Close();

                context.Items.Remove(CurrentSessionKey);

            }

    I hope someone can reference my solution to save their time.

    Thanks.

    Su Hlaing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 7, 2011 1:07 AM