NHibernate.Helper Project

本文介绍了一个辅助项目,旨在简化NHibernate在ASP.NET应用程序中的使用。该项目通过自动创建和关闭会话来确保每个请求正确管理NHibernate会话,并提供了一些便捷的方法来简化编码。

NHibernate.Helper Project

Overview

http://blogs.intesoft.net/simon/articles/16.aspx

When using NHibernate in an ASP.NET application it is important to manage sessions correctly. Typically, a session-per-request pattern is used with a single session created and used for the lifetime of a request and then discarded. This helper project makes using NHibernate with ASP.NET easier by automating the creation of sessions and ensuring that they are closed after each request. It also provides some convenient methods to make coding simpler and more readable:

Automatically create the database schema:

Db.CreateDatabase();

Load an object from the database

Customer customer = (Customer)Db.Load(typeof(Customer), 123);

Save an object:

Db.Save(Customer);

Delete an object:

Db.Delete(Customer);

Access to the NHibernate Configuration and SessionFactory objects are provided if needed.

Configuration

NHibernate already has a comprehensive and flexible configuration system where settings can be defined in code, in the web.config file or in a separate XML file. Using the separate XML file enables the location of the mapping files to be configured as required. The configuration below defines the NHibernate connection properties and driver classes to use (these could also be defined in the web.config file) and the location of the nhibernate mapping files (in this case the assembly 'MyAssembly' which would contain embedded resources).

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.0" > 
    <session-factory name="chat"> 
        <!-- properties --> 
        <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> 
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> 
        <property name="connection.connection_string">Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI</property> 
        <property name="show_sql">false</property> 
        <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property> 
        <property name="use_outer_join">true</property> 
        <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> 
        <!-- mapping files --> 
        <mapping assembly="MyAssembly" /> 
    </session-factory> 
</hibernate-configuration>

Rather than simply use the default filename "nhibernate.cfg.xml" I prefer instead to use "nhibernate.config", mainly because using an xml file extension is a security risk as the config file could easily be downloaded whereas access to the .config extension is restricted by ASP.NET automatically. To provide some extra flexibility the name of the file is specified in the <appSetting> section with the key "nhibernate.config":

    <appSettings> 
        <add key="nhibernate.config" value="~/nhibernate.config" /> 
    </appSettings> 

Now, the only other thing that needs to be added to the web.config file is the entry for the HttpModule:

    <httpModules> 
        <add name="NHibernateModule" type="NHibernate.Helper.Module, NHibernate.Helper" /> 
    </httpModules> 

Here is the HttpModule itself. As you can see, it is extremly simple and simply closes the connection at the end of the request.

using System; 
using System.Web; 

namespace NHibernate.Helper 
{ 
    /// <summary> 
    ///        HttpModule to automatically close a session at the end of a request 
    /// </summary> 
    public sealed class Module : IHttpModule 
    { 
        public void Init(HttpApplication context) 
        { 
            context.EndRequest += new EventHandler(EndRequest); 
        } 

        public void Dispose() { } 
         
        public void EndRequest(Object sender, EventArgs e) 
        { 
            Db.CloseSession(); 
        } 
    } 
} 

The Db class contains all the helper methods and manages the creation and lifetime of the sessions (with the HttpModule above).

using System; 
using System.Web; 
using System.Configuration; 

using NHibernate; 
using NHibernate.Cfg; 

namespace NHibernate.Helper 
{ 
    /// <summary> 
    ///        Provides access to a single NHibernate session on a per request basis. 
    /// </summary> 
    /// <remarks> 
    ///        NHibernate requires mapping files to be loaded. These can be stored as 
    ///        embedded resources in the assemblies alongside the classes that they are for or 
    ///        in separate XML files. 
    ///        <br /><br /> 
    ///        As the number of assemblies containing mapping resources may change and 
    ///        these have to be referenced by the NHibernate config before the SessionFactory 
    ///        is created, the configuration is stored in a separate config file to allow 
    ///        new references to be added. This would also enable the use of external mapping 
    ///        files if required. 
    ///        <br /><br /> 
    ///        The name of the NHibernate configuration file is set in the appSettings section 
    ///        with the name "nhibernate.config". If not specified the the default value of 
    ///        ~/nhibernate.config is used. 
    ///        <br /><br /> 
    ///        Note that the default config name is not used because the .xml extension is 
    ///        public and could be downloaded from a website whereas access to .config files is 
    ///        automatically restricted by ASP.NET. 
    /// </remarks> 

