Ejemplo n.º 1
0
        public void Can_attach_modified_entity()
        {
            var customer = new Customer
            {
                FirstName = "John",
                LastName = "Doe"
            };

            var context = (OrderEntities) OrdersContextProvider();
            context.AddToCustomers(customer);
            #if EF_1_0
            context.SaveChanges(true);
            #else
            context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
            #endif
            context.Detach(customer);
            context.Dispose();

            using (var scope = new UnitOfWorkScope())
            {
                customer.LastName = "Changed";
                var repository = new EFRepository<Customer>();
                repository.Attach(customer);
                scope.Commit();
            }

            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer savedCustomer = null;
                testData.Batch(x => savedCustomer = x.GetCustomerById(customer.CustomerID));
                Assert.That(savedCustomer, Is.Not.Null);
                Assert.That(savedCustomer.LastName, Is.EqualTo("Changed"));
            }
        }
Ejemplo n.º 2
0
        public void nested_commit_with_seperate_transaction_commits_when_wrapping_scope_rollsback()
        {
            var customer = new Customer {
                FirstName = "Joe", LastName = "Data"
            };
            var order = new Order {
                OrderDate = DateTime.Now, ShipDate = DateTime.Now
            };

            using (var scope = new UnitOfWorkScope())
            {
                new EFRepository <Customer>().Add(customer);
                using (var scope2 = new UnitOfWorkScope(TransactionMode.New))
                {
                    new EFRepository <Order>().Add(order);
                    scope2.Commit();
                }
            } //Rollback

            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer savedCustomer = null;
                Order    savedOrder    = null;
                testData.Batch(actions =>
                {
                    savedCustomer = actions.GetCustomerById(customer.CustomerID);
                    savedOrder    = actions.GetOrderById(order.OrderID);
                });

                Assert.That(savedCustomer, Is.Null);
                Assert.That(savedOrder, Is.Not.Null);
                Assert.That(savedOrder.OrderID, Is.EqualTo(order.OrderID));
            }
        }
        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"));
            });
        }
        protected override ActionResult Update()
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (var scope = new UnitOfWorkScope())
                    {
                        Localization currentLocalization = _repository.Get(Convert.ToInt32(GridModel.Id));

                        if (currentLocalization == null)
                        {
                            throw new DuplicateKeyException();
                        }
                        currentLocalization.SetValue(GridModel.Value);


                        _repository.Update(currentLocalization);
                        scope.Commit();
                    }
                    return(Json(GridModel));
                }
            }
            catch (DuplicateKeyException)
            {
                ModelState.AddModelError(string.Empty, string.Format("This type of Localization {0} already exists in the system.", GridModel.Key));
            }
            throw CreateModelException(GridModel);
        }
        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);
                               });
        }
Ejemplo n.º 6
0
        public void Can_lazyload()
        {
            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer customer = null;
                testData.Batch(x =>
                {
                    customer = x.CreateCustomer();
                    x.CreateOrderForCustomer(customer);
                });

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

                    Assert.That(savedCustomer, Is.Not.Null);
                    Assert.That(savedCustomer.Orders, Is.Not.Null);
                    Assert.DoesNotThrow(savedCustomer.Orders.Load);
                    Assert.That(savedCustomer.Orders.Count, Is.GreaterThan(0));
                    scope.Commit();
                }
            }
        }
Ejemplo n.º 7
0
        public void Can_query_multiple_databases()
        {
            using (var ordersTestData = new EFTestData(OrdersContextProvider()))
                using (var hrTestData = new EFTestData(HRContextProvider()))
                {
                    Customer    customer    = null;
                    SalesPerson salesPerson = null;
                    ordersTestData.Batch(x => customer = x.CreateCustomer());
                    hrTestData.Batch(x => salesPerson  = x.CreateSalesPerson());

                    //Suprisingly this does not enlist in a DTC transaction. EF is able to re-use the same connection
                    //since both ObjectContext connect to the same database instance.
                    using (var scope = new UnitOfWorkScope())
                    {
                        var savedCustomer = new EFRepository <Customer>()
                                            .Where(x => x.CustomerID == customer.CustomerID)
                                            .First();

                        var savedPerson = new EFRepository <SalesPerson>()
                                          .Where(x => x.Id == salesPerson.Id)
                                          .First();

                        Assert.That(savedCustomer, Is.Not.Null);
                        Assert.That(savedPerson, Is.Not.Null);
                        scope.Commit();
                    }
                }
        }
Ejemplo n.º 8
0
        //[CustomAuthorize(AuthorizedRoles = new[] { Roles.MunicipalityAdministrator, Roles.ZelsAdministrator })]
        public JsonResult ResetPassword(int userId)
        {
            User user;

            //SendResetPasswordConfirmationViewModel sendResetPasswordConfirmationViewModel;

            using (var scope = new UnitOfWorkScope())
            {
                user = _userRepository.Get(userId);
                if (user == null)
                {
                    throw new JsonException("Корисникот не е пронајден во системот.");
                }

                string password    = new PasswordGenerator().Generate();
                string passwordEnc = password.Md5String();

                user.SetPassword(passwordEnc);

                //sendResetPasswordConfirmationViewModel = new SendResetPasswordConfirmationViewModel
                //{
                //    FullName = user.FullName,
                //    Password = password
                //};

                _userRepository.Update(user);
                scope.Commit();
            }

            //sendResetPasswordConfirmationViewModel.To = user.UserName;
            //MailService.SendResetPasswordConfirmation(sendResetPasswordConfirmationViewModel);

            return(Json(true));
        }
Ejemplo n.º 9
0
        public void Can_attach_modified_entity()
        {
            var customer = new Customer
            {
                FirstName = "John",
                LastName  = "Doe"
            };

            var context = (OrderEntities)OrdersContextProvider();

            context.AddToCustomers(customer);
#if EF_1_0
            context.SaveChanges(true);
#else
            context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
#endif
            context.Detach(customer);
            context.Dispose();

            using (var scope = new UnitOfWorkScope())
            {
                customer.LastName = "Changed";
                var repository = new EFRepository <Customer>();
                repository.Attach(customer);
                scope.Commit();
            }

            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer savedCustomer = null;
                testData.Batch(x => savedCustomer = x.GetCustomerById(customer.CustomerID));
                Assert.That(savedCustomer, Is.Not.Null);
                Assert.That(savedCustomer.LastName, Is.EqualTo("Changed"));
            }
        }
Ejemplo n.º 10
0
 public T GetById(Guid entityId)
 {
     using (var unitOfWork = new UnitOfWorkScope <ShoppingCartContext>(UnitOfWorkScopePurpose.Reading))
     {
         return(unitOfWork.DbContext.Set <T>().SingleOrDefault(x => x.Id == entityId));
     }
 }
Ejemplo n.º 11
0
public static Entities.Car GetCar(int id)
{
    using (var uow = new UnitOfWorkScope<CarsContext>(UnitOfWorkScopePurpose.Reading))
    {
        return uow.DbContext.Cars.Single(c => c.CarId == id);
    }
}
Ejemplo n.º 12
0
 public int CountAll()
 {
     using (var unitOfWork = new UnitOfWorkScope <ShoppingCartContext>(UnitOfWorkScopePurpose.Reading))
     {
         return(unitOfWork.DbContext.Set <T>().AsExpandable().Count());
     }
 }
Ejemplo n.º 13
0
        public void Save_Updates_Existing_Order_Record()
        {
            int orderIDRetrieved;
            var updatedDate = DateTime.Now;

            using (var testData = new EFDataGenerator(new TestModel()))
            {
                testData.Batch(actions => actions.CreateOrderForCustomer(actions.CreateCustomer()));

                using (var scope = new UnitOfWorkScope())
                {
                    var order = new EFRepository <Order>().First();
                    Assert.That(order, Is.Not.Null);
                    orderIDRetrieved = order.OrderID;
                    order.OrderDate  = updatedDate;

                    scope.Commit();
                }

                using (new UnitOfWorkScope())
                {
                    var orderRepository = new EFRepository <Order>();
                    var order           = (from o in orderRepository
                                           where o.OrderID == orderIDRetrieved
                                           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));
                }
            }
        }
Ejemplo n.º 14
0
        public void UnitOfWork_is_rolledback_when_containing_TransactionScope_is_rolledback()
        {
            using (var testData = new EFDataGenerator(new TestModel()))
            {
                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 EFRepository <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 (var uowScope = new UnitOfWorkScope())
                {
                    var ordersRepository = new EFRepository <Order>();
                    var order            = (from o in ordersRepository
                                            where o.OrderID == orderId
                                            select o).First();

                    Assert.That(order.OrderDate, Is.EqualTo(oldDate));
                }
            }
        }
Ejemplo n.º 15
0
 public int Count(ISpecification <T> specification)
 {
     using (var unitOfWork = new UnitOfWorkScope <ShoppingCartContext>(UnitOfWorkScopePurpose.Reading))
     {
         return(unitOfWork.DbContext.Set <T>().AsExpandable().Where(specification.Expression).Count());
     }
 }
Ejemplo n.º 16
0
        public void UnitOfWork_Is_Rolledback_When_Containing_TransactionScope_Is_Rolledback()
        {
            using (var testData = new LinqToSqlDataGenerator(new TestDataDataContext()))
            {
                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 LinqToSqlRepository <Order>();
                        var order            = (from o in ordersRepository
                                                select o).First();

                        oldDate         = order.OrderDate;
                        order.OrderDate = DateTime.Now;
                        orderId         = order.OrderID;
                        uowScope.Commit();
                    }

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

                    Assert.That(order.OrderDate, Is.EqualTo(oldDate));
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Промена на податоци за POS
        /// </summary>
        /// <returns></returns>
        protected override ActionResult Update()
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (var scope = new UnitOfWorkScope())
                    {
                        var pos = _posRepository.Get(GridModel.Id);
                        if (pos == null)
                        {
                            throw new Exception("Корисникот не постои");
                        }
                        pos.SetName(GridModel.PosName);
                        pos.PrimaryContact = GridModel.PrimaryContact;
                        pos.Phone          = GridModel.Phone;
                        pos.SetIsActive(GridModel.IsActive);

                        _posRepository.Update(pos);
                        scope.Commit();
                    }

                    return(Json(GridModel));
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError(string.Empty, string.Format("Грешка за POS {0} ", GridModel.PosName));
            }

            throw CreateModelException(GridModel);
        }
