private static void BuildSessionFactory(NHibernate.Cfg.Configuration cfg) { try { // Use NHibernate.Mapping.Attributes to create information about our entities System.IO.MemoryStream stream = new System.IO.MemoryStream(); // Where the information will be written in NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Enable validation (optional) // Ask to NHibernate to use fields instead of properties NHibernate.Mapping.Attributes.HbmSerializer.Default.HbmDefaultAccess = "field.camelcase-underscore"; // Gather information from this assembly (can also be done class by class) //System.Console.Out.WriteLine("NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize()...\n"); NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(stream, System.Reflection.Assembly.GetExecutingAssembly()); stream.Position = 0; // StreamReader sr = new StreamReader(stream); // string IbDoc = sr.ReadToEnd(); cfg.AddInputStream(stream); // Send the Mapping information to NHibernate Configuration stream.Close(); // Create table(s) in the database for our entities // System.Console.Out.WriteLine("new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Create()..."); // Build the SessionFactory // System.Console.Out.WriteLine("\n\nsessionFact = cfg.BuildSessionFactory();\n\n"); SessionFactory = cfg.BuildSessionFactory(); } catch (Exception e) { throw new Exception("An error occurred while building the NHibernate Session Factory used for internal data storage." + Environment.NewLine + "Error CNF-370 in " + PROJ_FILE_NAME + ".BuildSessionFactory(): " + e.Message); } }
public static void ConfigureMappingsAndEventListeners(NHibernate.Cfg.Configuration config, string[] annotatedMappingAssemblies) { foreach (String assembly in annotatedMappingAssemblies) { MemoryStream stream = new MemoryStream(); NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(stream, Assembly.Load(assembly)); stream.Position = 0; StreamReader reader = new StreamReader(stream); String st = reader.ReadToEnd(); Console.Write(st); stream.Position = 0; config.AddInputStream(stream); } config.Properties["show_sql"] = "True"; config.Properties["hbm2ddl.keywords"] = "none"; config.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { new UpdateEventListener() }; config.EventListeners.DeleteEventListeners = new IDeleteEventListener[] { new DeleteEventListener() }; config.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new InsertEventListener() }; }
/// <summary> /// 创建 SessionFactory /// </summary> public static void CreateSessionFactory(string cfgFile) { NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(cfgFile); // where the xml will be written using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { // Enable validation (optional) NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Here, we serialize all decorated classes (but you can also do it class by class) NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(stream, Assembly.GetAssembly(typeof(Model.D_User_Model))); // Rewind stream.Position = 0; try { System.IO.File.WriteAllBytes(cfgFile.Substring(0, cfgFile.LastIndexOf("\\") + 1) + "Mapping.cfg.xml", stream.GetBuffer()); } catch (System.UnauthorizedAccessException) { } finally { cfg.AddInputStream(stream); // Use the stream here } } m_SessionFactory = cfg.BuildSessionFactory(); //m_SessionFactory = new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory(); }
/// <summary> /// 读入Attribute到内存 /// </summary> /// <param name="cfg"></param> /// <param name="assembly">要读入的AssemblyName</param> public static void MemorizeMappingAttribute(NHibernate.Cfg.Configuration cfg, Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } System.IO.MemoryStream stream = new System.IO.MemoryStream(); HbmSerializer.Default.Validate = true; HbmSerializer.Default.HbmAssembly = assembly.GetName().Name; HbmSerializer.Default.HbmNamespace = assembly.GetTypes()[0].Namespace; // Here, we serialize all decorated classes (but you can also do it class by class) HbmSerializer.Default.Serialize(stream, assembly); // System.Reflection.Assembly.GetExecutingAssembly() stream.Position = 0; // Rewind //using (System.IO.FileStream sw = new FileStream("c:\\test.xml", FileMode.Create)) //{ // stream.WriteTo(sw); //} cfg.AddInputStream(stream); // Use the stream here stream.Dispose(); }
protected override void PostProcessConfiguration(NHibernate.Cfg.Configuration config) { var stream = new MemoryStream(); HbmSerializer.Default.Validate = true; foreach (var name in MappingAssemblyNames) { var asm = Assembly.Load(name); HbmSerializer.Default.Serialize(stream, asm); stream.Position = 0; config.AddInputStream(stream); } stream.Close(); }
/// <summary> /// 创建 SessionFactory /// </summary> public static void CreateReadonlySessionFactory(string cfgFile) { NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(cfgFile); // where the xml will be written using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { // Enable validation (optional) NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Here, we serialize all decorated classes (but you can also do it class by class) NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(stream, Assembly.GetAssembly(typeof(Model.D_User_Model))); // Rewind stream.Position = 0; // Use the stream here cfg.AddInputStream(stream); } m_ReadonlySessionFactory = cfg.BuildSessionFactory(); }
private static ISessionFactory BuildSessionFactory(string factoryCfg) { MemoryStream stream = new MemoryStream(); // where the xml will be written HbmSerializer.Default.Validate = true; // Enable validation (optional) // Set any specific values for the <hibernate-mapping> element here // Set the 'default-access' attribute // This matches our naming convention for member fields HbmSerializer.Default.HbmDefaultAccess = "field.camelcase-underscore"; // Set the 'auto-import' attribute off // This forces NHibernate to use fully qualified class names (i.e. full namespace prefixes) HbmSerializer.Default.HbmAutoImport = false; // Here, we serialize all decorated classes GetNhibernateClasses(stream); stream.Position = 0; // Rewind // TODO: Implement a better method (i.e. configurable) of getting the resulting file out #if DEBUG try { stream.WriteTo(new FileStream(@"ProjectTracker.hbm.xml", FileMode.Create)); } catch (UnauthorizedAccessException e) { //user trying to access the path is probably coming from IIS and it does not have permission to create the file //to catch it and carry on e.ToString(); //prevent r# warning } #endif Configuration configuration = new Configuration();; configuration.Configure(factoryCfg); configuration.AddInputStream(stream); // Use the stream here stream.Close(); // Now use the configuration to build the Session Factory return(configuration.BuildSessionFactory()); }
private bool AddedMappingFromHbmResource(ItemDefinition definition, NHibernate.Cfg.Configuration cfg) { if (!TryLocatingHbmResources) { return(false); } Stream hbmXmlStream = definition.ItemType.Assembly.GetManifestResourceStream(definition.ItemType.FullName + ".hbm.xml"); if (hbmXmlStream == null) { return(false); } using (hbmXmlStream) { cfg.AddInputStream(hbmXmlStream); return(true); } }
/// <summary> /// If <paramref name="targetAssembly"/> has a reference on /// <c>NHibernate.Mapping.Attributes</c> : use the NHibernate mapping /// attributes contained in that assembly to update NHibernate /// configuration (<paramref name="cfg"/>). Else do nothing /// </summary> /// <remarks> /// To avoid an unnecessary dependency on the library /// <c>NHibernate.Mapping.Attributes.dll</c> when using this /// facility without NHibernate mapping attributes, all calls to that /// library are made using reflexion. /// </remarks> /// <param name="cfg">NHibernate configuration</param> /// <param name="targetAssembly">Target assembly name</param> protected void GenerateMappingFromAttributesIfNeeded(Configuration cfg, String targetAssembly) { //Get an array of all assemblies referenced by targetAssembly AssemblyName[] refAssemblies = Assembly.Load(targetAssembly).GetReferencedAssemblies(); //If assembly "NHibernate.Mapping.Attributes" is referenced in targetAssembly if (Array.Exists(refAssemblies,delegate(AssemblyName an) { return an.Name.Equals(NHMappingAttributesAssemblyName); })) { //Obtains, by reflexion, the necessary tools to generate NH mapping from attributes Type HbmSerializerType = Type.GetType(String.Concat(NHMappingAttributesAssemblyName, ".HbmSerializer, ", NHMappingAttributesAssemblyName)); Object hbmSerializer = Activator.CreateInstance(HbmSerializerType); PropertyInfo validate = HbmSerializerType.GetProperty("Validate"); MethodInfo serialize = HbmSerializerType.GetMethod("Serialize", new[] {typeof (Assembly)}); //Enable validation of mapping documents generated from the mapping attributes validate.SetValue(hbmSerializer, true, null); //Generates a stream of mapping documents from all decorated classes in targetAssembly and add it to NH config cfg.AddInputStream((MemoryStream) serialize.Invoke(hbmSerializer, new object[] {Assembly.Load(targetAssembly)})); } }
/// <summary> Configures NHibernate to access the data source and map entities to tables. </summary> public Persister() { System.Console.Out.WriteLine("Configuration of NHibernate...\n"); const string connectionString = @"Data Source=(local)\sqlexpress;Initial Catalog=nhibernate;Integrated Security=SSPI"; // Enable the logging of NHibernate operations log4net.Config.XmlConfigurator.Configure(); // Create the object that will hold the configuration settings // and fill it with the information to access to the database NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration(); configuration.Properties[NHibernate.Cfg.Environment.ConnectionProvider] = "NHibernate.Connection.DriverConnectionProvider"; System.Console.Out.WriteLine("Use SQL Server database: ConnectionString = <" + connectionString + ">\n"); // These are the three lines of code to change in order to use another database configuration.Properties[NHibernate.Cfg.Environment.Dialect] = "NHibernate.Dialect.MsSql2000Dialect"; configuration.Properties[NHibernate.Cfg.Environment.ConnectionDriver] = "NHibernate.Driver.SqlClientDriver"; configuration.Properties[NHibernate.Cfg.Environment.ConnectionString] = connectionString; // Use NHibernate.Mapping.Attributes to create mapping information about our entities System.Console.Out.WriteLine("Generating the mapping information for NHibernate...\n"); NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Enable validation (optional) using (System.IO.MemoryStream stream = NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(System.Reflection.Assembly.GetExecutingAssembly())) { configuration.AddInputStream(stream); // Send the mapping information to NHibernate configuration } // Create the table in the database for the entity Message System.Console.Out.WriteLine("Creating the table in the database for the entity Message..."); new NHibernate.Tool.hbm2ddl.SchemaExport(configuration).Create(true, true); // Build the SessionFactory System.Console.Out.WriteLine("\n\nBuilding the session factory, end of the configuration\n\n"); _sessionFactory = configuration.BuildSessionFactory(); }
public static void MyClassInitialize(TestContext testContext) { // define mapping schema HbmSerializer.Default.HbmAssembly = typeof(Product).Assembly.GetName().FullName; //HbmSerializer.Default.HbmNamespace = typeof( Product ).Namespace; HbmSerializer.Default.HbmAutoImport = true; HbmSerializer.Default.Validate = true; HbmSerializer.Default.WriteDateComment = false; HbmSerializer.Default.HbmDefaultAccess = "field"; //HbmSerializer.Default.Serialize(typeof(Product).Assembly, "output.hbm.xml"); // serialize mapping xml into file to spectate it // create configuration and load assembly NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration(); //cfg.Properties[NHibernate.Cfg.Environment.CollectionTypeFactoryClass] = typeof(Net4CollectionTypeFactory).AssemblyQualifiedName; cfg.Configure(); //cfg.AddAssembly( typeof( Product ).Assembly ); // use this only, if hbm.xml exists in the assembly cfg.AddInputStream(HbmSerializer.Default.Serialize(typeof(Product).Assembly)); // ez bármikor müxik, de lassabb try { SchemaValidator schemaValidator = new SchemaValidator(cfg); schemaValidator.Validate(); // validate the database schema } catch (Exception) { SchemaUpdate schemaUpdater = new SchemaUpdate(cfg); // try to update schema schemaUpdater.Execute(false, true); if (schemaUpdater.Exceptions.Count > 0) { throw new Exception("FAILED TO UPDATE SCHEMA"); } } //SchemaExport export = new SchemaExport(cfg); //export.Execute( false, true, false ); //new SchemaExport( cfg ).Execute( false, true, false ); mSessionFactory = cfg.BuildSessionFactory(); }
private static void AddInputStreamsForAssembly(NHibernate.Cfg.Configuration _configuration, Assembly asm) { Type[] types = GetTypesWithClassAttribute(asm); foreach (Type t in types) { HbmSerializer.Default.HbmAssembly = asm.GetName().Name; HbmSerializer.Default.HbmNamespace = t.Namespace; // Use NHibernate.Mapping.Attributes to create information about our entities HbmSerializer.Default.Validate = true; // Enable validation (optional) System.IO.MemoryStream stream = new System.IO.MemoryStream(); Console.WriteLine(t.Name); HbmSerializer.Default.Serialize(stream, t); stream.Position = 0; Console.WriteLine((new StreamReader(stream)).ReadToEnd()); Console.WriteLine(); stream.Position = 0; //DumpHbmXmlStreamToFile(stream, Path.Combine(appPath, hbmXmlDumpFile)); //stream.Position = 0; _configuration.AddInputStream(stream); stream.Close(); } }
private static ISessionFactory BuildSessionFactory(string factoryCfg) { MemoryStream stream = new MemoryStream(); // where the xml will be written HbmSerializer.Default.Validate = true; // Enable validation (optional) // Set any specific values for the <hibernate-mapping> element here // Set the 'default-access' attribute // This matches our naming convention for member fields HbmSerializer.Default.HbmDefaultAccess = "field.camelcase-underscore"; // Set the 'auto-import' attribute off // This forces NHibernate to use fully qualified class names (i.e. full namespace prefixes) HbmSerializer.Default.HbmAutoImport = false; // Here, we serialize all decorated classes GetNhibernateClasses(stream); stream.Position = 0; // Rewind // TODO: Implement a better method (i.e. configurable) of getting the resulting file out #if DEBUG try { stream.WriteTo(new FileStream(@"ProjectTracker.hbm.xml", FileMode.Create)); } catch (UnauthorizedAccessException e) { //user trying to access the path is probably coming from IIS and it does not have permission to create the file //to catch it and carry on e.ToString(); //prevent r# warning } #endif Configuration configuration = new Configuration();; configuration.Configure(factoryCfg); configuration.AddInputStream(stream); // Use the stream here stream.Close(); // Now use the configuration to build the Session Factory return configuration.BuildSessionFactory(); }
private static ISessionFactory CreateEntityManagerFactory(SchemaFactoryModeEnum mode, CategoryPropertyItem configItem) { CategoryPropertyItem item = ConfigurationAccessHelper.GetCategoryPropertyByPath(configItem.PropertyItems, "DatabaseManager"); if (item != null && !string.IsNullOrEmpty(item.EntryValue)) { Type databaseManagerType = null; try { databaseManagerType = TypeHelper.GetTypeFromString(item.EntryValue); } catch (Exception ex) { throw new InvalidConfigurationValueException(ex.Message, ex); } if (databaseManagerType != null) { using (IDatabaseManager manager = (IDatabaseManager)databaseManagerType.GetConstructor(Type.EmptyTypes).Invoke(null)) { manager.Initialize(item); Dictionary <string, string> settings = new Dictionary <string, string>(); foreach (CategoryPropertyItem pi in ConfigurationAccessHelper.GetCategoryPropertyByPath(configItem.PropertyItems, "NHibernateSettings")) { settings[pi.Id] = pi.EntryValue; } manager.EnsureDatabaseIntegrity(SYSTEM_ID, settings, mode); } } } string hbm2ddl = "hbm2ddl.auto"; NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration(); cfg.Properties.Clear(); foreach (CategoryPropertyItem pi in ConfigurationAccessHelper.GetCategoryPropertyByPath(configItem.PropertyItems, "NHibernateSettings")) { if (!hbm2ddl.Equals(pi.Id.ToLower())) { cfg.Properties[pi.Id] = pi.EntryValue; } } if (mode == SchemaFactoryModeEnum.Create) { cfg.Properties[hbm2ddl] = "create"; } else if (mode == SchemaFactoryModeEnum.Create_And_Drop) { cfg.Properties[hbm2ddl] = "create-drop"; } HbmSerializer serializer = new HbmSerializer(); serializer.HbmAssembly = typeof(PersistentStorageItem).Assembly.GetName().FullName; serializer.HbmAutoImport = true; serializer.Validate = true; serializer.WriteDateComment = false; serializer.HbmDefaultAccess = "field"; cfg.AddInputStream(serializer.Serialize(typeof(PersistentStorageItem).Assembly)); //cfg.Configure(); if (mode == SchemaFactoryModeEnum.Validate) { SchemaValidator schemaValidator = new SchemaValidator(cfg); schemaValidator.Validate(); // validate the database schema } else if (mode == SchemaFactoryModeEnum.Update) { SchemaUpdate schemaUpdater = new SchemaUpdate(cfg); // try to update schema schemaUpdater.Execute(false, true); if (schemaUpdater.Exceptions.Count > 0) { throw new Exception("FAILED TO UPDATE SCHEMA"); } } return(cfg.BuildSessionFactory()); }
private SessionManager() { var configuration = new NHibernate.Cfg.Configuration(); configuration.AddAssembly(Assembly.GetCallingAssembly()); IDictionary <string, string> properties = new Dictionary <string, string>(); properties[NHibernate.Cfg.Environment.ConnectionString] = ApplicationConfiguration.DBConnectionString(ApplicationConfiguration.DBType.Swdb); properties.Add(NHibernate.Cfg.Environment.ConnectionDriver, HibernateUtil.HibernateDriverName(ApplicationConfiguration.DBType.Swdb)); properties.Add(NHibernate.Cfg.Environment.Dialect, HibernateUtil.HibernateDialect(ApplicationConfiguration.DBType.Swdb)); properties.Add(NHibernate.Cfg.Environment.ShowSql, "false"); properties.Add(NHibernate.Cfg.Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider"); properties.Add(NHibernate.Cfg.Environment.ProxyFactoryFactoryClass, "NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate"); properties.Add(NHibernate.Cfg.Environment.CurrentSessionContextClass, "managed_web"); configuration.SetProperties(properties); //TODO: make this modular configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(User))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(Role))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(RoleGroup))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(DataConstraint))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(UserProfile))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(UserCustomConstraint))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(UserCustomRole))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(Category))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(PropertyDefinition))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(PropertyValue))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(Condition))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(WhereClauseCondition))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(PersonGroup))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(PersonGroupAssociation))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(AuditTrail))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(ISMAuditTrail))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(ExtraAttributes))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(HistWorkorder))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(HistTicket))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(R0042AssetHistory))); configuration.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(typeof(CiSpecMapping))); _sessionFactory = configuration.BuildSessionFactory(); }