    public sealed class Db 
    { 
        /// <summary> 
        /// Key used to identify NHibernate session in context items collection 
        /// </summary> 
        private const string sessionKey = "NHibernate.Db"; 

        /// <summary> 
        /// NHibernate Configuration 
        /// </summary> 
        private static readonly Configuration configuration = new Configuration(); 

        /// <summary> 
        /// NHibernate SessionFactory 
        /// </summary> 
        private static readonly ISessionFactory sessionFactory = configuration.Configure( HttpContext.Current.Request.MapPath(ConfigurationSettings.AppSettings["nhibernate.config"]) ).BuildSessionFactory(); 

        /// <summary> 
        /// NHibernate Session. This is only used for NUnit testing (ie. when HttpContext 
        /// is not available. 
        /// </summary> 
        private static readonly ISession session = sessionFactory.OpenSession(); 

        /// <summary> 
        /// None public constructor. Prevent direct creation of this object.  
        /// </summary> 
        private Db() { } 

        /// <summary> 
        /// See beforefieldinit 
        /// </summary> 
        static Db() { } 

        /// <summary> 
        /// Creates a new NHibernate Session object if one does not already exist. 
        /// When running in the context of a web application the session object is 
        /// stored in HttpContext items and has 'per request' lifetime. For client apps 
        /// and testing with NUnit a normal singleton is used. 
        /// </summary> 
        /// <returns>NHibernate Session object.</returns> 
        [CLSCompliant(false)] 
        public static ISession Session 
        { 
            get  
            {  
                ISession session; 
                if (HttpContext.Current == null) 
                { 
                    session = Db.session; 
                } 
                else 
                { 
                    if (HttpContext.Current.Items.Contains(sessionKey)) 
                    { 
                        session = (ISession)HttpContext.Current.Items[sessionKey]; 
                    } 
                    else 
                    { 
                        session = Db.sessionFactory.OpenSession(); 
                        HttpContext.Current.Items[sessionKey] = session; 
                    } 
                } 
                return session;  
            }                 
        } 

        /// <summary> 
        /// Closes any open NHibernate session if one has been used in this request.<br /> 
        /// This is called from the EndRequest event. 
        /// </summary> 
        [CLSCompliant(false)] 
        public static void CloseSession() 
        { 
            if (HttpContext.Current == null) 
            { 
                Db.session.Close(); 
            } 
            else 
            { 
                if (HttpContext.Current.Items.Contains(sessionKey)) 
                { 
                    ISession session = (ISession)HttpContext.Current.Items[sessionKey]; 
                    session.Close(); 
                    HttpContext.Current.Items.Remove(sessionKey); 
                } 
            } 
             
        } 

        /// <summary> 
        /// Returns the NHibernate Configuration object. 
        /// </summary> 
        /// <returns>NHibernate Configuration object.</returns> 
        [CLSCompliant(false)] 
        public static Configuration Configuration 
        { 
            get { return Db.configuration; } 
        } 

        /// <summary> 
        /// Returns the NHibernate SessionFactory object. 
        /// </summary> 
        /// <returns>NHibernate SessionFactory object.</returns> 
        [CLSCompliant(false)] 
        public static ISessionFactory SessionFactory 
        { 
            get { return Db.sessionFactory; } 
        } 

        /// <summary> 
        /// Loads the specified object. 
        /// </summary> 
        /// <param name="type">Type.</param> 
        /// <param name="id">Id.</param> 
        public static void Load(System.Type type, object id) 
        { 
            Db.Session.Load(type, id); 
        } 

        /// <summary> 
        /// Gets the specified object. 
        /// </summary> 
        /// <param name="type">Type.</param> 
        /// <param name="id">Id.</param> 
        public static object Get(System.Type type, object id) 
        { 
            return Db.Session.Get(type, id); 
        } 

        /// <summary> 
        /// Save object item using NHibernate. 
        /// </summary> 
        /// <param name="item">Object to save</param> 
        public static void Save(object item) 
        { 
            ITransaction transaction = Db.Session.BeginTransaction(); 

            try 
            { 
                Db.Session.Save(item); 
                transaction.Commit(); 
            } 
            catch (Exception ex) 
            { 
                transaction.Rollback(); 
                throw; 
            } 
        } 

        /// <summary> 
        /// Save object item using NHibernate. 
        /// </summary> 
        /// <param name="item">Object to delete</param> 
        public static void Delete(object item) 
        { 
            ITransaction transaction = Db.Session.BeginTransaction(); 

            try 
            { 
                Db.Session.Delete(item); 
                transaction.Commit(); 
            } 
            catch (Exception ex) 
            { 
                transaction.Rollback(); 
                throw; 
            } 
        } 

        /// <summary> 
        /// Creates the specified database. 
        /// </summary> 
        /// <param name="script">Script.</param> 
        /// <param name="export">Export.</param> 
        public static void CreateDatabase() 
        { 
            NHibernate.Tool.hbm2ddl.SchemaExport se = new NHibernate.Tool.hbm2ddl.SchemaExport(Db.Configuration); 
            se.Create(true, true); 
        } 
    } 
} 

NHibernate.Helper Project

Overview

When using NHibernate in an ASP.NET application it is important to manage sessions correctly. Typically, a session-per-request pattern is used with a single session created and used for the lifetime of a request and then discarded. This helper project makes using NHibernate with ASP.NET easier by automating the creation of sessions and ensuring that they are closed after each request. It also provides some convenient methods to make coding simpler and more readable:

Automatically create the database schema:

Db.CreateDatabase();

Load an object from the database

Customer customer = (Customer)Db.Load(typeof(Customer), 123);

Save an object:

Db.Save(Customer);

Delete an object:

Db.Delete(Customer);

Access to the NHibernate Configuration and SessionFactory objects are provided if needed.

Configuration

NHibernate already has a comprehensive and flexible configuration system where settings can be defined in code, in the web.config file or in a separate XML file. Using the separate XML file enables the location of the mapping files to be configured as required. The configuration below defines the NHibernate connection properties and driver classes to use (these could also be defined in the web.config file) and the location of the nhibernate mapping files (in this case the assembly 'MyAssembly' which would contain embedded resources).

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.0" > 
    <session-factory name="chat"> 
        <!-- properties --> 
        <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> 
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> 
        <property name="connection.connection_string">Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI</property> 
        <property name="show_sql">false</property> 
        <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property> 
        <property name="use_outer_join">true</property> 
        <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> 
        <!-- mapping files --> 
        <mapping assembly="MyAssembly" /> 
    </session-factory> 
</hibernate-configuration>

Rather than simply use the default filename "nhibernate.cfg.xml" I prefer instead to use "nhibernate.config", mainly because using an xml file extension is a security risk as the config file could easily be downloaded whereas access to the .config extension is restricted by ASP.NET automatically. To provide some extra flexibility the name of the file is specified in the <appSetting> section with the key "nhibernate.config":

    <appSettings> 
        <add key="nhibernate.config" value="~/nhibernate.config" /> 
    </appSettings> 

Now, the only other thing that needs to be added to the web.config file is the entry for the HttpModule:

    <httpModules> 
        <add name="NHibernateModule" type="NHibernate.Helper.Module, NHibernate.Helper" /> 
    </httpModules> 

Here is the HttpModule itself. As you can see, it is extremly simple and simply closes the connection at the end of the request.

using System; 
using System.Web; 

namespace NHibernate.Helper 
{ 
    /// <summary> 
    ///        HttpModule to automatically close a session at the end of a request 
    /// </summary> 
    public sealed class Module : IHttpModule 
    { 
        public void Init(HttpApplication context) 
        { 
            context.EndRequest += new EventHandler(EndRequest); 
        } 

        public void Dispose() { } 
         
        public void EndRequest(Object sender, EventArgs e) 
        { 
            Db.CloseSession(); 
        } 
    } 
} 

The Db class contains all the helper methods and manages the creation and lifetime of the sessions (with the HttpModule above).

using System; 
using System.Web; 
using System.Configuration; 

using NHibernate; 
using NHibernate.Cfg; 

