public void Can_attach()
        {
            var customer = new Customer
            {
                FirstName = "Jane",
                LastName = "Doe"
            };
            var session = NHTestUtil.OrdersDomainFactory.OpenSession();
            ITransaction transaction = session.BeginTransaction();
            session.Save(customer);
            transaction.Commit();
            session.Evict(customer); //Detching from owning session
            session.Dispose(); //Auto flush

            using (var scope = new UnitOfWorkScope())
            {
                var repository = new NHRepository<Customer,int>();
                repository.Attach(customer);
                customer.LastName = "Changed";
                scope.Commit(); //Should change since the customer was attached to repository.
            }

            using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                Customer savedCustomer = null;
                testData.Batch(x => savedCustomer = x.GetCustomerById(customer.CustomerID));
                Assert.IsNotNull(savedCustomer);
                Assert.AreEqual(savedCustomer.LastName, "Changed");
            }
        }
Exemple #2
0
        internal static void Setup(out ContentPersister persister, FakeSessionProvider sessionProvider, ItemFinder finder, SchemaExport schemaCreator)
        {
            IRepository <int, ContentItem>     itemRepository = new ContentItemRepository(sessionProvider);
            INHRepository <int, ContentDetail> linkRepository = new NHRepository <int, ContentDetail>(sessionProvider);

            Setup(out persister, sessionProvider, itemRepository, linkRepository, finder, schemaCreator);
        }
Exemple #3
0
        public void Query_Allows_Projection_Using_Select_Projection()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
                using (new UnitOfWorkScope())
                {
                    testData.Batch(actions =>
                                   actions.CreateOrderForCustomer(actions.CreateCustomer()));

                    var ordersRepository = new NHRepository <Order>();
                    var results          = from order in ordersRepository
                                           select new
                    {
                        order.Customer.FirstName,
                        order.Customer.LastName,
                        order.ShipDate,
                        order.OrderDate
                    };

                    Assert.DoesNotThrow(() => results.ForEach(x =>
                    {
                        Assert.That(string.IsNullOrEmpty(x.LastName), Is.False);
                        Assert.That(string.IsNullOrEmpty(x.FirstName), Is.False);
                    }));
                }
        }
        public void Test_Can_Get_MonthlySalesSummary_With_Money_Type()
        {
            IList<MonthlySalesSummary> report;
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            using (var scope = new UnitOfWorkScope())
            {
                testData.Batch(action => action.CreateMonthlySalesSummaryForMonth(1));

                var repository = new NHRepository<MonthlySalesSummary>();
                report = (from summary in repository
                          where summary.Month == 1
                          select summary).ToList();

                scope.Commit();
            }

            Assert.That(report, Is.Not.Null);
            Assert.That(report.Count, Is.GreaterThan(0));

            report.ForEach(rep =>
                               {
                                   Assert.That(rep.Month == 1);
                                   Assert.That(rep.TotalSale, Is.Not.Null);
                                   Assert.That(rep.TotalSale.Amount, Is.GreaterThan(0));
                                   Assert.That(rep.TotalSale.Currency, Is.Not.Null);
                               });
        }
        public void Test_Can_Query_MonthlySalesSummary_Based_On_Currency()
        {
            IList<MonthlySalesSummary> report;
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            using (var scope = new UnitOfWorkScope())
            {
                testData.Batch(actions => actions.CreateMonthlySalesSummaryWithAmount(
                    new Money{Amount = 100, Currency = "YEN"}
                    ));

                var repository = new NHRepository<MonthlySalesSummary>();
                report = (from summary in repository
                          where summary.TotalSale.Currency == "YEN"
                          select summary).ToList();

                scope.Commit();
            }

            Assert.That(report, Is.Not.Null);
            Assert.That(report.Count, Is.GreaterThan(0));

            report.ForEach(rep =>
            {
                Assert.That(rep.TotalSale, Is.Not.Null);
                Assert.That(rep.TotalSale.Amount, Is.GreaterThan(0));
                Assert.That(rep.TotalSale.Currency, Is.Not.Null);
                Assert.That(rep.TotalSale.Currency, Is.EqualTo("YEN"));
            });
        }
Exemple #6
0
        public void Repository_For_Uses_Registered_Fetching_Strategies()
        {
            IEnumerable <Order> orders;

            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
                using (new UnitOfWorkScope())
                {
                    testData.Batch(actions =>
                                   actions.CreateOrderForProducts(actions.CreateProducts(5)));

                    var strategies = new IFetchingStrategy <Order, NHRepositoryTests>[]
                    {
                        new OrderOrderItemsStrategy(),
                        new OrderItemsProductStrategy()
                    };

                    ServiceLocator.Current.Expect(x => x.GetAllInstances <IFetchingStrategy <Order, NHRepositoryTests> >())
                    .Return(strategies);

                    orders = new NHRepository <Order>()
                             .For <NHRepositoryTests>()
                             .ToList();
                }
            orders.ForEach(order =>
            {
                Assert.That(NHibernateUtil.IsInitialized(order.Items), Is.True);
                order.Items.ForEach(item =>
                                    Assert.That(NHibernateUtil.IsInitialized(item.Product), Is.True));
            });
        }
        public void Test_Can_Query_MonthlySalesSummary_Based_On_Currency()
        {
            IList <MonthlySalesSummary> report;

            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
                using (var scope = new UnitOfWorkScope())
                {
                    testData.Batch(actions => actions.CreateMonthlySalesSummaryWithAmount(
                                       new Money {
                        Amount = 100, Currency = "YEN"
                    }
                                       ));

                    var repository = new NHRepository <MonthlySalesSummary>();
                    report = (from summary in repository
                              where summary.TotalSale.Currency == "YEN"
                              select summary).ToList();

                    scope.Commit();
                }

            Assert.That(report, Is.Not.Null);
            Assert.That(report.Count, Is.GreaterThan(0));

            report.ForEach(rep =>
            {
                Assert.That(rep.TotalSale, Is.Not.Null);
                Assert.That(rep.TotalSale.Amount, Is.GreaterThan(0));
                Assert.That(rep.TotalSale.Currency, Is.Not.Null);
                Assert.That(rep.TotalSale.Currency, Is.EqualTo("YEN"));
            });
        }
        public void Test_Updating_Money_Amount_Updates_Amount_In_Store_And_Returns_Updated_Figure()
        {
            var newAmount = (decimal) new Random().Next();

            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions => actions.CreateMonthlySalesSummaryForSalesPerson(1));

                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository <MonthlySalesSummary>();
                    var report     = (from summary in repository
                                      where summary.SalesPersonId == 1
                                      select summary).SingleOrDefault();
                    report.TotalSale.Amount = newAmount;
                    scope.Commit();
                }

                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository <MonthlySalesSummary>();
                    var report     = (from summary in repository
                                      where summary.SalesPersonId == 1
                                      select summary).SingleOrDefault();

                    Assert.That(report.TotalSale.Amount, Is.EqualTo(newAmount));
                    scope.Commit();
                }
            }
        }
Exemple #9
0
        public void UnitOfWork_Rolledback_When_Containing_TransactionScope_Is_Rolledback()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions =>
                               actions.CreateOrderForCustomer(actions.CreateCustomer()));

                int      orderId;
                DateTime oldDate;

                using (var txScope = new TransactionScope(TransactionScopeOption.Required))
                    using (var uowScope = new UnitOfWorkScope(IsolationLevel.Serializable))
                    {
                        var ordersRepository = new NHRepository <Order>();
                        var order            = (from o in ordersRepository
                                                select o).First();

                        oldDate         = order.OrderDate;
                        order.OrderDate = DateTime.Now;
                        orderId         = order.OrderID;
                        uowScope.Commit();
                        //Note: txScope has not been committed
                    }

                using (new UnitOfWorkScope())
                {
                    var ordersRepository = new NHRepository <Order>();
                    var order            = (from o in ordersRepository
                                            where o.OrderID == orderId
                                            select o).First();

                    Assert.That(order.OrderDate, Is.EqualTo(oldDate));
                }
            }
        }
Exemple #10
0
        public void DeleteItemCascadesDetails()
        {
            IRepository <ContentDetail> detailRepository = new NHRepository <ContentDetail>(sessionProvider);
            int itemID = 0;

            using (repository)
            {
                ContentItem item = CreateOneItem <Definitions.PersistableItem>(0, "item", null);
                item["TheString"] = "the string";
                repository.Save(item);
                repository.Flush();
                itemID = item.ID;
            }
            using (detailRepository)
            {
                Assert.AreEqual(1, detailRepository.Count());
            }
            using (repository)
            {
                ContentItem item = repository.Get(itemID);
                repository.Delete(item);
                repository.Flush();
            }
            using (detailRepository)
            {
                Assert.AreEqual(0, detailRepository.Count());
            }
        }
Exemple #11
0
        public ActionResult Edit(int id)
        {
            var attendee = new NHRepository <Attendee>().Get(id);

            if (attendee.Type == AttendeeType.Pupil)
            {
                List <School> schools;
                using (var repository = new NHGetAllRepository <School>())
                {
                    schools = repository.GetAll().ToList();
                }

                ViewData["Schools"] = new SelectList(schools, "Id", "Name");

                List <AcademicProgram> programs;
                using (var repository = new NHGetAllRepository <AcademicProgram>())
                {
                    programs = repository.GetAll().ToList();
                }

                ViewData["Programs"] = new SelectList(programs, "Id", "Name");

                var list = new AcademicProgram {
                    Id = -1, Name = "не выбрано"
                }.AsEnumerable().Concat(programs).ToList();
                ViewData["NullablePrograms"] = new SelectList(list, "Id", "Name");


                var pupil = attendee as Pupil;

                return(View("EditPupil", pupil));
            }

            return(View(attendee));
        }
Exemple #12
0
        internal static void Setup(out ContentPersister persister, FakeSessionProvider sessionProvider, SchemaExport schemaCreator)
        {
            var itemRepository = new ContentItemRepository(sessionProvider);
            var linkRepository = new NHRepository <ContentDetail>(sessionProvider);

            Setup(out persister, sessionProvider, itemRepository, linkRepository, schemaCreator);
        }
        public void Test_Can_Get_MonthlySalesSummary_With_Money_Type()
        {
            IList <MonthlySalesSummary> report;

            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
                using (var scope = new UnitOfWorkScope())
                {
                    testData.Batch(action => action.CreateMonthlySalesSummaryForMonth(1));

                    var repository = new NHRepository <MonthlySalesSummary>();
                    report = (from summary in repository
                              where summary.Month == 1
                              select summary).ToList();

                    scope.Commit();
                }

            Assert.That(report, Is.Not.Null);
            Assert.That(report.Count, Is.GreaterThan(0));

            report.ForEach(rep =>
            {
                Assert.That(rep.Month == 1);
                Assert.That(rep.TotalSale, Is.Not.Null);
                Assert.That(rep.TotalSale.Amount, Is.GreaterThan(0));
                Assert.That(rep.TotalSale.Currency, Is.Not.Null);
            });
        }