Ejemplo n.º 18
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            TransactionalFlush();

            if (_transaction != null)
            {
                _transaction.Dispose();
                _transaction = null;
            }
            //if (_session != null)
            //{
            //    _session.Dispose();
            //}
            _session = null;

            _factory.DisposeUnitOfWork();
            UnitOfWorkScope.DisposeUnitOfWork();

            _disposed = true;
        }
Ejemplo n.º 19
0
        public void Can_save()
        {
            var customer = new Customer
            {
                FirstName      = "Jane",
                LastName       = "Doe",
                StreetAddress1 = "123 Main St",
                City           = "Sunset City",
                State          = "LA",
                ZipCode        = "12345"
            };

            using (var scope = new UnitOfWorkScope())
            {
                var repository = new EFRepository <Customer>();
                repository.Add(customer);
                scope.Commit();
            }
            Assert.That(customer.CustomerID, Is.GreaterThan(0));
            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer savedCustomer = null;
                testData.Batch(action => savedCustomer = action.GetCustomerById(customer.CustomerID));
                Assert.That(savedCustomer, Is.Not.Null);
                Assert.That(savedCustomer.CustomerID, Is.EqualTo(customer.CustomerID));
            }
        }
Ejemplo n.º 20
0
 public IList <T> Get()
 {
     using (var unitOfWork = new UnitOfWorkScope <ShoppingCartContext>(UnitOfWorkScopePurpose.Reading))
     {
         return(unitOfWork.DbContext.Set <T>().ToList());
     }
 }
Ejemplo n.º 21
0
        public void Can_delete()
        {
            var customer = new Customer
            {
                FirstName = "John",
                LastName  = "Doe",
            };

            using (var scope = new UnitOfWorkScope())
            {
                new EFRepository <Customer>().Add(customer);
                scope.Commit();
            }
            Assert.That(customer.CustomerID, Is.GreaterThan(0));
            using (var scope = new UnitOfWorkScope())
            {
                var repository    = new EFRepository <Customer>();
                var savedCustomer = repository.Where(x => x.CustomerID == customer.CustomerID).First();
                repository.Delete(savedCustomer);
                scope.Commit();
            }

            //Making sure customer is deleted
            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer savedCustomer = null;
                testData.Batch(x => savedCustomer = x.GetCustomerById(customer.CustomerID));
                Assert.That(savedCustomer, Is.Null);
            }
        }
Ejemplo n.º 22
0
        public void UpdateFirstCar()
        {
            int carId = 4;

            using (var ts = new TransactionScope())
            {
                using (var uow = new UnitOfWorkScope <CarsContext>(UnitOfWorkScopePurpose.Writing))
                {
                    Car c = SharedQueries.GetCar(carId);
                    c.Color = "White";
                    uow.SaveChanges();
                }

                using (var ctx = new CarsContext())
                {
                    Assert.AreEqual("White",
                                    ctx.Cars.Single(c => c.CarId == carId).Color);
                }
            }

            using (var ctx = new CarsContext())
            {
                Assert.AreEqual("Red",
                                ctx.Cars.Single(c => c.CarId == carId).Color);
            }
        }
Ejemplo n.º 23
0
        public void can_rollback_multipe_db_operations()
        {
            var customer = new Customer {
                FirstName = "John", LastName = "Doe"
            };
            var salesPerson = new SalesPerson {
                FirstName = "Jane", LastName = "Doe", SalesQuota = 2000
            };

            using (var scope = new UnitOfWorkScope())
            {
                new EFRepository <Customer>().Add(customer);
                new EFRepository <SalesPerson>().Add(salesPerson);
            }// Rolllback

            using (var ordersTestData = new EFTestData(OrdersContextProvider()))
                using (var hrTestData = new EFTestData(HRContextProvider()))
                {
                    Customer    savedCustomer    = null;
                    SalesPerson savedSalesPerson = null;
                    ordersTestData.Batch(action => savedCustomer = action.GetCustomerById(customer.CustomerID));
                    hrTestData.Batch(action => savedSalesPerson  = action.GetSalesPersonById(salesPerson.Id));

                    Assert.That(savedCustomer, Is.Null);
                    Assert.That(savedSalesPerson, Is.Null);
                }
        }
        public void Can_eager_fetch_many()
        {
            var testData = new EFTestData(Context);

            Customer customer = null;
            Customer savedCustomer = null;
            testData.Batch(x =>
            {
                customer = x.CreateCustomer();
                var order = x.CreateOrderForCustomer(customer);
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
            });

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

            Assert.IsNotNull(savedCustomer);
            Assert.IsNotNull(savedCustomer.Orders);
            savedCustomer.Orders.ForEach(order =>
            {
                Assert.IsNotNull(order.OrderItems);
                order.OrderItems.ForEach(orderItem => Assert.IsNotNull(orderItem.Product));
            });
        }
Ejemplo n.º 25
0
        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"));
            });
        }
Ejemplo n.º 26
0
        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();
                }
            }
        }
Ejemplo n.º 27
0
        public void Can_eager_fetch_using_for()
        {
            Locator.Stub(x => x.GetAllInstances <IFetchingStrategy <Customer, EFRepositoryEagerFetchingTests> >())
            .Return(new[] { new FetchingStrategy() });

            var      testData      = new EFTestData(Context);
            Customer customer      = null;
            Customer savedCustomer = null;

            testData.Batch(x =>
            {
                customer  = x.CreateCustomer();
                var order = x.CreateOrderForCustomer(customer);
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
            });

            using (var scope = new UnitOfWorkScope())
            {
                savedCustomer = new EFRepository <Customer>()
                                .For <EFRepositoryEagerFetchingTests>()
                                .Where(x => x.CustomerID == customer.CustomerID)
                                .SingleOrDefault();
                scope.Commit();
            }

            Assert.NotNull(savedCustomer);
            Assert.NotNull(savedCustomer.Orders);
            savedCustomer.Orders.ForEach(order =>
            {
                Assert.NotNull(order.OrderItems);
                order.OrderItems.ForEach(orderItem => Assert.NotNull(orderItem.Product));
            });
        }
Ejemplo n.º 28
0
        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);
            });
        }
Ejemplo n.º 29
0
        protected void btnGenerate_Click(object sender, DirectEventArgs e)
        {
            using (var unitOfWork = new UnitOfWorkScope(true))
            {
                BusinessLogic.GenerateBillFacade.GenerateReceivable(dtGenerationDate.SelectedDate);
            }
            using (var unitOfWork = new UnitOfWorkScope(true))
            {

                LoanAccount.UpdateLoanAccountStatus(dtGenerationDate.SelectedDate);
            }
            using (var unitOfWork = new UnitOfWorkScope(true))
            {
                DemandLetter.UpdateDemandLetterStatus(dtGenerationDate.SelectedDate);
            }
            using (var unitOfWork = new UnitOfWorkScope(true))
            {
                Customer.UpdateCustomerStatus(dtGenerationDate.SelectedDate);
            }
            using (var unitOfWork = new UnitOfWorkScope(true))
            {

                FinancialProduct.UpdateStatus();

            }
        }
        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");
            }
        }
        public void can_commit_multiple_db_operations()
        {
            var customer = new Customer { FirstName = "John", LastName = "Doe" };
            var salesPerson = new SalesPerson { FirstName = "Jane", LastName = "Doe", SalesQuota = 2000 };

            using (var scope = new UnitOfWorkScope())
            {
                new EFRepository<Customer>().Add(customer);
                new EFRepository<SalesPerson>().Add(salesPerson);
                scope.Commit();
            }

            using (var ordersTestData = new EFTestData(OrdersContextProvider()))
            using (var hrTestData = new EFTestData(HRContextProvider()))
            {
                Customer savedCustomer = null;
                SalesPerson savedSalesPerson = null;
                ordersTestData.Batch(action => savedCustomer = action.GetCustomerById(customer.CustomerID));
                hrTestData.Batch(action => savedSalesPerson = action.GetSalesPersonById(salesPerson.Id));

                Assert.That(savedCustomer, Is.Not.Null);
                Assert.That(savedSalesPerson, Is.Not.Null);
                Assert.That(savedCustomer.CustomerID, Is.EqualTo(customer.CustomerID));
                Assert.That(savedSalesPerson.Id, Is.EqualTo(salesPerson.Id));
            }
        }
Ejemplo n.º 32
0
        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 bool ChangeToZero(int loanid)
 {
     using (var unitOfWork = new UnitOfWorkScope(true))
     {
         return ChangeInterestTypeFacade.SaveInterestType(loanid, InterestType.ZeroInterestTYpe, 0);
     }
 }
Ejemplo n.º 34
0
        public void TestInitialize()
        {
            _scope = new UnitOfWorkScope(new EFUnitOfWorkFactory(() => new DataContainer()));

            basicInfoDomainServiceObjects = new BasicInfoDomainServiceObjectsContainer(_scope);

            OrderConfigurator orderConfigurator = null;
            //new OrderConfigurator(new OrderStateFactory(new FuelReportDomainService(new FuelReportRepository(_scope),
            //    new VoyageDomainService( new VoyageRepository(_scope)),new InventoryOperationDomainService(new InventoryOperationRepository(_scope)),
            //    new InventoryOperationRepository(_scope),new InventoryOperationFactory()   ),new InvoiceDomainService() ));

            var client = new WebClientHelper(new HttpClient());
            _orderRepository = new OrderRepository(_scope, orderConfigurator, new EFRepository<OrderItem>(_scope));
            _orderRepository.GetAll();
            _tr = new TransactionScope();

            var hostAdapter = new ExternalHostAddressHelper();

            _target = new GoodFacadeService(
                new GoodDomainService(
                    new GoodAntiCorruptionAdapter(
                        new GoodAntiCorruptionServiceWrapper
                    (client, hostAdapter),
                    new GoodAntiCorruptionMapper()),
                    new EFRepository<Good>(_scope),
                    basicInfoDomainServiceObjects.CompanyDomainService, new EFRepository<GoodUnit>(_scope)),
                    new GoodToGoodDtoMapper(new CompanyGoodUnitToGoodUnitDtoMapper()));
        }
Ejemplo n.º 35
0
        public void rollback_does_not_rollback_supressed_scope()
        {
            var customer = new Customer {
                FirstName = "Joe", LastName = "Data"
            };
            var order = new Order {
                OrderDate = DateTime.Now, ShipDate = DateTime.Now
            };

            using (var scope = new UnitOfWorkScope())
            {
                new EFRepository <Customer>().Add(customer);
                using (var scope2 = new UnitOfWorkScope(TransactionMode.Supress))
                {
                    new EFRepository <Order>().Add(order);
                    scope2.Commit();
                }
            } //Rollback.

            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer savedCustomer = null;
                Order    savedOrder    = null;
                testData.Batch(actions =>
                {
                    savedCustomer = actions.GetCustomerById(customer.CustomerID);
                    savedOrder    = actions.GetOrderById(order.OrderID);
                });

                Assert.That(savedCustomer, Is.Null);
                Assert.That(savedOrder, Is.Not.Null);
            }
        }
Ejemplo n.º 36
0
        public void PerformActivity(Guid actorId, Guid flowId, IDictionary <string, object> attributeValues = null, string transitionName = null)
        {
            using (var scope = new UnitOfWorkScope(autoCommit: false))
            {
                try
                {
                    var organizationApplication = ServiceLocator.Current.GetInstance <IOrganizationApplication>();
                    var actor = organizationApplication.FindActor(actorId);

                    var flowRepository = ServiceLocator.Current.GetInstance <IRepository <Flow> >();
                    var flow           =
                        flowRepository.With(w => w.Node)
                        .With(w => w.Parent)
                        .With(w => w.AttributeInstances)
                        .Single(s => s.Id == flowId);

                    var processInstanceRepository = ServiceLocator.Current.GetInstance <IRepository <ProcessInstance> >();
                    var processInstance           = processInstanceRepository.Get(flow.ProcessInstanceId);

                    var processDefinitionRepository     = ServiceLocator.Current.GetInstance <IRepository <ProcessDefinition> >();
                    ProcessDefinition processDefinition = processDefinitionRepository.With(w => w.Nodes).Get(processInstance.ProcessDefinitionId);

                    ExecutionContext executionContext = new ExecutionContext(actor, processDefinition, processInstance, flow);
                    executionContext.PerformActivity(attributeValues);

                    scope.Commit();
                }
                catch
                {
                    throw;
                }
            }
        }
Ejemplo n.º 37
0
        protected override ActionResult Add()
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (var scope = new UnitOfWorkScope())
                    {
                        Localization localization = _repository.GetLocalizationByKey(GridModel.Key);
                        if (localization != null)
                        {
                            throw new DuplicateKeyException();
                        }

                        localization = new Localization(GridModel.Key, GridModel.Value, GridModel.JavaScript, GridModel.Language);

                        _repository.Save(localization);
                        scope.Commit();
                    }
                    return(Json(GridModel));
                }
            }
            catch (DuplicateKeyException)
            {
                ModelState.AddModelError(string.Empty, string.Format("localization with name {0} already exists in the system.", GridModel.Key));
            }

            throw CreateModelException(GridModel);
        }
Ejemplo n.º 38
0
        public ActionResult Confirmation(RegistrationConfirmationViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (var scope = new UnitOfWorkScope())
                    {
                        User user = _repository.GetUserByUsername(model.UserName);
                        if (user.UserName != model.UserName || user.RegistrationCode != model.Code)
                        {
                            ModelState.AddModelError("UserName", "Невалидно корисничко име или код!");
                        }
                        else
                        {
                            user.IsActive = true;
                            _repository.Update(user);
                            scope.Commit();

                            CreateAuthTicket(user, true);
                            return(Json(true));
                        }
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, "Во моментов системот има технички проблеми.<br/>Обидете се повторно за некоја минута");
                    Log.Error(ex);
                }
            }
            throw base.CreateModelException(model);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Додава нова Мастер Админ
        /// </summary>
        /// <returns></returns>
        protected override ActionResult Add()
        {
            try
            {
                if (ModelState.IsValid)
                {
                    PublicUser newUser;
                    //SendWelcomeEmailToUserViewModel sendWelcomeEmailToUserViewModel;
                    using (var scope = new UnitOfWorkScope())
                    {
                        var user = _userRepository.GetUserByUsername(GridModel.UserName);
                        if (user != null)
                        {
                            throw new DuplicateKeyException();
                        }

                        //Generate the Password
                        string password    = new PasswordGenerator().Generate();
                        string passwordEnc = password.Md5String();

                        //Create new User
                        var lang = _langRepository.Get(GridModel.PreferedLanguage);

                        newUser = new PublicUser(GridModel.UserName, passwordEnc, GridModel.FirstName, GridModel.LastName, lang);
                        //newUser.AddToPos(pos);
                        newUser.IsActive = GridModel.IsActive;
                        var role = _roleRepository.GetRoleByName(Roles.Admin);
                        newUser.AddToRole(role);



                        //Get the Pos
                        //int posId = Convert.ToInt32(GridModel.Pos);
                        //Pos pos = _posRepository.Get(posId);
                        //newUser.AddToPos(pos);

                        //sendWelcomeEmailToUserViewModel = new SendWelcomeEmailToUserViewModel
                        //{
                        //    FullName = newUser.FullName,
                        //    Password = password
                        //};

                        //Save It
                        _publicUserRepository.Save(newUser);
                        scope.Commit();
                    }

                    ////Send Welcome email to created administrator
                    //sendWelcomeEmailToUserViewModel.To = newUser.UserName;
                    //MailService.SendWelcomeEmailToUser(sendWelcomeEmailToUserViewModel);

                    return(Json(GridModel));
                }
            }
            catch (DuplicateKeyException)
            {
                ModelState.AddModelError(string.Empty, string.Format("Корисникот со корисничко име {0} веќе постои во системот.", GridModel.UserName));
            }
            throw CreateModelException(GridModel);
        }
Ejemplo n.º 40
0
        public ActionResult ForgotPasswordConfirmation(ForgotPasswordConfirmationViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    User user;
                    using (var scope = new UnitOfWorkScope())
                    {
                        user = _repository.GetAll().SingleOrDefault(x => x.RegistrationCode == model.UserName);
                        if (user == null)
                        {
                            throw new JsonException("Корисникот не е пронајден во системот.");
                        }
                        user.SetPassword(model.PasswordNew.Md5String());
                        _repository.Update(user);
                        scope.Commit();
                    }
                    return(Json(true));
                }
                catch (Exception ex)
                {
                    if (ex is JsonException)
                    {
                        throw ex;
                    }

                    ModelState.AddModelError(string.Empty,
                                             "Во моментов системот има технички проблеми.<br/>Обидете се повторно за некоја минута");
                    Log.Error(ex);
                }
            }

            throw base.CreateModelException(model);
        }
Ejemplo n.º 41
0
        public void Can_eager_fetch_many()
        {
            var testData = new EFTestData(Context);

            Customer customer      = null;
            Customer savedCustomer = null;

            testData.Batch(x =>
            {
                customer  = x.CreateCustomer();
                var order = x.CreateOrderForCustomer(customer);
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
                order.OrderItems.Add(x.CreateOrderItem(item => item.Order = order));
            });

            using (var scope = new UnitOfWorkScope())
            {
                savedCustomer = new EFRepository <Customer>()
                                .FetchMany(x => x.Orders)
                                .ThenFetchMany(x => x.OrderItems)
                                .ThenFetch(x => x.Product)
                                .Where(x => x.CustomerID == customer.CustomerID)
                                .SingleOrDefault();
                scope.Commit();
            }

            Assert.NotNull(savedCustomer);
            Assert.NotNull(savedCustomer.Orders);
            savedCustomer.Orders.ForEach(order =>
            {
                Assert.NotNull(order.OrderItems);
                order.OrderItems.ForEach(orderItem => Assert.NotNull(orderItem.Product));
            });
        }
Ejemplo n.º 42
0
 public virtual void ChangePassword(Guid id, string oldPassword, string newPassword)
 {
     using (var scope = new UnitOfWorkScope())
     {
         _userAccountService.ChangePassword(id,oldPassword,newPassword);
         scope.Commit();
     }
 }
Ejemplo n.º 43
0
 public void CancelVerification(string key, out bool accountClosed)
 {
     using (var scope = new UnitOfWorkScope())
     {
         _userAccountService.CancelVerification(key,out accountClosed);
         scope.Commit();
     }
 }
Ejemplo n.º 44
0
        public void TestInitialize()
        {
            _scope = new UnitOfWorkScope(new EFUnitOfWorkFactory(() => new DataContainer()));

            _orderRepository = null;//new OrderRepository(_scope, new OrderConfigurator(new StateFactory(new )), new EFRepository<OrderItem>(_scope));
            _orderRepository.GetAll();

            _target = new OrderDomainService(_orderRepository);
        }
 protected void btnDeactivate_Click(object sender, DirectEventArgs e)
 {
     FinancialProductForm form = this.CreateOrRetrieve<FinancialProductForm>();
     using (var unitOfWork = new UnitOfWorkScope(true))
     {
         ProductStatu status = ProductStatu.ChangeStatus(form.FinancialProductId, ProductStatusType.InactiveType, DateTime.Now);
         EnableValidActivity(status);
     }
 }
Ejemplo n.º 46
0
 public bool ChangePasswordFromResetKey(string key, string newPassword, out NhUserAccount account)
 {
     bool success;
     using (var scope = new UnitOfWorkScope())
     {
         success=_userAccountService.ChangePasswordFromResetKey(key,newPassword,out account);
         scope.Commit();
     }
     return success;
 }
        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            var today = DateTime.Now;

            using (var unitOfWork = new UnitOfWorkScope())
            {
                LoanRestructureForm form = this.CreateOrRetrieve<LoanRestructureForm>();
                form.SaveChangeIcmAmortizationSchedule(today);
            }
        }
 public bool ChangeToFixed(int loanid)
 {
     decimal amount = 0;
     if (string.IsNullOrWhiteSpace(txtInterest.Text) == false)
         amount = decimal.Parse(txtInterest.Text);
     using (var unitOfWork = new UnitOfWorkScope(true))
     {
         return ChangeInterestTypeFacade.SaveInterestType(loanid, InterestType.FixedInterestTYpe, amount);
     }
 }
 protected void btnSave_Click(object sender, DirectEventArgs e)
 {
     using (var unitOfWork = new UnitOfWorkScope(true))
     {
         int id = int.Parse(this.RecordID.Text);
         AssetType asset = ObjectContext.AssetTypes.SingleOrDefault(entity => entity.Id == id);
         asset.Name = this.txtName.Text;
         asset.IsAppraisableIndicator = this.radTrue.Checked;
     }
 }
Ejemplo n.º 50
0
        public virtual void AddUsersToRoles(List<Guid> userId, List<string> roleName)
        {
            if (userId == null || userId.Count == 0 || roleName == null || roleName.Count == 0)
                return;
            StringBuilder message=new StringBuilder();
            var users = _userRepository.Query.Where(x => userId.Contains(x.ID)).ToList();
            var roles = _roleRepository.Query.Where(x => roleName.Contains(x.Name)).ToList();
            foreach (var userEntity in users)
            {
                if (userEntity.Roles != null && userEntity.Roles.Any())
                {
                    var newRoles = roles.Except(userEntity.Roles);

                    foreach (var role in newRoles)
                        userEntity.Roles.Add(role);
                    if(newRoles!=null && newRoles.Count()>0)
                        message.AppendFormat("User {0} is added to role(s) {1}.",userEntity.Username,string.Join(",", newRoles.Select(x => x.Name)));
                }
                else
                {
                    foreach (var role in roles)
                        userEntity.Roles.Add(role);
                    if(roles!=null && roles.Count()>0)
                        message.AppendFormat("User {0} is added to role(s) {1}.",userEntity.Username,string.Join(",", roles.Select(x => x.Name)));
                }
                using (var scope = new UnitOfWorkScope())
                {
                    _userRepository.Update(userEntity);
                    scope.Commit();
                }
            }
            foreach (var uid in userId)
            {
                if (!users.Any(u => u.ID == uid))
                {
                    var user = _userRepository.Query.Where(x => x.ID == uid).SingleOrDefault();
                    if (user != null)
                    {
                        user.Roles = roles;
                        using (var scope = new UnitOfWorkScope())
                        {
                            _userRepository.Update(user);
                            scope.Commit();
                        }
                        if(roles!=null && roles.Count()>0)
                            message.AppendFormat("User {0} is added to role(s) {1}.",user.Username,string.Join(",", roles.Select(x => x.Name)));
                    }
                }
            }
            if (message.Length > 0)
            {
                ActivityLog item = new ActivityLog(ActivityType.AddUserToRole.ToString(), message.ToString());
                _activityLogService.Add(item);
            }
        }
Ejemplo n.º 51
0
        //BUTTON CLICK EVENT HANDLERS
        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            int selectedDemandLetterId = int.Parse(hdnDemandLetterId.Text);

            using (var scope = new UnitOfWorkScope(true))
            {
                var demandLetter = ObjectContext.DemandLetters.SingleOrDefault(entity => entity.Id == selectedDemandLetterId);

                demandLetter.DatePromisedToPay = dfDatePromiseToPay.SelectedDate;
                demandLetter.CurrentStatus.Remarks = txtRemarks.Text;
            }
        }
Ejemplo n.º 52
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);
            }
        }
Ejemplo n.º 53
0
        //public virtual bool Exists(string name)
        //{
        //    if (string.IsNullOrEmpty(name))
        //        throw new ArgumentNullException("name");
        //    int count = _repository.Query.Where(x => x.Name == name.Trim()).Count();
        //    return count > 0 ? true : false;
        //}
        /// <summary>
        /// Adds a item
        /// </summary>
        /// <param name="item">item</param>
        public virtual void Add(ActivityLog item)
        {
            if (item == null)
                throw new ArgumentNullException("item");
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Add(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityInserted(item);
        }
        /// <summary>
        /// Gets for entity.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        public IList<AuditChangeLog> GetAllAuditLogsForEntity(string guid)
        {
            IList<AuditChangeLog> auditLogs = new List<AuditChangeLog>();
            using(var scope = new UnitOfWorkScope())
            {
                var repo = scope.GetRepositoy<AuditChangeLog>();

                string query = string.Format("from AuditChangeLog  where Entity.Guid='{0}'", guid);
                auditLogs = repo.Query(query).Cast<AuditChangeLog>().ToList();
            }

            return auditLogs;
        }
Ejemplo n.º 55
0
        static void Main(string[] args)
        {
            using (var unitOfWork = new UnitOfWorkScope(true))
            {
                WriteLog("Generation of receivables started.");
              //  GenerateBill.Generate(DateTime.Now);
                GenerateBillFacade.GenerateReceivable(DateTime.Today);
                WriteLog("Generation of receivables ended.");
            }

            using (var unitOfWork = new UnitOfWorkScope(true))
            {
                WriteLog("Updating status of financial product started.");
                FinancialProduct.UpdateStatus();
                WriteLog("Updating status of financial product ended.");
            }

            using (var unitOfWork = new UnitOfWorkScope(true))
            {
                ///If day difference between lastpaymentdate to today is greater than 3 months, loan account status
                ///must be changed to delinquent
                ///or if 3 months of no payment since loan release date, loan account status must also be changed to
                /// delinquent
                WriteLog("Updating status of loan account started.");
                LoanAccount.UpdateLoanAccountStatus(DateTime.Today);
                WriteLog("Updating status of loan account ended.");
            }
            using (var unitOfWork = new UnitOfWorkScope(true))
            {
               ///Create First Demand Letter if loan account is delinquent and has no existing
               ///demand letter for that loan account, also, set the status to Require First Demand Letter
               ///else if demand letter already exists -> if day difference between date today and promise
               ///to  pay date, change status to Require Final Demand Letter
                WriteLog("Updating status of demand letter started.");
                DemandLetter.UpdateDemandLetterStatus(DateTime.Today);
                WriteLog("Updating status of demand letter ended.");

            }

            using (var unitOfWork = new UnitOfWorkScope(true))
            {
                ///Deliquent -> Active If that customer no longer has an overdue account
                ///Subprime -> Active If customer has no under litigation account && no deliquent account
                ///Subprime -> Deliquent Active If customer has no under litigation account but has deliquent account
                ///Active -> Deliquent if customer has no under litigation account but has deliquent account
                WriteLog("Updating status of customer started.");
                Customer.UpdateCustomerStatus(DateTime.Now);
                WriteLog("Updating status of customer ended.");

            }
        }
        public BasicInfoDomainServiceObjectsContainer(UnitOfWorkScope unitOfWorkScope)
        {
            this.UnitOfWorkScope = unitOfWorkScope;

            this.CurrencyRepository = new EFRepository<Currency>(this.UnitOfWorkScope);

            this.CurrencyDomainService = new CurrencyDomainService(this.CurrencyRepository);

            this.VoyageDomainService = new VoyageDomainService(new VoyageRepository(this.UnitOfWorkScope), new FuelReportRepository(this.UnitOfWorkScope, new FuelReportConfigurator(new FuelReportStateFactory(),null,null)));

            this.VoyageLogDomainService = new VoyageLogDomainService(new VoyageLogRepository(this.UnitOfWorkScope));

            this.ClientHelper = new WebClientHelper(new HttpClient());
            this.HostAddressHelper = new ExternalHostAddressHelper();

            this.WorkflowLogRepository = new WorkflowLogRepository(this.UnitOfWorkScope);

            //this.InventoryOperationNotifier = new InventoryOperationNotifier();
            this.InventoryOperationNotifier = null;

            this.VesselDomainService = new VesselInCompanyDomainService(
                new VesselInCompanyRepository(this.UnitOfWorkScope, null), new VoyageRepository(this.UnitOfWorkScope));

            this.CompanyDomainService = new CompanyDomainService(
                new CompanyAntiCorruptionAdapter(
                    new CompanyAntiCorruptionServiceWrapper(this.ClientHelper, this.HostAddressHelper),
                    new CompanyAntiCorruptionMapper()),
                new CompanyRepository(this.UnitOfWorkScope));

            this.GoodDomainService = new GoodDomainService(
               new GoodAntiCorruptionAdapter(
                   new GoodAntiCorruptionServiceWrapper(this.ClientHelper, this.HostAddressHelper),
                   new GoodAntiCorruptionMapper()),
               new EFRepository<Good>(this.UnitOfWorkScope),
               this.CompanyDomainService, new EFRepository<GoodUnit>(this.UnitOfWorkScope));

            this.TankDomainService = new TankDomainService(new EFRepository<Tank>(this.UnitOfWorkScope));

            this.GoodUnitDomainService = new GoodUnitDomainService(
                new BaseAntiCorruptionAdapter<GoodUnit, GoodUnitDto>(
                    new BaseAntiCorruptionServiceWrapper<GoodUnitDto>(this.ClientHelper),
                    new BaseAntiCorruptionMapper<GoodUnit, GoodUnitDto>()),
                new EFRepository<GoodUnit>(this.UnitOfWorkScope));

            this.WorkflowRepository = new WorkflowRepository(this.UnitOfWorkScope);
        }
Ejemplo n.º 57
0
        public virtual bool Delete(Guid id)
        {
            if (id == default(Guid))
                throw new ArgumentNullException("id");
            ActivityLog item = _repository.Query.FirstOrDefault(x => x.Id == id);
            if (item == null)
                return false;
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Delete(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityDeleted(item);
            return true;
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Adds a item
        /// </summary>
        /// <param name="item">item</param>
        public virtual void Add(ScheduleTask item)
        {
            if (item == null)
                throw new ArgumentNullException("item");
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Add(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityInserted(item);
            TaskManager.Instance.Refresh();
            StringBuilder message = new StringBuilder();
            message.AppendFormat("Task {0} is created.", item.Name);
            ActivityLog activityItem = new ActivityLog(ActivityType.AddTask.ToString(), message.ToString());
            _activityLogService.Add(activityItem);
        }
        public void can_commit()
        {
            var customer = new Customer
            {
                FirstName = "John",
                LastName = "Doe"
            };
            using (var scope = new UnitOfWorkScope())
            {
                new EFRepository<Customer,int>()
                    .Add(customer);
                scope.Commit();
            }

            var savedCustomer = new EFRepository<Customer, int>().Query
                .First(x => x.CustomerID == customer.CustomerID);
            Assert.IsNotNull(savedCustomer);
        }
        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));
            }
        }