namespace NHibernate.Helper 
{ 
    /// <summary> 
    ///        Provides access to a single NHibernate session on a per request basis. 
    /// </summary> 
    /// <remarks> 
    ///        NHibernate requires mapping files to be loaded. These can be stored as 
    ///        embedded resources in the assemblies alongside the classes that they are for or 
    ///        in separate XML files. 
    ///        <br /><br /> 
    ///        As the number of assemblies containing mapping resources may change and 
    ///        these have to be referenced by the NHibernate config before the SessionFactory 
    ///        is created, the configuration is stored in a separate config file to allow 
    ///        new references to be added. This would also enable the use of external mapping 
    ///        files if required. 
    ///        <br /><br /> 
    ///        The name of the NHibernate configuration file is set in the appSettings section 
    ///        with the name "nhibernate.config". If not specified the the default value of 
    ///        ~/nhibernate.config is used. 
    ///        <br /><br /> 
    ///        Note that the default config name is not used because the .xml extension is 
    ///        public and could be downloaded from a website whereas access to .config files is 
    ///        automatically restricted by ASP.NET. 
    /// </remarks> 

    public sealed class Db 
    { 
        /// <summary> 
        /// Key used to identify NHibernate session in context items collection 
        /// </summary> 
        private const string sessionKey = "NHibernate.Db"; 

        /// <summary> 
        /// NHibernate Configuration 
        /// </summary> 
        private static readonly Configuration configuration = new Configuration(); 

        /// <summary> 
        /// NHibernate SessionFactory 
        /// </summary> 
        private static readonly ISessionFactory sessionFactory = configuration.Configure( HttpContext.Current.Request.MapPath(ConfigurationSettings.AppSettings["nhibernate.config"]) ).BuildSessionFactory(); 

        /// <summary> 
        /// NHibernate Session. This is only used for NUnit testing (ie. when HttpContext 
        /// is not available. 
        /// </summary> 
        private static readonly ISession session = sessionFactory.OpenSession(); 

        /// <summary> 
        /// None public constructor. Prevent direct creation of this object.  
        /// </summary> 
        private Db() { } 

        /// <summary> 
        /// See beforefieldinit 
        /// </summary> 
        static Db() { } 

        /// <summary> 
        /// Creates a new NHibernate Session object if one does not already exist. 
        /// When running in the context of a web application the session object is 
        /// stored in HttpContext items and has 'per request' lifetime. For client apps 
        /// and testing with NUnit a normal singleton is used. 
        /// </summary> 
        /// <returns>NHibernate Session object.</returns> 
        [CLSCompliant(false)] 
        public static ISession Session 
        { 
            get  
            {  
                ISession session; 
                if (HttpContext.Current == null) 
                { 
                    session = Db.session; 
                } 
                else 
                { 
                    if (HttpContext.Current.Items.Contains(sessionKey)) 
                    { 
                        session = (ISession)HttpContext.Current.Items[sessionKey]; 
                    } 
                    else 
                    { 
                        session = Db.sessionFactory.OpenSession(); 
                        HttpContext.Current.Items[sessionKey] = session; 
                    } 
                } 
                return session;  
            }                 
        } 

        /// <summary> 
        /// Closes any open NHibernate session if one has been used in this request.<br /> 
        /// This is called from the EndRequest event. 
        /// </summary> 
        [CLSCompliant(false)] 
        public static void CloseSession() 
        { 
            if (HttpContext.Current == null) 
            { 
                Db.session.Close(); 
            } 
            else 
            { 
                if (HttpContext.Current.Items.Contains(sessionKey)) 
                { 
                    ISession session = (ISession)HttpContext.Current.Items[sessionKey]; 
                    session.Close(); 
                    HttpContext.Current.Items.Remove(sessionKey); 
                } 
            } 
             
        } 

        /// <summary> 
        /// Returns the NHibernate Configuration object. 
        /// </summary> 
        /// <returns>NHibernate Configuration object.</returns> 
        [CLSCompliant(false)] 
        public static Configuration Configuration 
        { 
            get { return Db.configuration; } 
        } 

        /// <summary> 
        /// Returns the NHibernate SessionFactory object. 
        /// </summary> 
        /// <returns>NHibernate SessionFactory object.</returns> 
        [CLSCompliant(false)] 
        public static ISessionFactory SessionFactory 
        { 
            get { return Db.sessionFactory; } 
        } 

        /// <summary> 
        /// Loads the specified object. 
        /// </summary> 
        /// <param name="type">Type.</param> 
        /// <param name="id">Id.</param> 
        public static void Load(System.Type type, object id) 
        { 
            Db.Session.Load(type, id); 
        } 

        /// <summary> 
        /// Gets the specified object. 
        /// </summary> 
        /// <param name="type">Type.</param> 
        /// <param name="id">Id.</param> 
        public static object Get(System.Type type, object id) 
        { 
            return Db.Session.Get(type, id); 
        } 

        /// <summary> 
        /// Save object item using NHibernate. 
        /// </summary> 
        /// <param name="item">Object to save</param> 
        public static void Save(object item) 
        { 
            ITransaction transaction = Db.Session.BeginTransaction(); 

            try 
            { 
                Db.Session.Save(item); 
                transaction.Commit(); 
            } 
            catch (Exception ex) 
            { 
                transaction.Rollback(); 
                throw; 
            } 
        } 

        /// <summary> 
        /// Save object item using NHibernate. 
        /// </summary> 
        /// <param name="item">Object to delete</param> 
        public static void Delete(object item) 
        { 
            ITransaction transaction = Db.Session.BeginTransaction(); 

            try 
            { 
                Db.Session.Delete(item); 
                transaction.Commit(); 
            } 
            catch (Exception ex) 
            { 
                transaction.Rollback(); 
                throw; 
            } 
        } 

        /// <summary> 
        /// Creates the specified database. 
        /// </summary> 
        /// <param name="script">Script.</param> 
        /// <param name="export">Export.</param> 
        public static void CreateDatabase() 
        { 
            NHibernate.Tool.hbm2ddl.SchemaExport se = new NHibernate.Tool.hbm2ddl.SchemaExport(Db.Configuration); 
            se.Create(true, true); 
        } 
    } 
} 
内容概要:本文介绍了基于噪声抑制半监督学习的锂离子电池SOH(State of Health,健康状态)估计方法的Python代码实现。该方法融合半监督学习框架与先进的噪声抑制机制,旨在利用少量标注样本和大量未标注数据,有效提升电池健康状态预测的精度与模型鲁棒性,特别适用于实际工程中电池老化数据标注成本高、样本稀缺的挑战性场景。通过设计高效的特征提取网络与可靠的伪标签生成及优化策略,模型能够有效识别并抑制训练过程中的噪声干扰,增强在复杂工况和数据波动下的泛化能力与稳定性。; 适合人群:具备一定机器学习理论基础和Python编程能力,从事电池管理系统(BMS)、新能源汽车、储能系统等领域的科研人员、工程师,以及专注于电池寿命预测、设备状态监测与智能运维等方向的硕博研究生;; 使用场景及目标:①解决锂离子电池SOH估计中标注数据获取困难、成本高昂的核心痛点;②提升模型在存在测量误差、传感器漂移或异常数据等噪声环境下的预测准确性与可靠性;③为相关科研课题提供可复现、可扩展的算法基准与开源代码框架,加速算法迭代与工程落地; 阅读建议:此资源以Python代码为核心载体,强调算法的完整复现与实验验证过程,建议读者结合代码逐模块剖析模型架构、损失函数设计与训练流程细节,并积极在自有电池数据集上进行迁移学习、参数调优与性能对比,以深入掌握半监督学习与噪声抑制技术在电池退化建模中的关键应用。
内容概要:本文系统阐述了高速串行信号在传输过程中因信道损耗导致的眼图闭合问题,并介绍了主流的均衡技术解决方案。信道作为低通滤波器,会显著衰减高频分量,造成码间干扰(ISI),尤其在速率高于1GHz时更为严重。为恢复信号质量,发送端采用FFE(前馈均衡器)实施预加重或去加重,提前补偿高频损耗;接收端则结合CTLE与DFE进行二次均衡:CTLE通过模拟高通滤波器“削峰填谷”提升高频响应,而DFE利用反馈机制消除后向码间干扰,提高判决准确性。文章详细解析了各均衡模块的工作原理、电路结构、关键参数及其频率响应特性,并通过PCIe 3.0实例展示均衡前后眼图的改善效果,最后对比了不同技术的适用场景与优缺点。; 适合人群:从事高速电路设计、信号完整性分析等相关领域的工程师和技术人员,以及具备一定通信原理和电子工程基础的研发人员; 使用场景及目标:①理解高速信号传输中的损耗机理与眼图退化成因;②掌握FFE、CTLE、DFE等均衡技术的设计原理与应用场景;③为高速接口(如PCIe、USB等)的信号完整性优化提供理论支持与实践指导; 阅读建议:建议结合仿真工具观察不同均衡参数对眼图的影响,深入理解抽头系数、零极点配置等关键参数的调节逻辑,并关注实际硬件实现中的功耗与噪声权衡问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值