public void Can_Load_Configuration_With_Mappings()
        {
            var mgr = new NHibernateSessionManager();
            ISession session = mgr.GetSession();

            Assert.IsNotNull(session);
        }
        public void TestOuterDisposeOfTheSession()
        {
            ISession session1;

            using (session1 = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml"))
            {
            }
            ISession session2 = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml");

            Assert.That(session1, Is.Not.EqualTo(session2), "Same session returned even if we disposed outside the SessionManager");
        }
Ejemplo n.º 3
0
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            var session = NHibernateSessionManager.GetSession();

            if (session.Transaction != null && session.Transaction.IsActive)
            {
                session.Transaction.Commit();
            }
            NHibernate.Context.CurrentSessionContext.Unbind(NHibernateSessionManager.GetSessionFactory());
            session.Dispose();
        }
        public void VerifyThatSessionIsDisposedWhenRollbackOccurred()
        {
            ISession session1;

            using (GlobalTransactionManager.BeginTransaction())
            {
                session1 = NHibernateSessionManager.GetSessionFor("files\\NhConfigFile1.cfg.xml");
                GlobalTransactionManager.DoomCurrentTransaction();
            }
            Assert.That(session1.IsOpen, Is.False);
        }
Ejemplo n.º 5
0
        private void InitializeSessionFactories()
        {
            bool writeOnly = false;

            foreach (var connectionString in _connectionStrings)
            {
                NHibernateSessionManager.AddSessionFactory(connectionString, writeOnly);

                writeOnly = true;
            }
        }
Ejemplo n.º 6
0
        public VehicleModel Save(string code, string name, VehicleBrand brand, VehicleSize size, VehicleType type)
        {
            VehicleModel newModel = null;
            var          session  = NHibernateSessionManager.GetLocalSession();

            session.DoTransactional(sess =>
            {
                newModel = _modelRepo.Insert(new VehicleModel(code, name, brand, size, type));
            });

            return(newModel);
        }
Ejemplo n.º 7
0
        public void Begin()
        {
            if (NHSession.IsNull())
            {
                NHSession = NHibernateSessionManager.OpenSession(FlushMode.Commit);
            }

            if (NHSession.Transaction.IsActive == false)
            {
                NHSession.Transaction.Begin(IsolationLevel.ReadCommitted);
            }
        }
Ejemplo n.º 8
0
        public VehicleBrand Save(string code, string name)
        {
            VehicleBrand brand   = null;
            ISession     session = NHibernateSessionManager.GetLocalSession();

            session.DoTransactional(sess =>
            {
                brand = _brandRepo.Insert(
                    new VehicleBrand(code, name));
            });

            return(brand);
        }
        public void ThrowExceptionIfInvalidFilePathForDatabaseCreation()
        {
            // Arrange
            DatabaseFactory.CreateTestFolder();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            // Act
            Action action = () => sessionManager.CreateDatabase("Desktop\\Test");

            // Assert
            action.ShouldThrow <FluentConfigurationException>();
        }
        public void SetFilePathWhenDatabaseWasLoaded()
        {
            // Arrange
            DatabaseFactory.CreateTestFile();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            // Act
            sessionManager.LoadDatabase(DatabaseFactory.TestFilePath);

            // Assert
            sessionManager.FilePath.Should().Be(DatabaseFactory.TestFilePath);
        }
        public void DoNothingIfDatabaseShouldBeClosedWhenNotConnected()
        {
            // Arrange
            DatabaseFactory.CreateTestFile();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            // Act
            Action action = () => sessionManager.CloseDatabase();

            // Assert
            action.ShouldNotThrow <Exception>();
        }
        public void CanCreateDatabase()
        {
            // Arrange
            DatabaseFactory.CreateTestFolder();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            // Act
            sessionManager.CreateDatabase(DatabaseFactory.TestFilePath);

            // Assert
            FileAssert.Exists(DatabaseFactory.TestFilePath);
        }
Ejemplo n.º 13
0
        public void CanCorrectlyMapCityToPostalCode()
        {
            // Arrange
            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            sessionManager.CreateDatabase(DatabaseFactory.TestFilePath);

            // Assert
            new PersistenceSpecification <CityToPostalCode>(sessionManager.OpenSession(), new ObjectEqualityComparer())
            .CheckProperty(c => c.PostalCode, ModelFactory.DefaultCityToPostalCodePostalCode)
            .CheckProperty(c => c.City, ModelFactory.DefaultCityToPostalCodeCity)
            .VerifyTheMappings();
        }
        public void IsConnectedAfterDatabaseCreation()
        {
            // Arrange
            DatabaseFactory.CreateTestFolder();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            // Act
            sessionManager.CreateDatabase(DatabaseFactory.TestFilePath);

            // Assert
            sessionManager.IsConnected.Should().BeTrue();
        }
        public void ThrowExceptionIfInvalidFilePathForDatabaseLoading()
        {
            // Arrange
            DatabaseFactory.CreateTestFile();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            // Act
            Action action = () => sessionManager.LoadDatabase("Desktop\\Test");

            // Assert
            action.ShouldThrow <InvalidOperationException>();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// In the test fixture setup I simply ovveride the configuration registry
        /// using an in memory configuration with a fixed connection string.
        /// </summary>
        protected override void OnTestFixtureSetUp()
        {
            sut = new NHibernateRepository <AnEntity>();
            sut.ConfigurationFileName = ConfigFileName;
            repo = new InMemoryConfigurationRegistry();
            repo.ConnStrings.Add(
                "main", new ConnectionStringSettings(
                    "main", "Data Source=DbFile1.db;Version=3", "System.Data.SQLite"));
            DisposeAtTheEndOfFixture(ConfigurationRegistry.Override(repo));
            NHibernateSessionManager.GenerateDbFor(ConfigFileName);

            base.OnTestFixtureSetUp();
        }
Ejemplo n.º 17
0
        public ProductCategory Save()
        {
            ProductCategory productCategory = null;
            var             session         = NHibernateSessionManager.GetLocalSession();

            session.DoTransactional(sess =>
            {
                productCategory = new ProductCategory(_form.Code, _form.CategoryName, _form.CategoryDescription);

                productCategory = _categoryRepository.Insert(productCategory);
            });

            return(productCategory);
        }
Ejemplo n.º 18
0
        private static int GetNewDailyIndexOf <T>() where T : Entity
        {
            var session = NHibernateSessionManager.GetLocalSession();

            var entityNewIndex = session.CreateCriteria <T>()
                                 .SetProjection(Projections.CountDistinct(@"Id"))
                                 .Add(
                Restrictions.Conjunction()
                .Add(Restrictions.Gt(@"CreatedOn", DateTime.Today))
                .Add(Restrictions.Lt(@"CreatedOn", DateTime.Today.AddDays(1).AddTicks(-1)))
                ).UniqueResult <int>() + 1;

            return(entityNewIndex);
        }
Ejemplo n.º 19
0
        public UnitOfMeasurement Save()
        {
            UnitOfMeasurement uom = null;
            var session = NHibernateSessionManager.GetLocalSession();

            session.DoTransactional(sess =>
                {
                    uom = _measurementRepository.Insert(
                        new UnitOfMeasurement(_form.MeasurementName, _form.MeasurementDescription)
                        );
                });

            return uom;
        }
Ejemplo n.º 20
0
        public void OpenConnection()
        {
            ISession _session = null;

            try
            {
                NHibernateSessionManager <BaseForm> .Connection = connection;
                _session = NHibernateSessionManager <BaseForm> .OpenSession();

                Assert.AreNotEqual(null, _session);
                _DataAccessLayer = new DataAccessLayer(_session);
                Assert.AreNotEqual(null, _DataAccessLayer);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception : " + e.ToString() + "\r\n" + e.InnerException.ToString());
                Assert.Fail("Exception : " + e.ToString() + "\r\n" + e.InnerException.ToString());
            }
            try
            {
                for (int i = 0; i < 4; i++)
                {
                    Persoon pers = new Persoon()
                    {
                        Naam     = "VDB",
                        Voornaam = "Bram" + i.ToString(),

                        Straat     = "Brugsestraat",
                        Nr         = "113 - bus 3.01",
                        Postcode   = "8020",
                        Woonplaats = "Oostkamp",
                        Land       = "Belgie",



                        Email = "*****@*****.**",
                        GSMNr = "0000",
                        TelNr = "000001"
                    };


                    _DataAccessLayer.AddRecord <Persoon>(pers);
                }
            }
            catch (Exception e)
            {
                Assert.Fail("Exception : " + e.ToString() + "\r\n" + e.InnerException.ToString());
                Console.WriteLine("Exception : " + e.ToString() + "\r\n" + e.InnerException.ToString());
            }
        }
Ejemplo n.º 21
0
        public void LoadAll()
        {
            LoadProvince();
            LoadCity();
            LoadBrand();
            LoadModel();

            using (var tx = NHibernateSessionManager.GetLocalSession().BeginTransaction())
            {
                var superAdmin = new User(
                    new Employee(
                        new Branch(
                            @"MAI",
                            @"MACSAUTO JAKARTA",
                            new Address(
                                _cityRepository.FindByName(@"ADMINISTRASI JAKARTA BARAT"),
                                @"11720",
                                @"KAPUK"
                                )
                            ),
                        Position.Storemanager,
                        new PersonName(@"SUPERADMIN"),
                        Gender.Male
                        ),
                    @"SUPERADMINMAI",
                    @"SUPERADMINMAI"
                    );

                _userRepository.Insert(superAdmin);

                var provinces = _provinceRepository.GetAll();
                var cities    = _cityRepository.GetAll();

                foreach (var province in provinces)
                {
                    province.CreatedBy = superAdmin.Employee;

                    _provinceRepository.Update(province);
                }

                foreach (var city in cities)
                {
                    city.CreatedBy = superAdmin.Employee;

                    _cityRepository.Update(city);
                }

                tx.Commit();
            }
        }
        public void CanGetSessionWhenConnected()
        {
            // Arrange
            DatabaseFactory.CreateTestFile();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            sessionManager.LoadDatabase(DatabaseFactory.TestFilePath);

            // Act
            ISession session = sessionManager.OpenSession();

            // Assert
            session.Should().NotBeNull();
        }
        public void CanGetCachedEntityById()
        {
            // Arrange - read once to seed the second level cache and close and open a new session
            IList <Product> all = GetAll <Product>();

            Product p = Session.Get <Product>(all[0].Id);

            NHibernateSessionManager.CloseSession();
            NHibernateSessionManager.OpenSession();

            // Act - This should come from the second level cache this time
            Product p2 = Session.Get <Product>(all[0].Id);

            // Assert - just make sure something is returned, we're not testing NHibernate
            Assert.IsNotNull(p2);
        }
Ejemplo n.º 24
0
        public Storage Save()
        {
            var session = NHibernateSessionManager.GetLocalSession();
            var storage = new Storage(
                _form.StorageCode,
                _form.StorageName,
                _form.StorageDescription
                );

            session.DoTransactional(sess =>
            {
                storage = _storageRepository.Insert(storage);
            });

            return(storage);
        }
Ejemplo n.º 25
0
        private static int GetNewMonthlyIndexOf <T>() where T : Entity, ITransaction
        {
            var childSession = NHibernateSessionManager.GetLocalSession().GetSession(EntityMode.Poco);

            var totalTransaction = childSession.CreateCriteria <T>()
                                   .SetProjection(Projections.RowCount())
                                   .Add(
                Restrictions.Eq(
                    Projections.SqlFunction(@"Month", NHibernateUtil.Int32,
                                            Projections.Property(@"CreatedOn")),
                    DateTime.Now.Month
                    )
                ).UniqueResult <int>();

            return(totalTransaction + 1);
        }
Ejemplo n.º 26
0
        public void CanMapArticle()
        {
            // Arrange
            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            sessionManager.CreateDatabase(DatabaseFactory.TestFilePath);

            // Assert
            new PersistenceSpecification <Article>(sessionManager.OpenSession())
            .CheckProperty(c => c.Id, 1)
            .CheckProperty(c => c.ArticleNumber, ModelFactory.DefaultArticleNumber)
            .CheckProperty(c => c.Description, ModelFactory.DefaultArticleDescription)
            .CheckProperty(c => c.Amount, ModelFactory.DefaultArticleAmount)
            .CheckProperty(c => c.Price, ModelFactory.DefaultArticlePrice)
            .VerifyTheMappings();
        }
        public void SessionIsDisposedAndFlushedWhenClosed()
        {
            ISession session = mockRepository.CreateMock <ISession>();

            Expect.Call(session.Flush);
            Expect.Call(session.Dispose);
            mockRepository.ReplayAll();
            //Need to invoke private method to get the session key to insert mock object.
            String sessionkey = Invoker.InvokePrivate <String>(
                typeof(NHibernateSessionManager), "GetContextSessionKeyForConfigFileName", "files\\NhConfig1.cfg.xml");
            Object obj = Invoker.CreatePrivateInstance(SessionDataTypeName);

            Invoker.SetField(obj, "Session", session);
            overrideContext.storage.Add(sessionkey, obj);
            NHibernateSessionManager.CloseSessionFor("files\\NhConfig1.cfg.xml");
        }
        public void CanGetCachedQueryResults()
        {
            // Arrange - read once to seed the second level cache
            IList <Product> all = GetAll <Product>();

            IList <Order> orders = CreateOrdersByProductQuery(all[0].Id).List <Order>();

            NHibernateSessionManager.CloseSession();
            NHibernateSessionManager.OpenSession();

            // Act - This should come from the second level cache this time
            IList <Order> orders2 = CreateOrdersByProductQuery(all[0].Id).List <Order>();

            // Assert - just make sure something is returned, we're not teststing NHibernate
            Assert.IsNotNull(orders2);
        }
        public void CloseDatabaseAndClearFilePath()
        {
            // Arrange
            DatabaseFactory.CreateTestFile();

            NHibernateSessionManager sessionManager = new NHibernateSessionManager();

            sessionManager.LoadDatabase(DatabaseFactory.TestFilePath);

            // Act
            sessionManager.CloseDatabase();

            // Assert
            sessionManager.IsConnected.Should().BeFalse();
            sessionManager.FilePath.Should().BeNullOrEmpty();
        }
Ejemplo n.º 30
0
        public void CanUseTransactionAttribute()
        {
            _employeeRepository = new EmployeeRepository(
                new Repository <Employee>(NHibernateSessionManager.GetSession())
                );

            var john = new Employee()
            {
                FirstName   = "Johny",
                LastName    = "Doe",
                BirthDate   = new DateTime(1989, 12, 08),
                Gender      = Gender.Male,
                HomeAddress = new Address("California", "90210", "Chill Rd.")
            };

            var newEmployee = _employeeRepository.RegisterEmployee(john);
        }
Ejemplo n.º 31
0
        public void Setup()
        {
            NHibernateSessionManager.Initialize();

            NHibernateSessionManager.OpenSession();
            NHibernateSessionManager.BeginTransaction();

            try
            {
                CreateStandardDataSet();
            }
            finally
            {
                NHibernateSessionManager.CommitTransaction();
                NHibernateSessionManager.CloseSession();
            }
        }
 public void Test_Fixture_Set_Up()
 {
     _sessionFactory = new NHibernateSessionManager();
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Clears the second level cache for the specified entity type.
 /// </summary>
 /// <param name="type">The type.</param>
 public void ClearSecondLevelCache(Type type)
 {
     var sessionFactory = new NHibernateSessionManager(_configPath).GetSessionFactory();
     sessionFactory.Evict(type);
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Clears the query cache.
 /// </summary>
 public void ClearQueryCache()
 {
     var sessionFactory = new NHibernateSessionManager(_configPath).GetSessionFactory();
     sessionFactory.EvictQueries();
 }