Exemple #14
0
        public void Query_Using_Specifications_With_Closure_Works()
        {
            //This test demonstrates how closures can be used to modify a pre-defined specification using
            //parameters. The specification in this test searches for all customers in the state specified by
            //the queryState local variable. The test then proceeds to build a query using the specification
            //and enumerates over the states array and executes the query by changing the queryState parameter.

            var states     = new[] { "PA", "LA" };
            var queryState = string.Empty;

            var spec       = new Specification <Order>((order) => order.Customer.Address.State == queryState);
            var repository = new NHRepository <Order>();

            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
                using (new UnitOfWorkScope())
                {
                    testData.Batch(actions =>
                    {
                        actions.CreateOrdersForCustomers(actions.CreateCustomersInState("PA", 2));
                        actions.CreateOrdersForCustomers(actions.CreateCustomersInState("DE", 5));
                        actions.CreateOrdersForCustomers(actions.CreateCustomersInState("LA", 3));
                    });

                    var query = repository.With(x => x.Customer).Query(spec);
                    states.ForEach(testState =>
                    {
                        queryState  = testState;
                        var results = query.ToArray();
                        results.ForEach(result =>
                                        Assert.That(result.Customer.Address.State, Is.EqualTo(testState)));
                    });
                }
        }
        public object Delete(int id)
        {
            var repo = new NHRepository <Volunteer>();

            repo.Delete(id);

            return(0);
        }
        public object Delete(int id)
        {
            var repo = new NHRepository <Department>();

            repo.Delete(id);

            return(0);
        }
Exemple #17
0
        public override void SetUp()
        {
            base.SetUp();
            CreateDatabaseSchema();

            sessionProvider = engine.Resolve <ISessionProvider>();
            repository      = new NHRepository <int, ContentItem>(sessionProvider);
        }
        public object Delete(int id)
        {
            var repo = new NHRepository <Address>();

            repo.Delete(id);

            return(0);
        }
        public object Delete(int id)
        {
            var repo = new NHRepository <SchoolType>();

            repo.Delete(id);

            return(0);
        }
Exemple #20
0
        public object Delete(int id)
        {
            var repo = new NHRepository <AcademicProgram>();

            repo.Delete(id);

            return(0);
        }
        public ActionResult School(int id = 0)
        {
            ViewBag.Edit = id != 0;

            List <Address> addresses;

            using (var repository = new NHGetAllRepository <Address>())
            {
                addresses = repository.GetAll().ToList();
            }

            var listAddress = (IEnumerable <SelectListItem>) new SelectList(addresses, "Id", "FullAddress");

            List <SchoolType> types;

            using (var repository = new NHGetAllRepository <SchoolType>())
            {
                types = repository.GetAll().ToList();
            }

            var listType = (IEnumerable <SelectListItem>) new SelectList(types, "Id", "Name");


            SchoolDto school = new SchoolDto();

            if (id != 0)
            {
                using (var repository = new NHRepository <School>())
                {
                    var t = repository.Get(id);
                    school = new SchoolDto()
                    {
                        Id      = t.Id,
                        Address = t.Addresses.ToList()[0].Id,
                        Name    = t.Name,
                        Type    = t.Type.Id
                    };
                }


                listAddress = addresses.Select(x =>
                                               new SelectListItem()
                {
                    Text = x.FullAddress, Selected = x.Id == school.Address, Value = x.Id.ToString()
                });

                listType = types.Select(x =>
                                        new SelectListItem()
                {
                    Text = x.Name, Selected = x.Id == school.Type, Value = x.Id.ToString()
                });
            }

            ViewData["Address"] = listAddress;
            ViewData["Type"]    = listType;

            return(View(school));
        }
 private IEnumerable <T> Parse <T>(IEnumerable <int> data) where T : IEntity
 {
     foreach (var id in data.WithEnumerable())
     {
         using (var repository = new NHRepository <T>())
         {
             yield return(repository.Get(id));
         }
     }
 }
        public object Add(string name)
        {
            var repo = new NHRepository <SchoolType>();
            var type = new SchoolType()
            {
                Name = name
            };

            return(repo.Add(type));
        }
        public object Save(int id, string name)
        {
            var repo = new NHRepository <SchoolType>();
            var type = repo.Get(id);

            type.Name = name;

            repo.Update(type);

            return(0);
        }
        public void Delete_Deletes_Record()
        {
            //Adding a dummy record.
            var newAddress = new Address
            {
                StreetAddress1 = "This record was inserted for deletion",
                City = "Fictional city",
                State = "LA",
                ZipCode = "12345"
            };

            var newCustomer = new Customer
            {
                FirstName = ("John_DELETE_ME_" + DateTime.Now),
                LastName = ("Doe_DELETE_ME_" + DateTime.Now),
                Address = newAddress
            };

            //Re-usable query to query for the matching record.
            var queryForCustomer = new Func<NHRepository<Customer>, Customer>
                (x => (from cust in x
                       where cust.FirstName == newCustomer.FirstName && cust.LastName == newCustomer.LastName
                       select cust).FirstOrDefault()
                );

            using (var scope = new UnitOfWorkScope())
            {
                var customerRepository = new NHRepository<Customer>();
                var recordCheckResult = queryForCustomer(customerRepository);
                Assert.That(recordCheckResult, Is.Null);

                customerRepository.Add(newCustomer);
                scope.Commit();
            }

            //Retrieve the record for deletion.
            using (var scope = new UnitOfWorkScope())
            {
                var customerRepository = new NHRepository<Customer>();
                var customerToDelete = queryForCustomer(customerRepository);
                Assert.That(customerToDelete, Is.Not.Null);
                customerRepository.Delete(customerToDelete);
                scope.Commit();
            }

            //Ensure customer record is deleted.
            using (new UnitOfWorkScope())
            {
                var customerRepository = new NHRepository<Customer>();
                var recordCheckResult = queryForCustomer(customerRepository);
                Assert.That(recordCheckResult, Is.Null);
            }
        }
Exemple #26
0
        public void Delete_Deletes_Record()
        {
            //Adding a dummy record.
            var newAddress = new Address
            {
                StreetAddress1 = "This record was inserted for deletion",
                City           = "Fictional city",
                State          = "LA",
                ZipCode        = "12345"
            };

            var newCustomer = new Customer
            {
                FirstName = ("John_DELETE_ME_" + DateTime.Now),
                LastName  = ("Doe_DELETE_ME_" + DateTime.Now),
                Address   = newAddress
            };

            //Re-usable query to query for the matching record.
            var queryForCustomer = new Func <NHRepository <Customer>, Customer>
                                       (x => (from cust in x
                                              where cust.FirstName == newCustomer.FirstName && cust.LastName == newCustomer.LastName
                                              select cust).FirstOrDefault()
                                       );

            using (var scope = new UnitOfWorkScope())
            {
                var customerRepository = new NHRepository <Customer>();
                var recordCheckResult  = queryForCustomer(customerRepository);
                Assert.That(recordCheckResult, Is.Null);

                customerRepository.Add(newCustomer);
                scope.Commit();
            }

            //Retrieve the record for deletion.
            using (var scope = new UnitOfWorkScope())
            {
                var customerRepository = new NHRepository <Customer>();
                var customerToDelete   = queryForCustomer(customerRepository);
                Assert.That(customerToDelete, Is.Not.Null);
                customerRepository.Delete(customerToDelete);
                scope.Commit();
            }

            //Ensure customer record is deleted.
            using (new UnitOfWorkScope())
            {
                var customerRepository = new NHRepository <Customer>();
                var recordCheckResult  = queryForCustomer(customerRepository);
                Assert.That(recordCheckResult, Is.Null);
            }
        }
Exemple #27
0
        public ActionResult Save()
        {
            var data = (IEnumerable <Attendee>)TempData["Import"];

            var repository = new NHRepository <Attendee>();

            foreach (var attendee in data)
            {
                repository.Add(attendee);
            }

            return(RedirectToAction("Index"));
        }
Exemple #28
0
        public void Query_With_Incompatible_UnitOfWork_Throws_InvalidOperationException()
        {
            var mockUnitOfWork = MockRepository.GenerateStub <IUnitOfWork>();

            UnitOfWork.Current = mockUnitOfWork;
            Assert.Throws <InvalidOperationException>(() =>
            {
                var customerRepository = new NHRepository <Customer>();
                var results            = from customer in customerRepository
                                         select customer;
            }
                                                      );
            UnitOfWork.Current = null;
        }
Exemple #29
0
        public void When_Calling_CalculateTotal_On_Order_Returns_Valid_When_Under_UnitOfWork()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
                using (new UnitOfWorkScope())
                {
                    testData.Batch(actions =>
                                   actions.CreateOrderForProducts(actions.CreateProducts(5)));

                    var oredersRepository = new NHRepository <Order>();
                    var order             = (from o in oredersRepository
                                             select o).FirstOrDefault();

                    Assert.That(order.CalculateTotal(), Is.GreaterThan(0));
                }
        }
        public void when_ambient_transaction_is_running_and_a_previous_scope_rollsback_new_scope_still_works()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions => actions.CreateCustomer());

                string oldCustomerName;
                var    newCustomerName = "NewCustomer" + new Random().Next(0, int.MaxValue);
                var    newCustomer     = new Customer
                {
                    FirstName = newCustomerName,
                    LastName  = "Save",
                    Address   = new Address
                    {
                        StreetAddress1 = "This record was inserted via a test",
                        City           = "Fictional City",
                        State          = "LA",
                        ZipCode        = "00000"
                    }
                };

                using (var ambientScope = new TransactionScope())
                {
                    using (var firstUOW = new UnitOfWorkScope())
                    {
                        var customer = new NHRepository <Customer>().First();
                        oldCustomerName    = customer.FirstName;
                        customer.FirstName = "Changed";
                    }  //Rollback

                    using (var secondUOW = new UnitOfWorkScope())
                    {
                        new NHRepository <Customer>().Add(newCustomer);
                        secondUOW.Commit();
                    }
                }

                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository <Customer>();
                    Assert.That(repository.First().FirstName, Is.EqualTo(oldCustomerName));
                    Assert.That(repository.Where(x => x.FirstName == newCustomerName).Count(), Is.GreaterThan(0));
                    repository.Attach(newCustomer);
                    repository.Delete(newCustomer);
                    scope.Commit();
                }
            }
        }
        public ActionResult AcademicProgram(int id = 0)
        {
            ViewBag.Edit = id != 0;

            var academicProgram = new AcademicProgram();

            if (id != 0)
            {
                using (var repository = new NHRepository <AcademicProgram>())
                {
                    academicProgram = repository.Get(id);
                }
            }

            return(View(academicProgram));
        }
        public ActionResult SchoolType(int id = 0)
        {
            ViewBag.Edit = id != 0;

            SchoolType schoolType = new SchoolType();

            if (id != 0)
            {
                using (var repository = new NHRepository <SchoolType>())
                {
                    schoolType = repository.Get(id);
                }
            }

            return(View(schoolType));
        }
        public ActionResult CityType(int id = 0)
        {
            ViewBag.Edit = id != 0;

            CityType cityType = new CityType();

            if (id != 0)
            {
                using (var repository = new NHRepository <CityType>())
                {
                    cityType = repository.Get(id);
                }
            }

            return(View(cityType));
        }
        public ActionResult Volunteer(int id = 0)
        {
            ViewBag.Edit = id != 0;

            Volunteer volunteer = new Volunteer();

            if (id != 0)
            {
                using (var repository = new NHRepository <Volunteer>())
                {
                    volunteer = repository.Get(id);
                }
            }

            return(View(volunteer));
        }
        public void NHUOW_Issue_6_Replication()
        {
            var readCustomerFunc = new Func<Customer>(() =>
            {
                using (var scope = new UnitOfWorkScope())
                {
                    var customer = new NHRepository<Customer>().First();
                    scope.Commit();
                    return customer;
                }
            });

            var updateCustomerFunc = new Func<Customer, Customer>(customer =>
            {
                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository<Customer>();
                    repository.Attach(customer);
                    scope.Commit();
                    return customer;
                }
            });

            var newCustomerName = "Changed" + new Random().Next(0, int.MaxValue);
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions => actions.CreateCustomer());

                using (var masterScope = new UnitOfWorkScope())
                {
                    using (var childScope = new UnitOfWorkScope(UnitOfWorkScopeTransactionOptions.CreateNew))
                    {
                        var customer = readCustomerFunc();
                        customer.FirstName = newCustomerName;
                        updateCustomerFunc(customer);
                        childScope.Commit();
                    }
                } //Rollback

                var checkCustomer = readCustomerFunc();
                Assert.That(checkCustomer.FirstName, Is.EqualTo(newCustomerName));
            }
        }
        public void CanDeleteDetail()
        {
            IRepository<ContentDetail> detailRepository = new NHRepository<ContentDetail>(sessionProvider);

            using (repository)
            {
                ContentItem item = CreateOneItem<Definitions.PersistableItem1>(0, "item", null);
                item["TheString"] = "the string";
                repository.Save(item);
                repository.Flush();

                Assert.AreEqual(1, detailRepository.Count());

                item["TheString"] = null;
                repository.Save(item);
                repository.Flush();

                Assert.AreEqual(0, detailRepository.Count());
            }
        }
        public void changes_are_not_persisted_when_ambient_transaction_rolls_back()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions => actions.CreateCustomer());
                using (var ambientScope = new TransactionScope())
                {
                    using (var scope = new UnitOfWorkScope())
                    {
                        var customer = new NHRepository<Customer>().First();
                        customer.FirstName = "Changed";
                        scope.Commit();
                    }
                } //Auto rollback

                using (var scope = new UnitOfWorkScope())
                {
                    var customer = new NHRepository<Customer>().First();
                    Assert.That(customer.FirstName, Is.Not.EqualTo("Changed"));
                }
            }
        }
Exemple #38
0
        public void NHRepositoryOperationsTest()
        {
            // IMPORTANT NOTE Never use Repository inside a UnitOfWork!!!
            // Never! The Curse of Deadlock will be upon you!!!

            //Instantiate
            var repLoc = new NHRepository<Location>(_sessionFactory);

            // CREATE = Save
            // populate the database
            var input = new List<IMeasure> { new SimpleMeasure("ReteA", 10U) };
            var loc = _entitiesFactory.CreateLocation("Location1", input);
            loc.TotalTime = TimeVal;

            var input2 = new List<IMeasure> { new SimpleMeasure("ReteB", 50U), new SimpleMeasure("ReteC", 100U) };
            var loc2 = _entitiesFactory.CreateLocation("Location2", input2);
            loc2.TotalTime = TimeVal1;

            //this saves everything else via cascading
            repLoc.Save(loc);
            repLoc.Save(loc2);

            // READ = Get and GetAll
            Location locA = null;
            IList<Location> locations = repLoc.GetAll();
            Assert.AreEqual(locations.Count, 2);
            foreach (var location in locations)
            {
                //For a visual feedback
                Console.WriteLine(location.ToString());
                if (location.Name == "Location1")
                {
                    Assert.AreEqual(location.TotalTime, TimeVal);
                    locA = location;
                }
                else if (location.Name == "Location2")
                {
                    Assert.AreEqual(location.TotalTime, TimeVal1);
                }
                else
                {
                    Log.Debug(location.Name);
                    Assert.Fail("Location name not matching");
                }
            }

            Assert.IsNotNull(locA);
            var locB = repLoc.Get(locA.Id);
            Assert.AreEqual(locB.Name, "Location1");
            Assert.AreEqual(locB.TotalTime, TimeVal);

            var repNet = new NHRepository<Network>(_sessionFactory);
            var networks = repNet.GetAll();
            Assert.AreEqual(networks.Count, 3);

            //Dirty Get (without waiting for transactions)
            var locDirty = repLoc.Get(locA.Id, dirty: true);
            Assert.AreEqual(locDirty.Name, "Location1");
            Assert.AreEqual(locDirty.TotalTime, TimeVal);

            var locDirties = repLoc.GetAll(dirty: true);
            Assert.AreEqual(locDirties.Count, 2);
            foreach (var location in locDirties)
            {
                if (location.Name == "Location1")
                {
                    Assert.AreEqual(location.TotalTime, TimeVal);
                }
                else if (location.Name == "Location2")
                {
                    Assert.AreEqual(location.TotalTime, TimeVal1);
                }
                else
                {
                    Log.Debug(location.Name);
                    Assert.Fail("Location name not matching");
                }
            }

            // UPDATE = Update
            // BEWARE OF DIRTY WRITES!!! THEY ARE STILL DIFFERENT TRANSACTIONS!!!
            Location locUpdated = locA;
            locUpdated.TotalTime = TimeVal2;
            repLoc.Update(locUpdated);

            Location tmp = repLoc.Get(locUpdated.Id);
            Assert.AreEqual(tmp.TotalTime, TimeVal2);

            // DELETE = Delete
            locations = repLoc.GetAll();

            foreach (var location in locations)
            {
                repLoc.Delete(location);
            }

            //check cascading deletion
            locations = repLoc.GetAll();
            Assert.AreEqual(locations.Count, 0);

            networks = repNet.GetAll();
            Assert.AreEqual(networks.Count, 0);
        }
        public void Can_modify()
        {
            using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                Customer customer = null;
                testData.Batch(x => customer = x.CreateCustomer());

                using (var scope = new UnitOfWorkScope())
                {
                    var savedCustomer = new NHRepository<Customer, int>().Query
                        .Where(x => x.CustomerID == customer.CustomerID)
                        .First();

                    savedCustomer.LastName = "Changed";
                    scope.Commit();
                }

                testData.Session.Refresh(customer);
                Assert.AreEqual(customer.LastName, "Changed");
            }
        }
        public void Save_Updates_Existing_Order_Record()
        {
            var updatedDate = DateTime.Now;

            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions =>
                               actions.CreateOrderForCustomer(actions.CreateCustomer()));

                int orderId;
                using (var scope = new UnitOfWorkScope())
                {
                    var orderRepository = new NHRepository<Order>();
                    var order = orderRepository.FirstOrDefault();
                    Assert.That(order, Is.Not.Null);
                    orderId = order.OrderID;
                    order.OrderDate = updatedDate;

                    scope.Commit();
                }

                using (new UnitOfWorkScope())
                {
                    var orderRepository = new NHRepository<Order>();
                    var order = (from o in orderRepository
                                 where o.OrderID == orderId
                                 select o).FirstOrDefault();

                    Assert.That(order, Is.Not.Null);
                    Assert.That(order.OrderDate.Date, Is.EqualTo(updatedDate.Date));
                    Assert.That(order.OrderDate.Hour, Is.EqualTo(updatedDate.Hour));
                    Assert.That(order.OrderDate.Minute, Is.EqualTo(updatedDate.Minute));
                    Assert.That(order.OrderDate.Second, Is.EqualTo(updatedDate.Second));
                }
            }
        }
        public void Can_perform_simple_query()
        {
            using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                var customerId = 0;
                testData.Batch(x => customerId = x.CreateCustomer().CustomerID);

                using (var scope = new UnitOfWorkScope())
                {
                    var customer = new NHRepository<Customer, int>().Query
                        .Where(x => x.CustomerID == customerId)
                        .First();

                    Assert.IsNotNull(customer);
                    Assert.AreEqual(customer.CustomerID, customerId);
                    scope.Commit();
                }
            }
        }
        public void When_Calling_CalculateTotal_On_Order_Returns_Valid_When_Under_UnitOfWork()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            using (new UnitOfWorkScope())
            {
                testData.Batch(actions =>
                               actions.CreateOrderForProducts(actions.CreateProducts(5)));

                var oredersRepository = new NHRepository<Order>();
                var order = (from o in oredersRepository
                             select o).FirstOrDefault();

                Assert.That(order.CalculateTotal(), Is.GreaterThan(0));
            }
        }
        public void DeleteItemCascadesDetails()
        {
            IRepository<ContentDetail> detailRepository = new NHRepository<ContentDetail>(sessionProvider);
            int itemID = 0;

            using (repository)
            {
                ContentItem item = CreateOneItem<Definitions.PersistableItem1>(0, "item", null);
                item["TheString"] = "the string";
                repository.Save(item);
                repository.Flush();
                itemID = item.ID;
            }
            using(detailRepository)
            {
                Assert.AreEqual(1, detailRepository.Count());
            }
            using(repository)
            {
                ContentItem item = repository.Get(itemID);
                repository.Delete(item);
                repository.Flush();
            }
            using(detailRepository)
            {
                Assert.AreEqual(0, detailRepository.Count());
            }
        }
        public void Test_SaveOrderAndCommitUsingRepository()
        {
            Order order = new Order();
              //order.CustomFields = new System.Collections.Hashtable();
              //order.CustomFields.Add("OrderDate", DateTime.Now);
              HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
              IRepository<Order> orderRepo = new NHRepository<Order>();

              var orders = orderRepo.All();
              int countBefore = orders.Count();

              orderRepo.Save(order);

              int countAfter = orders.Count();

              Assert.AreEqual(countAfter, countBefore + 1);
        }
        public void Can_delete()
        {
            var customer = new Customer
            {
                FirstName = "John",
                LastName = "Doe",
            };
            using (var scope = new UnitOfWorkScope())
            {
                new NHRepository<Customer, int>().Add(customer);
                scope.Commit();
            }
            Assert.IsTrue(customer.CustomerID > 0);
            using (var scope = new UnitOfWorkScope())
            {
                var repository = new NHRepository<Customer, int>();
                var savedCustomer = repository.Query.Where(x => x.CustomerID == customer.CustomerID).First();
                repository.Delete(savedCustomer);
                scope.Commit();
            }

            //Making sure customer is deleted
            using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                Customer savedCustomer = null;
                testData.Batch(x => savedCustomer = x.GetCustomerById(customer.CustomerID));
                Assert.IsNull(savedCustomer);
            }
        }
        public void UnitOfWork_Rolledback_When_Containing_TransactionScope_Is_Rolledback()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions =>
                               actions.CreateOrderForCustomer(actions.CreateCustomer()));

                int orderId;
                DateTime oldDate;

                using (var txScope = new TransactionScope(TransactionScopeOption.Required))
                using (var uowScope = new UnitOfWorkScope(IsolationLevel.Serializable))
                {
                    var ordersRepository = new NHRepository<Order>();
                    var order = (from o in ordersRepository
                                 select o).First();

                    oldDate = order.OrderDate;
                    order.OrderDate = DateTime.Now;
                    orderId = order.OrderID;
                    uowScope.Commit();
                    //Note: txScope has not been committed
                }

                using (new UnitOfWorkScope())
                {
                    var ordersRepository = new NHRepository<Order>();
                    var order = (from o in ordersRepository
                                 where o.OrderID == orderId
                                 select o).First();

                    Assert.That(order.OrderDate, Is.EqualTo(oldDate));
                }
            }
        }
        public void Can_lazyload()
        {
            using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                Customer customer = null;
                testData.Batch(x =>
                {
                    customer = x.CreateCustomer();
                    x.CreateOrderForCustomer(customer);
                });

                using (var scope = new UnitOfWorkScope())
                {
                    var savedCustomer = new NHRepository<Customer, int>().Query
                        .Where(x => x.CustomerID == customer.CustomerID)
                        .First();

                    Assert.IsNotNull(savedCustomer);
                    Assert.IsNotNull(savedCustomer.Orders);
                    Assert.IsTrue(savedCustomer.Orders.Count > 0);
                    scope.Commit();
                }
            }
        }
        public void Test_Updating_Money_Amount_Updates_Amount_In_Store_And_Returns_Updated_Figure()
        {
            var newAmount = (decimal) new Random().Next();
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions => actions.CreateMonthlySalesSummaryForSalesPerson(1));

                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository<MonthlySalesSummary>();
                    var report = (from summary in repository
                                  where summary.SalesPersonId == 1
                                  select summary).SingleOrDefault();
                    report.TotalSale.Amount = newAmount;
                    scope.Commit();
                }

                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository<MonthlySalesSummary>();
                    var report = (from summary in repository
                                  where summary.SalesPersonId == 1
                                  select summary).SingleOrDefault();

                    Assert.That(report.TotalSale.Amount, Is.EqualTo(newAmount));
                    scope.Commit();
                }
            }
        }
        public void when_ambient_transaction_is_running_multiple_scopes_work()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions => actions.CreateCustomerInState("LA"));
                using (var ambientScope = new TransactionScope())
                {
                    using (var firstUOW = new UnitOfWorkScope())
                    {
                        var repository = new NHRepository<Customer>();
                        var query = repository.Where(x => x.Address.State == "LA");
                        Assert.That(query.Count(), Is.GreaterThan(0));
                        firstUOW.Commit();
                    }

                    using (var secondUOW = new UnitOfWorkScope())
                    {
                        var repository = new NHRepository<Customer>();
                        repository.Add(new Customer
                        {
                            FirstName = "NHUnitOfWorkTransactionTest",
                            LastName = "Customer",
                            Address = new Address
                            {
                                StreetAddress1 = "This recrd was insertd via a test",
                                City = "Fictional City",
                                State = "LA",
                                ZipCode = "00000"
                            }
                        });
                        secondUOW.Commit();
                    }
                    //Rolling back changes.
                }
            }
        }
        public void when_ambient_transaction_is_running_and_a_previous_scope_rollsback_new_scope_still_works()
        {
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            {
                testData.Batch(actions => actions.CreateCustomer());

                string oldCustomerName;
                var newCustomerName = "NewCustomer" + new Random().Next(0, int.MaxValue);
                var newCustomer = new Customer
                {
                    FirstName = newCustomerName,
                    LastName = "Save",
                    Address = new Address
                    {
                        StreetAddress1 = "This record was inserted via a test",
                        City = "Fictional City",
                        State = "LA",
                        ZipCode = "00000"
                    }
                };

                using (var ambientScope = new TransactionScope())
                {
                    using (var firstUOW = new UnitOfWorkScope())
                    {
                        var customer = new NHRepository<Customer>().First();
                        oldCustomerName = customer.FirstName;
                        customer.FirstName = "Changed";
                    }  //Rollback

                    using (var secondUOW = new UnitOfWorkScope())
                    {

                        new NHRepository<Customer>().Add(newCustomer);
                        secondUOW.Commit();
                    }
                }

                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository<Customer>();
                    Assert.That(repository.First().FirstName, Is.EqualTo(oldCustomerName));
                    Assert.That(repository.Where(x => x.FirstName == newCustomerName).Count(), Is.GreaterThan(0));
                    repository.Attach(newCustomer);
                    repository.Delete(newCustomer);
                    scope.Commit();
                }
            }
        }
        public void When_No_FetchingStrategy_Registered_For_Makes_No_Changes()
        {
            Order order;
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            using (new UnitOfWorkScope())
            {
                testData.Batch(actions =>
                               actions.CreateOrderForCustomer(actions.CreateCustomer()));

                var oredersRepository = new NHRepository<Order>().For<NHRepositoryTests>();
                order = (from o in oredersRepository
                         select o).FirstOrDefault();
            }
            Assert.That(NHibernateUtil.IsInitialized(order.Customer), Is.False);
        }
        public void Test_LoadAllOrdersUsingRepository()
        {
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

              var orderRepository = new NHRepository<Order>();
              var orders = orderRepository.All();
              List<Order> orderList = orders.ToList<Order>();
              Customer c = orderList[0].Customer;
              Employee e = orderList[0].Employee;
              Assert.IsNotNull(c);
              Assert.IsNotNull(e);
              Assert.AreEqual("VINET", c.CustomerId);
              Assert.AreEqual(5, e.EmployeeId);
        }
        public void Test_LoadCustomerALFKIAndAllOrdersUsingRepository()
        {
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

              using (ISession session = NHibernateHelper.OpenSession())
              {
            var customers1 = session.Linq<Customer>().Where(x => x.CustomerId == "ALFKI");

            foreach (Customer c in customers1)
            {
              Customer cc = c;
            }
              }
              var customerRepository = new NHRepository<Customer>();
              var customers = customerRepository.Where(x => x.CustomerId == "ALFKI");
              foreach (Customer c in customers)
              {
            Customer cc = c;
              }
        }
        public void Can_detach()
        {
            using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                Customer customer = null;
                testData.Batch(action => customer = action.CreateCustomer());

                using (var scope = new UnitOfWorkScope())
                {
                    var repository = new NHRepository<Customer, int>();
                    var savedCustomer = repository.Query
                        .Where(x => x.CustomerID == customer.CustomerID)
                        .First();

                    repository.Detach(savedCustomer);
                    savedCustomer.LastName = "Changed"; //This shouldn't be saved since the savedCustomer instance is detached.
                    scope.Commit();
                }

                testData.Session.Refresh(customer);
                Assert.AreNotEqual(customer.LastName, "Changed");
            }
        }
        public void Test_SaveOrderAndCustomerAndEmployeeUsingRepositoryUsingCascadedSaves()
        {
            Order o = new Order();

              Customer c = new Customer();
              o.Customer = c;
              c.CustomerId = GenerateAndReturnARandomCustomerId();
              c.CompanyName = "Some company";

              Employee e = new Employee();
              o.Employee = e;
              e.FirstName = "Dummy";
              e.LastName = "Employee";

              HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
              IRepository<Order> orderRepo = new NHRepository<Order>();
              IRepository<Customer> custRepo = new NHRepository<Customer>();
              IRepository<Employee> empRepo = new NHRepository<Employee>();

              int countOrdersBefore = orderRepo.All().Count();
              int countEmployeesBefore = empRepo.All().Count();
              int countCustomerBefore = custRepo.All().Count();

              orderRepo.Save(o);

              int countOrdersAfter = orderRepo.All().Count();
              int countEmployeesAfter = empRepo.All().Count();
              int countCustomerAfter = custRepo.All().Count();

              Debug.Write(o.OrderId);

              Assert.AreEqual(countOrdersBefore+1,countOrdersAfter);
              Assert.AreEqual(countEmployeesBefore+1,countEmployeesAfter);
              Assert.AreEqual(countCustomerBefore+1,countCustomerAfter);
        }
 public void Lazyloading_should_not_load()
 {
     using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
     {
         Order order = null;
         testData.Batch(x => order = x.CreateOrderForCustomer(x.CreateCustomer()));
         Order savedOrder;
         using (var scope = new UnitOfWorkScope())
         {
             savedOrder = new NHRepository<Order, int>().Query
                 .Where(x => x.OrderID == order.OrderID)
                 .First();
             scope.Commit();
         }
         Assert.IsNotNull(savedOrder);
         Assert.IsFalse(NHibernateUtil.IsInitialized(savedOrder.Customer));
     }
 }
        public void Can_save()
        {
            var customer = new Customer
            {
                FirstName = "Jane",
                LastName = "Doe",
                Address = new Address
                {
                    StreetAddress1 = "123 Main St",
                    City = "Sunset City",
                    State = "LA",
                    ZipCode = "12345"
                }
            };

            using (var scope = new UnitOfWorkScope())
            {
                var repository = new NHRepository<Customer, int>();
                repository.Add(customer);
                scope.Commit();
            }
            Assert.IsTrue(customer.CustomerID > 0);
            using (var testData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                Customer savedCustomer = null;
                testData.Batch(action => savedCustomer = action.GetCustomerById(customer.CustomerID));
                Assert.IsNotNull(savedCustomer);
                Assert.AreEqual(savedCustomer.CustomerID, customer.CustomerID);
            }
        }
        public void When_Calling_CalculateTotal_On_Order_Returns_Valid_With_No_UnitOfWork_Throws()
        {
            Order order;
            using (var testData = new NHTestDataGenerator(Factory.OpenSession()))
            using (new UnitOfWorkScope())
            {
                testData.Batch(actions =>
                               actions.CreateOrderForProducts(actions.CreateProducts(5)));

                var oredersRepository = new NHRepository<Order>();
                order = (from o in oredersRepository
                         select o).FirstOrDefault();
            }
            Assert.Throws<LazyInitializationException>(() => order.CalculateTotal());
        }
