Skip to content

Instantly share code, notes, and snippets.

@Azerothian
Forked from anonymous/gist:807190
Created February 2, 2011 03:52
Show Gist options
  • Save Azerothian/807212 to your computer and use it in GitHub Desktop.
Save Azerothian/807212 to your computer and use it in GitHub Desktop.
using System;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Mapping.Attributes;
using NHibernate.Cfg;
using NHibernate;
using log4net;
using System.Reflection;
using System.Web;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
namespace normist.data
{
/// <summary>
/// nHibernate Manager for mapping classes to Tables
/// </summary>
public class Manager
{
private static Manager _context = null;
public static Manager Context
{
get
{
return _context ?? (_context = new Manager());
}
}
// Data Management Logger
private static readonly ILog log = log4net.LogManager.GetLogger(typeof(Manager));
public bool IsInitialised = false;
public bool RenderHBM = false;
public string HBMOutput = @".\nbm";
readonly Configuration _config = null;
ISessionFactory _sessionFactory = null;
ISession _currentSession = null;
const string VarSession = "nhsession";
public ISession CurrentSession
{
get
{
if (HttpContext.Current == null)
{
if (_currentSession != null)
{
return _currentSession;
}
_currentSession = OpenSession();
return _currentSession;
}
var currentContext = HttpContext.Current;
var session = currentContext.Items[VarSession] as ISession;
if (session == null)
{
session = OpenSession();
currentContext.Items[VarSession] = session;
}
return session;
}
}
/// <summary>
/// Reset the HTTP Session if this is a WebAPP
/// </summary>
public void ResetSession()
{
var currentContext = HttpContext.Current;
var session = currentContext.Items[VarSession] as ISession;
session = OpenSession();
currentContext.Items[VarSession] = session;
}
/// <summary>
/// Make the new nHibernate Manager Object
/// </summary>
public Manager()
{
// Setup Logging
log4net.Appender.FileAppender appender = new log4net.Appender.FileAppender();
appender.File = @".\logs\data-manager.log";
appender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
appender.ImmediateFlush = true;
// Logging Pattern & Layout
string pattern = "%timestamp, %thread, %level, %logger, %ndc,%message %newline";
log4net.Layout.PatternLayout pl = new log4net.Layout.PatternLayout(pattern);
appender.Layout = pl;
appender.ActivateOptions();
appender.Threshold = log4net.Core.Level.Verbose;
log4net.Config.BasicConfigurator.Configure(appender);
// Setup nHibernate Configuration
_config = new Configuration();
_config.Configure(@".\config\hibernate.cfg.xml");
if (_config == null)
{
throw new InvalidOperationException("NHibernate configuration is null.");
}
}
/// <summary>
/// Load in Table Mapping Scripts from the Data Directory
/// </summary>
public void LoadMappings()
{
// Setup Code Header and Footers
string CodeHeader;
string CodeFooter;
string CodeBody;
string Code;
CodeHeader = @" using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Text;
using normist.data.Abstraction;
using NHibernate.Mapping.Attributes;
namespace normist.data.Tables
{
";
CodeFooter = @"
}";
//Load in Code Objects
TextReader tr = new StreamReader(@".\Data\Stock.cs");
CodeBody = tr.ReadToEnd();
tr.Close();
// Merge all together
Code = CodeHeader + CodeBody + CodeFooter;
// Setup Compiler Objects and Parameters
ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters loParameters = new CompilerParameters();
loParameters.CompilerOptions = "/target:library /optimize";
loParameters.GenerateExecutable = false;
loParameters.OutputAssembly = "normist.data.Tables.dll";
loParameters.GenerateInMemory = true;
loParameters.ReferencedAssemblies.Add("System.dll");
loParameters.ReferencedAssemblies.Add("System.Data.Linq.dll");
loParameters.ReferencedAssemblies.Add("normist.data.dll");
loParameters.ReferencedAssemblies.Add("NHibernate.Mapping.Attributes.dll");
log.Info("Data Map Compile Options :- " + loParameters.CompilerOptions);
// Compile the Code into an in Memory Assembly
CompilerResults loCompiled = loCompiler.CompileAssemblyFromSource(loParameters, Code);
// Spit back errors
if (loCompiled.Errors.HasErrors)
{
log.Error("Data Map Compiler Error Encounted " + loCompiled.Errors.Count.ToString());
for (int x = 0; x < loCompiled.Errors.Count; x++)
{
log.Error("Error " + x + " Line: " + loCompiled.Errors[x].Line.ToString() + " - " + loCompiled.Errors[x].ErrorText);
}
}
// Load up the Assembly
Assembly dataMapAssembly = loCompiled.CompiledAssembly;
}
private ISessionFactory SessionFactory
{
get
{
if (_config == null)
{
throw new InvalidOperationException("NHibernate configuration is null.");
}
if (_sessionFactory == null)
{
_sessionFactory = _config.BuildSessionFactory();
}
if (_sessionFactory == null)
{
throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
}
return _sessionFactory;
}
}
public ISession OpenSession()
{
ISession session = SessionFactory.OpenSession();
if (session == null)
{
throw new InvalidOperationException("Call to SessionFactory.OpenSession() returned null.");
}
return session;
}
public void RegisterAssembly(Assembly asm)
{
if (IsInitialised)
return;
HbmSerializer.Default.Validate = true; // Enable validation (optional)
if (RenderHBM)
HbmSerializer.Default.Serialize(HBMOutput, asm);
_config.AddInputStream(HbmSerializer.Default.Serialize(asm));
BuildSessionFactory();
IsInitialised = true;
}
public void RegisterAssembly(Assembly[] asm)
{
if (IsInitialised)
return;
HbmSerializer.Default.Validate = true; // Enable validation (optional)
foreach (var assembly in asm)
{
if (RenderHBM)
HbmSerializer.Default.Serialize(HBMOutput, assembly);
_config.AddInputStream(HbmSerializer.Default.Serialize(assembly));
}
BuildSessionFactory();
IsInitialised = true;
}
public void BuildSessionFactory()
{
//if (UpdateDatabase)
UpdateDbSchema();
//ExportDbSchema();
_sessionFactory = _config.BuildSessionFactory();
}
public void UpdateDbSchema()
{
var update = new SchemaUpdate(_config);
update.Execute(true, true);
}
public void ExportDbSchema()
{
var export = new SchemaExport(_config);
export.Execute(true, true, true);
}
public static bool UpdateDatabase
{
get
{
bool result = false;
var config = System.Configuration.ConfigurationManager.AppSettings["UpdateDatabase"];
if (config != null)
{
bool.TryParse(config, out result);
}
return result;
}
}
}
//using (ITransaction tx = session.BeginTransaction())
// {
// user = (from v in session.Query<User>()
// where v.Username.ToLower() == username.ToLower() &&
// v.Password.ToLower() == password.ToLower()
// select v).FirstOrDefault();
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment