protected virtual void ConfigureNHibernate()
        {
            var configuration = new Configuration()
                .SetProperties(new Dictionary<string, string>
                {
                    {Environment.Dialect, typeof (MsSql2005Dialect).AssemblyQualifiedName},
                    {Environment.ProxyFactoryFactoryClass, typeof (ProxyFactoryFactory).AssemblyQualifiedName},
                    {Environment.ConnectionString, RootContext.GetConnectionStringFor(TenantId)},
                });
            var customMapping = GetMappingFrom(Assembly);
            var added = new HashSet<string>();
            foreach (var mapping in customMapping)
            {
                configuration.AddResource(mapping, Assembly);
                added.Add(GetEntityName(mapping));
            } 
            var coreMapping = GetMappingFrom(typeof(AbstractBootStrapper).Assembly);
            foreach (var mapping in coreMapping)
            {
                if (added.Add(GetEntityName(mapping)) == false)
                    continue;//already there
                configuration.AddResource(mapping, typeof (AbstractBootStrapper).Assembly);
            }

            container.Kernel.AddComponentInstance<Configuration>(configuration);

            ISessionFactory sessionFactory = configuration.BuildSessionFactory();
            container.Kernel.AddComponentInstance<ISessionFactory>(sessionFactory);
        }
Example #2
0
        public static void Connect()
        {
            ServerConsole.WriteLine("Database connecting...", MessageLevel.ODBC);

            //create config
            ServerConsole.WriteLine("Connecting to KalAuth...", MessageLevel.ODBC);
            Configuration cfg = new Configuration().Configure("kalauth.cfg.xml");

            //load resources
            ServerConsole.WriteLine("Loading resources", MessageLevel.ODBC);
            cfg.AddResource(@"KalSharp.Account.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());

            //building config
            KalAuth = cfg.BuildSessionFactory();
            ServerConsole.WriteLine("Connected to KalAuth", MessageLevel.ODBC);

            //create config
            ServerConsole.WriteLine("Connecting to KalDB...", MessageLevel.ODBC);
            Configuration cfg2 = new Configuration().Configure("kaldb.cfg.xml");

            //load resources
            ServerConsole.WriteLine("Loading resources", MessageLevel.ODBC);
            cfg2.AddResource(@"KalSharp.Player.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());
            cfg2.AddResource(@"KalSharp.PlayerDeleted.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());
            cfg2.AddResource(@"KalSharp.Worlds.Items.Item.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());

            //building config
            KalDB = cfg2.BuildSessionFactory();
            ServerConsole.WriteLine("Connected to KalDB", MessageLevel.ODBC);
        }
		public virtual void SetUp()
		{
			Configuration cfg = new Configuration();
			Assembly dm = Assembly.GetAssembly(typeof(Simple));
			cfg.AddResource("NHibernate.DomainModel.Simple.hbm.xml", dm);
			cfg.AddResource("NHibernate.DomainModel.NHSpecific.SimpleComponent.hbm.xml", dm);
			cfg.AddResource("NHibernate.DomainModel.Multi.hbm.xml", dm);

			factory = cfg.BuildSessionFactory();
			factoryImpl = (ISessionFactoryImplementor) factory;
			dialect = factoryImpl.Dialect;
		}
Example #4
0
		public void WrongPropertyNameForCamelcaseShouldThrow()
		{
			//default-access="field.camelcase" on property
			var cfg = new Configuration();
			Assert.Throws<MappingException>(() =>
				cfg.AddResource(ns + "DogMapping.hbm.xml", Assembly.GetExecutingAssembly()));
		}
Example #5
0
		public void SupportTypedefInReturnScalarElements()
		{
			var cfg = new Configuration();
			Assembly assembly = Assembly.GetExecutingAssembly();
			cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1605.Mappings.hbm.xml", assembly);
			using (cfg.BuildSessionFactory()) {}
		}
		public void MisspelledPropertyName() 
		{
			bool excCaught = false;

			// add a resource that has a bad mapping
			string resource = "NHibernate.Test.MappingExceptions.A.PropertyNotFound.hbm.xml";
			Configuration cfg = new Configuration();
			try 
			{
				cfg.AddResource( resource, this.GetType().Assembly );
				cfg.BuildSessionFactory();
			}
			catch( MappingException me ) 
			{
				//"Problem trying to set property type by reflection"
				// "Could not find a getter for property 'Naame' in class 'NHibernate.Test.MappingExceptions.A'"
				Assert.IsTrue( me.InnerException is MappingException );
				Assert.IsTrue( me.InnerException.InnerException is PropertyNotFoundException );

				Exception inner = me.InnerException.InnerException;
				Assert.IsTrue( inner.Message.IndexOf( "Naame" ) > 0, "should contain name of missing property 'Naame' in exception" );
				Assert.IsTrue( inner.Message.IndexOf( "NHibernate.Test.MappingExceptions.A" ) > 0, "should contain name of class that is missing the property" );
				excCaught = true;
			}

			Assert.IsTrue( excCaught, "Should have caught the MappingException that contains the property not found exception." );
		}
		public void MisspelledPropertyName()
		{
			bool excCaught = false;

			// add a resource that has a bad mapping
			string resource = "NHibernate.Test.MappingExceptions.A.PropertyNotFound.hbm.xml";
			Configuration cfg = new Configuration();
			try
			{
				cfg.AddResource(resource, GetType().Assembly);
				cfg.BuildSessionFactory();
			}
			catch (MappingException me)
			{
				PropertyNotFoundException found = null;
				Exception find = me;
				while (find != null)
				{
					found = find as PropertyNotFoundException;
					find = find.InnerException;
				}
				Assert.IsNotNull(found, "The PropertyNotFoundException is not present in the Exception tree.");
				Assert.AreEqual("Naame", found.PropertyName, "should contain name of missing property 'Naame' in exception");
				Assert.AreEqual(typeof(A), found.TargetType, "should contain name of class that is missing the property");
				excCaught = true;
			}

			Assert.IsTrue(excCaught, "Should have caught the MappingException that contains the property not found exception.");
		}
		public void MissingSuper()
		{
			Configuration cfg = new Configuration();

			try
			{
				cfg.AddResource(BaseForMappings + "Extendshbm.Customer.hbm.xml", typeof (ExtendsFixture).Assembly);
				Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Null, "cannot be in the configuration yet!");
				cfg.AddResource(BaseForMappings + "Extendshbm.Employee.hbm.xml", typeof (ExtendsFixture).Assembly);

				cfg.BuildSessionFactory();

				Assert.Fail("Should not be able to build sessionfactory without a Person");
			}
			catch (HibernateException) {}
		}
Example #9
0
		public void IncrementGeneratorShouldIncludeClassLevelSchemaWhenGettingNextId()
		{
			System.Type thisType = GetType();
			Assembly thisAssembly = thisType.Assembly;

			Configuration cfg = new Configuration();
			cfg.AddResource(thisType.Namespace + ".Mappings.hbm.xml", thisAssembly);

			PersistentClass persistentClass = cfg.GetClassMapping(typeof(TestNH1061));
			// We know the ID generator is an IncrementGenerator.  The dialect does
			// not play a big role here, so just use the MsSql2000Dialect.
			IncrementGenerator generator =
				(IncrementGenerator)
				persistentClass.Identifier.CreateIdentifierGenerator(new Dialect.MsSql2000Dialect(), null, null, null);

			// I could not find a good seam to crack to test this.
			// This is not ideal as we are reflecting into a private variable to test.
			// On the other hand, the IncrementGenerator is rather stable, so I don't
			// think this would be a huge problem.
			// Having said that, if someone sees this and have a better idea to test,
			// please feel free to change it.
			FieldInfo sqlFieldInfo = generator.GetType().GetField("sql", BindingFlags.NonPublic | BindingFlags.Instance);
			string sql = (string)sqlFieldInfo.GetValue(generator);

			Assert.AreEqual("select max(Id) from test.TestNH1061", sql);
		}
		public void NwaitingForSuper()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.Customer.hbm.xml", typeof (ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Null, "cannot be in the configuration yet!");

			cfg.AddResource(BaseForMappings + "Extendshbm.Employee.hbm.xml", typeof (ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Employee).FullName), Is.Null, "cannot be in the configuration yet!");

			cfg.AddResource(BaseForMappings + "Extendshbm.Person.hbm.xml", typeof (ExtendsFixture).Assembly);

			cfg.BuildMappings();
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Person).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Employee).FullName), Is.Not.Null);
		}
Example #11
0
		public void CanLoadMappingWithNotNullIgnore()
		{
			var cfg = new Configuration();
			if (TestConfigurationHelper.hibernateConfigFile != null)
				cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
			Assert.DoesNotThrow(
				() => cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1255.Mappings.hbm.xml", typeof (Customer).Assembly));
		}
		public void ValidateQuickStart() 
		{
			Configuration cfg = new Configuration();
			cfg.AddResource( "NHibernate.Examples.ForumQuestions.T1078029.Member.hbm.xml", Assembly.Load("NHibernate.Examples") );
			
			ISessionFactory factory = cfg.BuildSessionFactory();
			
		}
		public void ClassMissingDefaultCtor()
		{
			// add a resource that doesn't exist
			string resource = "NHibernate.Test.MappingExceptions.MissingDefCtor.hbm.xml";
			Configuration cfg = new Configuration();
			cfg.AddResource(resource, this.GetType().Assembly);
			Assert.Throws<InstantiationException>(() =>cfg.BuildSessionFactory());
		}
		public void OrderingAddResources()
		{
			Configuration cfg = new Configuration();
			foreach (string res in Resources)
			{
				cfg.AddResource(res, MyAssembly);
			}
			cfg.BuildSessionFactory().Close();
		}
		public void AllInOne()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.allinone.hbm.xml", typeof(ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof(Person).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof(Employee).FullName), Is.Not.Null);
		}
		public void ConfigurationIsOK()
		{
			Configuration cfg = new Configuration();
			cfg.AddResource("NHibernate.Test.NHSpecificTest.NH251.CustomAccessDO.hbm.xml",
			                Assembly.GetExecutingAssembly());

			ISessionFactoryImplementor factory = (ISessionFactoryImplementor)cfg.BuildSessionFactory();
			cfg.GenerateSchemaCreationScript(factory.Dialect);
		}
        public void AddToConfiguration(Configuration cfg)
        {
            ArrayList orderedHbms;
            ArrayList extraFiles;
            this.GetHbmFiles(out orderedHbms, out extraFiles);

            foreach (NonClassEntry file in extraFiles)
            {
                cfg.AddResource(file.FileName, file.Assembly);    
            }

            // Add ordered hbms *after* the extra files, so that the extra files are processed first.
            // This may be useful if the extra files define filters, etc. that are being used by
            // the entity mappings.
            foreach (ClassEntry classEntry in orderedHbms)
            {
                cfg.AddResource(classEntry.FileName, classEntry.Assembly);
            }
        }
		private void CreateConfig()
		{
			cfg = new Configuration();

			for (int i=0; i<files.Count; i++) 
			{
				cfg.AddResource( assemblyName + "." + files[i].ToString(), Assembly.Load( assemblyName ) );
			}
			sessions = cfg.BuildSessionFactory( );
		}
		public void NotAllowRelatedCollections()
		{
			Configuration configure = new Configuration().Configure();
			configure.AddResource("NHibernate.Test.CfgTest.Loquacious.EntityToCache.hbm.xml", GetType().Assembly);

			var exception =
				Assert.Throws<ArgumentOutOfRangeException>(
					() => configure.EntityCache<EntityToCache>(ce => ce.Collection(e => e.Relation.Elements, cc => { })));
			Assert.That(exception.Message, Is.StringContaining("Collection not owned by"));
		}
        public static void LoadFactory()
        {
            Configuration cfg = new Configuration().Configure("Database.cfg.xml");

            //load resources
            cfg.AddResource(@"SharekalItemUpdate.Item.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());
            cfg.AddResource(@"SharekalItemUpdate.ShopItem.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());
            cfg.AddResource(@"SharekalItemUpdate.Server.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());
            cfg.AddResource(@"SharekalItemUpdate.Prefix.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly());

            try
            {
                Factory = cfg.BuildSessionFactory();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                System.Environment.Exit(0);
            }
        }
 public void CreateDb()
 {
     InitializeServiceLocator();
     Configuration cfg = new Configuration();
     Environment.BytecodeProvider = GetBytecodeProvider();
     cfg.Configure();
     cfg.AddResource("uNhAddIns.Adapters.CommonTests.EnhancedBytecodeProvider.Foo.Spechbm.xml",
                                     typeof(AbstractInjectableUserTypeFixture).Assembly);
     new SchemaExport(cfg).Create(false, true);
     sessions = (ISessionFactoryImplementor)cfg.BuildSessionFactory();
 }
		public void TestFilterThrowsWithNoParameterSet()
		{
			Configuration cfg = new Configuration();
			cfg.AddResource(mappingCfg, this.GetType().Assembly);

			ISessionFactory factory = cfg.BuildSessionFactory();

			ISession session = factory.OpenSession();
			IFilter filter = session.EnableFilter("LiveFilter");
			Assert.Throws<HibernateException>(() => filter.Validate());
		}
		public void ManyToManyTableCreationScript()
		{
			Configuration cfg = new Configuration();
			Assembly assembly = Assembly.GetExecutingAssembly();
			cfg.AddResource( "NHibernate.Test.NHSpecificTest.NH257.Mappings.hbm.xml", assembly );
			
			string[] script = cfg.GenerateSchemaCreationScript(new Dialect.MsSql2000Dialect());
			string createManyToManyTable = script[1];
			Assert.AreEqual("create table users_in_groups (group_id INT not null, user_id INT not null, primary key (user_id, group_id))",
				createManyToManyTable);
		}
Example #24
0
		public void ShouldNotThrowDuplicateMapping()
		{
			var cfg = new Configuration();
			if (TestConfigurationHelper.hibernateConfigFile != null)
				cfg.Configure(TestConfigurationHelper.hibernateConfigFile);

			cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1700.Mappings.hbm.xml", GetType().Assembly);
			new SchemaExport(cfg).Create(false, true);

			new SchemaExport(cfg).Drop(false, true);
		}
        private Configuration CreateConfiguration()
        {
            Configuration cfg = new Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            Assembly assembly = Assembly.GetExecutingAssembly();

            foreach (string file in Mappings)
                cfg.AddResource(assembly.GetName().Name + "." + file, assembly);
            SearchTestCase.SetListener(cfg);
            return cfg;
        }
Example #26
0
		public void Config()
		{
			cfg = new Configuration();
			if (TestConfigurationHelper.hibernateConfigFile != null)
				cfg.Configure(TestConfigurationHelper.hibernateConfigFile);

			cfg.AddResource(GetResourceFullName(), GetType().Assembly);

			factory = (ISessionFactoryImplementor)cfg.BuildSessionFactory();

			expectedExportString = GetDialect().GetTypeName(NHibernateUtil.Decimal.SqlType, 0, 5, 2);
		}
Example #27
0
        /// <summary>
        /// Add a spatial metadata class mapping to NHibernate configuration.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="clazz">The clazz.</param>
        /// <remarks>
        /// DO NOT add metadata class mappings when using the SchemaExport utility.
        /// You could lose all contents of those tables.
        /// </remarks>
        public static void AddMapping(Configuration configuration, MetadataClass clazz)
        {
            NHibernate.Dialect.Dialect dialect = NHibernate.Dialect.Dialect.GetDialect(configuration.Properties);

            string resource = typeof(Metadata).Namespace
                + "."
                + clazz.ToString()
                + "."
                + dialect.GetType().Name
                + ".hbm.xml";

            configuration.AddResource(resource, dialect.GetType().Assembly);
        }
		public void ExportSchema(string[] files, bool exportSchema) 
		{
			cfg = new Configuration();
			
			for (int i=0; i<files.Length; i++) 
			{
				cfg.AddResource("NHibernate.Examples.ForumQuestions." + files[i], Assembly.Load(AssemblyName));
			}

			if(exportSchema) new SchemaExport(cfg).Create(true, true);
		
			sessions = cfg.BuildSessionFactory( );
			dialect = Dialect.Dialect.GetDialect( cfg.Properties );
		}
		public void AddClassNotFound()
		{
			Configuration cfg = new Configuration();
			try
			{
				cfg.AddResource("NHibernate.Test.MappingExceptions.A.ClassNotFound.hbm.xml", this.GetType().Assembly);
			}
			catch (MappingException me)
			{
				Assert.IsTrue(me.InnerException is MappingException);
				MappingException innerMe = (MappingException) me.InnerException;
				Assert.AreEqual("persistent class " + typeof(A).FullName + " not found", innerMe.Message);
			}
		}
		public void ResourceNotFound() 
		{
			// add a resource that doesn't exist
			string resource = "NHibernate.Test.MappingExceptions.A.DoesNotExists.hbm.xml";
			Configuration cfg = new Configuration();
			try 
			{
				cfg.AddResource( resource, this.GetType().Assembly );
			}
			catch( MappingException me ) 
			{
				Assert.AreEqual( "Resource: " + resource + " not found", me.Message );
			}
		}
        /// <remarks>
        /// Cначала осуществляется поиск fluent-маппинга, в случае
        /// неудачи ищется hbm.xml-маппинг.
        /// </remarks>
        private ISessionFactoryProvider FindMapping(Type type, Assembly assembly = null)
        {
            assembly = assembly ?? type.Assembly;

            var fluentMappings = assembly.GetTypes()
                                 .Where(x => x.IsSubclassOf(typeof(ClassMap <>).MakeGenericType(type)))
                                 .ToList();

            if (fluentMappings.Count > 1)
            {
                throw new EntityMappingRegistrationException($"There are more than one fluent mapping for {type.FullName}.");
            }

            var fluentMapping = fluentMappings.SingleOrDefault();

            if (fluentMapping != null)
            {
                _fluentMappingTypes.Add(fluentMapping);
                Logger.LogDebug($"An entity with the {type.FullName} has been registered with the fluent mapping");
            }
            else
            {
                var typeManifestName = assembly.GetManifestResourceNames()
                                       .SingleOrDefault(x => x.Contains($"{type.FullName}.hbm.xml"));

                if (string.IsNullOrEmpty(typeManifestName))
                {
                    throw new EntityMappingRegistrationException($"There is no .hbm.xml mapping for {type.FullName}.");
                }

                nhConfig.AddResource(typeManifestName, assembly);
                Logger.LogDebug($"An entity with the {type.FullName} and the mapping {typeManifestName} has been registered");
            }

            return(this);
        }