Exemple #59
0
        public override void SetUp()
        {
            base.SetUp();
            CreateDatabaseSchema();

            sessionProvider = engine.Resolve<ISessionProvider>();
            repository = new NHRepository<int, ContentItem>(sessionProvider);
        }
        public void Can_eager_fetch_using_fetch()
        {
            using (var tesData = new NHTestData(NHTestUtil.OrdersDomainFactory.OpenSession()))
            {
                Customer customer = null;
                tesData.Batch(x =>
                {
                    var products = x.CreateProducts(10);
                    var order = x.CreateOrderForProducts(products);
                    customer = order.Customer = x.CreateCustomer();
                });

                Customer savedCustomer;
                using (var scope = new UnitOfWorkScope())
                {
                    savedCustomer = new NHRepository<Customer,int>().Query
                        .Where(x => x.CustomerID == customer.CustomerID)
                        .FetchMany(x => x.Orders)
                        .ThenFetchMany(x=>x.Items)
                        .ThenFetch(x=>x.Product)
                        .First();
                    scope.Commit();
                }

                Assert.IsNotNull(savedCustomer);
                Assert.IsTrue(NHibernateUtil.IsInitialized(savedCustomer.Orders));
                foreach (var order in savedCustomer.Orders)
                {
                    Assert.IsTrue(NHibernateUtil.IsInitialized(order.Items));
                    foreach (var item in order.Items)
                    {
                        Assert.IsTrue(NHibernateUtil.IsInitialized(item.Product));
                    }
                }
                //((IEnumerable<Order>)(savedCustomer.Orders)).ForEach(order =>
                //{
                //    Assert.IsTrue(NHibernateUtil.IsInitialized(order.Items));
                //    ((IEnumerable<OrderItem>)(order.Items)).ForEach(item => Assert.IsTrue(NHibernateUtil.IsInitialized(item.Product)));
                //});
            }
        }