public void ReadMessage_With_Invalid_MessageID()
 {
     IRepository repo = new EFRepository();
     MessageService ms = new MessageService(repo);
     var message = ms.ReadMessage(new Guid("11111111-1111-1111-1111-111111111111"), new Guid("37519c07-acd4-e011-ad03-206a8a339500"));
     Assert.IsNotNull(message);
 }
Ejemplo n.º 2
0
 public void Setup()
 {
     var mockDbSet = new MockDbSet<FakeEntity>(TestData.GetFakeEntities());
     _mockDbContext = new Mock<IDbContext>();
     _mockDbContext.Setup(m => m.Set<FakeEntity>()).Returns(mockDbSet);
     _testRepository = new EFRepository<FakeEntity>(_mockDbContext.Object);
 }
 public void ReadMessageTest()
 {
     IRepository repo = new EFRepository();
     MessageService ms = new MessageService(repo);
     var message = ms.ReadMessage(new Guid("c085ce65-9fd8-e011-813c-206a8a339500"), new Guid("37519c07-acd4-e011-ad03-206a8a339500"));
     Assert.IsNotNull(message);
 }
Ejemplo n.º 4
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"));
            }
        }
 public void ReadMessage_With_Invalid_TravelerID()
 {
     IRepository repo = new EFRepository();
     MessageService ms = new MessageService(repo);
     var message = ms.ReadMessage(new Guid("c085ce65-9fd8-e011-813c-206a8a339500"), new Guid("11111111-1111-1111-1111-111111111111"));
     Assert.IsNotNull(message);
 }
Ejemplo n.º 6
0
 public void InsertUserTest()
 {
     EFRepository<GazallionMigraineDataDbContext> repo = new EFRepository<GazallionMigraineDataDbContext>();
     User test = repo.Insert<User>(new User
     {
         FirstName = "John",
         LastName = "Nystrom",
         Addresses = new List<Address>
         {
             new Address
             {
                 City = "Alpharetta",
                 Region = "GA",
                 ZipCode = "30004",
                 StreetName = "Montgomery Ave",
                 StreetNumber = "123"
             }
         },
         EmailAddress = "*****@*****.**",
         UserConditions = new List<UserCondition>
         {
             new UserCondition
             {
                 Condition = new Condition
                 {
                     Name = "Migraine",
                     Description = "bad headaches"
                 },
                 IncidentThreshold = 9,
                 ThresholdTimePeriod = (int)ThresholdTimePeriod.Monthly
             }
         }
     });
 }
        public void addElement()
        {
            var repository = new EFRepository<User>(new SystemOfFinancialContext());
            repository.Insert(new User(){FirstName = "Flyagin"});

            Assert.NotNull(repository.Get(x=>x.FirstName=="Flyagin"));
        }
 public void Can_fetch_after_a_many_fetch()
 {
     var repository = new EFRepository<Order,int>();
     var fetchingRepo = repository
         .FetchMany(x => x.OrderItems)
         .ThenFetch(x => x.Product);
     Assert.AreEqual("OrderItems.Product", fetchingRepo.FetchingPath);
 }
Ejemplo n.º 9
0
 public void TestMethod1()
 {
     IRepository repo = new EFRepository<GazallionMigraineDataDbContext>();
     IUserService userService = new UserService(repo);
     var users = userService.GetUsers();
     Assert.IsNotNull(users);
     Assert.IsTrue(users.Any());
 }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            EFRepository<Product> productRepository = new EFRepository<Product>();

            LoggingRepositoryDecorator<Product> updateDeleteLoggingDecorator =
                new LoggingRepositoryDecorator<Product>(productRepository);

            SendRequestRepositoryDecorator<Product> updateDeleteRequestDecorator =
                new SendRequestRepositoryDecorator<Product>(updateDeleteLoggingDecorator);

            UpdateDataWareHouseRepositoryDecorator<Product> updateDataWareHouseDecorator =
                new UpdateDataWareHouseRepositoryDecorator<Product>(updateDeleteRequestDecorator);

            SecurityRepositoryDecorator<Product> securityDecorator =
                new SecurityRepositoryDecorator<Product>(updateDataWareHouseDecorator);


            #region Select işlemi

            Console.WriteLine("--------------------------------------------");

            securityDecorator.Get(3);

            Console.WriteLine("---------------------------------------------\n");

            #endregion

            #region Add işlemi

            Console.WriteLine("--------------------------------------------");

            Product p=new Product(){ ProductId=1, ProductName="Ürünüm 1" };

            securityDecorator.Add(p);

            Console.WriteLine("---------------------------------------------\n");

            #endregion

            #region Update ve Delete İşlemi

            
            Console.WriteLine("---------------------------------------------");

            securityDecorator.Delete(p);

            Console.WriteLine("---------------------------------------------\n");

            Console.WriteLine("---------------------------------------------");

            securityDecorator.Update(p);

            Console.WriteLine("---------------------------------------------\n");

            #endregion

            Console.ReadLine();
        }
 public void TestGetByUIdCanNotBeNull()
 {
     IDbContext db = new R2DisasterContext();
     IRepository<Comprehensive> re = new EFRepository<Comprehensive>(db);
     IComprehensiveService s = new ComprehensiveService(re);
     InvestigationController c = new InvestigationController(s);
     string a=null;
     c.GetCompleteByUId(a);
 }
        public void Can_fectch_many_on_association()
        {
            var repository = new EFRepository<Order,int>();
            var fetchingRepo = repository
                .Fetch(order => order.Customer)
                .ThenFetchMany(customer => customer.Orders);

            Assert.AreEqual("Customer.Orders", fetchingRepo.FetchingPath);
        }
   public void Test_QueryByUnifieldId()
   {
       IDbContext db = new R2DisasterContext();
       IRepository<Comprehensive> re = new EFRepository<Comprehensive>(db);
 
       IComprehensiveService service = new ComprehensiveService(re);
       string id = "370101060001";
       Comprehensive c=service.GetByUnifiedID(id);
   }
Ejemplo n.º 14
0
 public void Reload()
 {
     _context = new TMPHWEntities();
     EMP = new EFRepository<EMP>(_context);
     DEPT = new EFRepository<DEPT>(_context);
     DEMO_CUSTOMERS = new EFRepository<DEMO_CUSTOMERS>(_context);
     DEMO_ORDERS = new EFRepository<DEMO_ORDERS>(_context);
     DEMO_ORDER_ITEMS = new EFRepository<DEMO_ORDER_ITEMS>(_context);
     DEMO_PRODUCT_INFO = new EFRepository<DEMO_PRODUCT_INFO>(_context);
 }
Ejemplo n.º 15
0
        public static bool AddEmployee(Employees NewEmployee)
        {
            EFRepository<Employees> EmployeesRepo = new EFRepository<Employees>();

            EmployeesRepo.Add(NewEmployee);

            GlobalUnitOfWork.Commit();
            return true;

        }
        public void SendMessageTest()
        {
            IRepository repo = new EFRepository();
            MessageService ms = new MessageService(repo);
            Guid author = new Guid("37519c07-acd4-e011-ad03-206a8a339500");
            Guid[] recipients = new Guid[] {
                new Guid("d0293215-1dd7-e011-ae1d-206a8a339500"),
                new Guid("45d03989-9fd8-e011-813c-206a8a339500") };

            ms.SendMessage("blablabla", "blablablbla?", author, recipients);
        }
        public void SendMessage_With_Invalid_AuthorID()
        {
            IRepository repo = new EFRepository();
            MessageService ms = new MessageService(repo);
            Guid author = new Guid("11111111-1111-1111-1111-111111111111");
            Guid[] recipients = new Guid[] {
                new Guid("d0293215-1dd7-e011-ae1d-206a8a339500"),
                new Guid("45d03989-9fd8-e011-813c-206a8a339500") };

            ms.SendMessage("blablabla", "blablablbla?", author, recipients);
        }
        public void ListMessagesTest()
        {
            IRepository repo = new EFRepository();
            MessageService ms = new MessageService(repo);
            Guid traveler = new Guid("d0293215-1dd7-e011-ae1d-206a8a339500");
            var msgs = ms.ListMessages(traveler, FolderType.Inbox, 0, 5);
            foreach (var item in msgs)
            {
                Trace.WriteLine(String.Format("{0} {1} {2}", item.Message.Subject, item.Message.Author.Fullname, item.Message.SentDate));

            }
        }
        public void CreateNews_WithIncorrectData_ShouldThrow()
        {
            // Arrange
            this.CleanUpDatabase();
            var listWithNews = new List<News>();
            var repo = new EFRepository<News>(this.dbcontext);
            var new1 = new News() { Content = null, Title = null, PublishedAt = DateTime.Now };

            // Act
            repo.Add(new1);
            repo.SaveChanges();
        }
Ejemplo n.º 20
0
        public void TestMethod1()
        {
            EFRepository<GazallionMigraineDataDbContext> repo = new EFRepository<GazallionMigraineDataDbContext>();
            Medicine test = repo.Insert<Medicine>(new Medicine
            {
                MedType = new MedType
                {
                    Type = "daily"
                },
                Name = "Topomax",

            });
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            EFRepository<Catetgory> catRepo = new EFRepository<Catetgory>();
            SecurityDecorator<Catetgory> secDec = new SecurityDecorator<Catetgory>(catRepo);
            LogDecorator<Catetgory> logDec = new LogDecorator<Catetgory>(secDec);
            MailDecorator<Catetgory> mailDec = new MailDecorator<Catetgory>(logDec);
            CRMDecorator<Catetgory> crmDec = new CRMDecorator<Catetgory>(mailDec);

            crmDec.Add(new Catetgory());
            crmDec.Update(new Catetgory());
            crmDec.Delete(new Catetgory());
            crmDec.Get();
            Console.ReadLine();
        }
Ejemplo n.º 22
0
        public void Delete_Deletes_Record()
        {
            var newCustomer = new Customer
            {
                FirstName = ("John_DELETE_ME_" + DateTime.Now),
                LastName = ("Doe_DELETE_ME_" + DateTime.Now),
                StreetAddress1 = "This record was inserted for deletion",
                City = "Fictional city",
                State = "LA",
                ZipCode = "12345"
            };

            //Re-usable query to query for the matching record.
            var queryForCustomer = new Func<EFRepository<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 EFRepository<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 EFRepository<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 EFRepository<Customer>();
                var recordCheckResult = queryForCustomer(customerRepository);
                Assert.That(recordCheckResult, Is.Null);
            }
        }
        public void TestMethod1()
        {
            try
            {
                var context = new CarContext();
                var testContext = new EFRepository<Car, int>(context);

                var all = context.Car.ToList();

                var cart = testContext.Get(all.First().ID);
            }
            catch 
            { 

            }
        }
        public void Test_Sample()
        {
            IDbContext db = new R2DisasterContext();
            IRepository<Category> re = new EFRepository<Category>(db);

            Category c = new Category()
            {
                Name = "Testname",
                Book = new Book()
                {
                    Name="TestBook",
                    Price=333
                }
            };
            re.Insert(c);
        }
Ejemplo n.º 25
0
        public void TransactionsWork()
        {
            if (ConfigurationManager.AppSettings["Environment"] == "Test")
                Assert.Ignore("Skipped on AppHarbor");

            using (var repo = new EFRepository<TestContext, TestClass>(x => x.Objects))
            {
                repo.RemoveAll();
                repo.SaveChanges();

                using (var scope = new TransactionScope())
                {
                    repo.Insert(mTestObjects.First());
                    repo.SaveChanges();
                    scope.Complete();
                }
            }

            using (var repo = new EFRepository<TestContext, TestClass>(x => x.Objects))
            {
                Assert.IsTrue(repo.Items.Any());
                repo.RemoveAll();
                repo.SaveChanges();
            }

            using (var repo = new EFRepository<TestContext, TestClass>(x => x.Objects))
            {

                try
                {
                    using (var scope = new TransactionScope())
                    {
                        repo.Insert(mTestObjects.First());
                        repo.SaveChanges();

                        throw new Exception();
                    }
                }

                catch (Exception e)
                {
                    Assert.IsFalse(repo.Items.Any());
                }
            }
        }
        public void Delete_ExistingNews_ShouldDeleteTheNew()
        {
            // Arrange
            this.CleanUpDatabase();
            var listWithNews = new List<News>();
            var repo = new EFRepository<News>(this.dbcontext);
            var new1 = new News() { Content = "Content of new", Title = "Title 1", PublishedAt = DateTime.Now };

            // Act
            repo.Add(new1);
            repo.SaveChanges();
            var newsInDb = repo.All().ToArray();
            repo.Delete(newsInDb[0]);
            repo.SaveChanges();

            // Assert
            Assert.AreEqual(0, repo.All().ToList().Count());
        }
 public void GetCountDeleteIsOK()
 {
     var context = new CarContext();
     var testContext = new EFRepository<Car,int>(context);
     var all = context.Car.ToList();
     all.ForEach(r => testContext.Delete(r));
     testContext.Save();
     Assert.AreEqual(context.Car.ToList().Count, 0);
     context.Car.Add(new Car()
     {
         CarName = "Ford",
         CarPrice = 100000
     });
     testContext.Save();
     var cars = context.Car.ToList();
     Assert.AreEqual(testContext.Count(), 1);
     Assert.AreEqual(testContext.Get(r => r.CarPrice == 100000).CarName, "Ford");
 }
        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);
        }
Ejemplo n.º 29
0
        public void Can_lazyload()
        {
            Customer customer = null;
            var testData = new EFTestData(Context);
            testData.Batch(x =>
            {
                customer = x.CreateCustomer();
                x.CreateOrderForCustomer(customer);
            });

            using (var scope = new UnitOfWorkScope())
            {
                var savedCustomer = new EFRepository<Customer>()
                    .First(x => x.CustomerID == customer.CustomerID);
                Assert.That(savedCustomer, Is.Not.Null);
                Assert.That(savedCustomer.Orders.Count, Is.EqualTo(1));
                scope.Commit();
            }
        }
        public void can_rollback()
        {
            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                Customer customer = null;
                testData.Batch(action => customer = action.CreateCustomer());

                using (new UnitOfWorkScope())
                {
                    var savedCustomer = new EFRepository<Customer>()
                        .Where(x => x.CustomerID == customer.CustomerID)
                        .First();
                    savedCustomer.LastName = "Changed";
                } //Dispose here as scope is not comitted.

                testData.Context<OrderEntities>().Refresh(RefreshMode.StoreWins, customer);
                Assert.That(customer.LastName, Is.Not.EqualTo("Changed"));
            }
        }
Ejemplo n.º 31
0
        public void Update_Should_Have_Change_Record()
        {
            EFRepository <Function, string> EFRepository = new EFRepository <Function, string>(_context);

            EFRepository.Add(new Function()
            {
                Id        = "USER",
                Name      = "Test",
                Status    = Status.Active,
                SortOrder = 1
            });
            _unitOfWork.Commit();
            Function function1 = EFRepository.FindById("USER");

            function1.Name = "Test2";
            EFRepository.Update(function1);
            _unitOfWork.Commit();

            Function function = EFRepository.FindById("USER");

            Assert.Equal("Test2", function.Name);
        }
Ejemplo n.º 32
0
        private static void Process()
        {
            IRepository dBContext = new EFRepository();
            Boolean     exit_flag = true;

            Welcome();
            do
            {
                Main_menu();
                string input = Console.ReadLine();
                switch (input)
                {
                case "1":
                    Case1_0(dBContext);
                    break;

                case "2":
                    Case2_0(dBContext);
                    break;

                case "3":
                    Case3_0(dBContext);
                    break;

                case "4":
                    Case4_0(dBContext);
                    break;

                case "5":
                    Case5_0(dBContext);
                    break;

                case "0":
                    exit_flag = false;
                    break;
                }
                Clear_console();
            } while (exit_flag);
        }
        public void Delete_ExistingNews_ShouldDeleteTheNew()
        {
            // Arrange
            this.CleanUpDatabase();
            var listWithNews = new List <News>();
            var repo         = new EFRepository <News>(this.dbcontext);
            var new1         = new News()
            {
                Content = "Content of new", Title = "Title 1", PublishedAt = DateTime.Now
            };

            // Act
            repo.Add(new1);
            repo.SaveChanges();
            var newsInDb = repo.All().ToArray();

            repo.Delete(newsInDb[0]);
            repo.SaveChanges();

            // Assert
            Assert.AreEqual(0, repo.All().ToList().Count());
        }
Ejemplo n.º 34
0
        static void PrepareControllers(frmMain main)
        {
            IEFRepository      repository = new EFRepository();
            IControllerManager manager    = ControllerManager.GetInstance();

            manager.RegisterController(new LogEntriesController(repository, main));
            manager.RegisterController(new SummaryLogsController(repository, new frmSummarizeLogs()));
            manager.RegisterController(new PersonalNoteController(repository, new frmPersonalNotes()));
            manager.RegisterController(new ObjectiveController(repository, new frmObjectives()));
            manager.RegisterController(new LeaveController(repository, new frmLeaves()));
            manager.RegisterController(new DailyAttributeController(repository, new frmDailyAttribute()));
            manager.RegisterController(new HolidayController(repository, new frmHolidays()));
            manager.RegisterController(new DailyActivityController(repository, new frmDailyActivity()));
            manager.RegisterController(new CategoryController(repository, new frmCategory()));
            manager.RegisterController(new AttributeController(repository, new frmAttribute()));
            manager.RegisterController(new ActivityController(repository, new frmActivity()));
            manager.RegisterController(new StandardOperatingProcedureController(repository, new frmStandardOperatingProcedure()));
            manager.RegisterController(new SummaryHoursByCategoriesController(repository, new frmSummarizeHoursByCategories()));

            //Prepare data for main window before showing
            ((LogEntriesController)manager.GetControllerFromId(LogEntriesController.cID)).View.View_ViewReady(null);
        }
        public ActionResult getLienContacts(JqGridRequest request, string selectedLienId)
        {
            var context = new EFRepository();

            var lienid = Convert.ToInt32(selectedLienId);

            var contactList =
                from C in context.EFLienContacts
                where C.LienId == lienid
                select C;

            JqGridResponse jqGridResp = new JqGridResponse()
            {
                TotalPagesCount   = (int)Math.Ceiling((float)contactList.Count() / (float)request.RecordsCount),
                PageIndex         = request.PageIndex,
                TotalRecordsCount = contactList.Count()
            };

            foreach (EFLienContact contact in contactList)
            {
                jqGridResp.Records.Add(new JqGridRecord(Convert.ToString(contact.Id), new List <object>()
                {
                    contact.Id.ToString(),
                    contact.LienId.ToString(), // change to propertyId
                    contact.FirstName,
                    contact.LastName,
                    contact.Role
                    //Contact.PhoneHome,
                    //Contact.PhoneWork,
                    //Contact.PhoneCell,
                    //Contact.PhoneFax,
                    //Contact.Email
                }));
            }
            return(new JqGridJsonResult()
            {
                Data = jqGridResp
            });
        }
Ejemplo n.º 36
0
        public void Test_Business_Exception_High_Price()
        {
            //create In Memory Database
            var options = new DbContextOptionsBuilder <ERPContext>()
                          .UseInMemoryDatabase(databaseName: "ERP")
                          .Options;

            using (var context = new ERPContext(options))
            {
                var repository = new EFRepository(context);

                var productService = new ProductsService(repository);

                Assert.Throws <BusinessException>(() => productService.AddProduct(new Product
                {
                    Id    = 1,
                    Name  = "Ball",
                    Price = 10000000,
                    Image = "base64Image"
                }));
            }
        }
Ejemplo n.º 37
0
        public void HelloWorld3()
        {
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.Load("Definitions\\HelloWorld3.xml");

            using (var unitWork = UnitOfWork.Start())
            {
                ProcessDefinitionCreationContext creationContext = new ProcessDefinitionCreationContext();
                ProcessDefinition processDefinition = creationContext.CreateProcessDefinition(xmlDocument);
                creationContext.ResolveReferences();

                AttributeDef evaluation = null, text = null;
                foreach (AttributeDef attribute in processDefinition.Attributes)
                {
                    if (attribute.Name == "evaluation result")
                    {
                        evaluation = attribute;
                    }
                    else if (attribute.Name == "the text attrib")
                    {
                        text = attribute;
                    }
                }

                Assert.IsNotNull(evaluation);
                Assert.IsNotNull(evaluation.SerializerDelegation);
                Assert.AreEqual("EvaluationSerializer", evaluation.SerializerDelegation.ClassName);

                Assert.IsNotNull(text);
                Assert.IsNotNull(text.SerializerDelegation);
                Assert.AreEqual("TextSerializer", text.SerializerDelegation.ClassName);
                Assert.AreEqual(":-)", text.InitialValue);

                var processBlockRepository = new EFRepository <ProcessBlock>();
                processBlockRepository.Add(processDefinition);
                unitWork.Flush();
            }
        }
Ejemplo n.º 38
0
        public void CanDeleteDvd()
        {
            var dvdToCreate = new Dvd();
            var repo        = new EFRepository();

            dvdToCreate.Title       = "Inception";
            dvdToCreate.ReleaseYear = 2010;
            dvdToCreate.Rating      = "PG-13";
            dvdToCreate.Director    = "Christopher Nolan";
            dvdToCreate.Notes       = "Good, solid movie.";

            repo.Create(dvdToCreate);

            var dvdToDelete = repo.GetDvdById(6);

            Assert.IsNotNull(dvdToDelete);

            repo.Delete(6);

            dvdToDelete = repo.GetDvdById(6);
            Assert.IsNull(dvdToDelete);
        }
        public void Can_eager_fetch()
        {
            var testData = new EFTestData(Context);

            Order order      = null;
            Order savedOrder = null;

            testData.Batch(x => order = x.CreateOrderForCustomer(x.CreateCustomer()));

            using (var scope = new UnitOfWorkScope())
            {
                savedOrder = new EFRepository <Order>()
                             .Fetch(o => o.Customer)
                             .Where(x => x.OrderID == order.OrderID)
                             .SingleOrDefault();
                scope.Commit();
            }

            Assert.NotNull(savedOrder);
            Assert.NotNull(savedOrder.Customer);
            Assert.DoesNotThrow(() => { var firstName = savedOrder.Customer.FirstName; });
        }
        public void CreateNews_WithCorrectData_ShouldCreateNewsSuccessfully()
        {
            // Arrange
            this.CleanUpDatabase();
            var listWithNews = new List <News>();
            var repo         = new EFRepository <News>(this.dbcontext);
            var new1         = new News()
            {
                Content = "Content 1", Title = "Title 1", PublishedAt = DateTime.Now
            };

            // Act
            repo.Add(new1);
            repo.SaveChanges();
            var newsInDb = repo.All().ToArray();

            // Assert
            Assert.AreEqual(1, newsInDb.Count());
            Assert.AreEqual(new1.Title, newsInDb[0].Title);
            Assert.AreEqual(new1.Content, newsInDb[0].Content);
            Assert.AreEqual(new1.PublishedAt.ToString(), newsInDb[0].PublishedAt.ToString());
        }
Ejemplo n.º 41
0
        public cSalaahCalendar(Masjid pMasjid, ApplicationDbContext context)
        {
            _context   = context;
            Repository = new EFRepository(_context);

            Masjid = pMasjid;

            Months = new List <DateTime>();

            for (int i = 1; i <= 12; i++)
            {
                Months.Add(new DateTime(DateTime.Now.Year, i, 1));
            }

            Times = new List <SalaahTime>();

            if (Masjid.SalaahTimesType == SalaahTimesType.DailyTime)
            {
                Times = Repository
                        .Find <SalaahTime>(s => s.MasjidId == Masjid.Id &&
                                           s.TimeDate.Year == DateTime.Now.Year &&
                                           s.Type == SalaahTimesType.DailyTime)
                        .OrderBy(s => s.DayNumber)
                        .ToList();

                Type = SalaahTimesType.DailyTime;
            }
            else
            {
                Times = Repository
                        .Find <SalaahTime>(s => s.MasjidId == Masjid.Id &&
                                           s.Type == SalaahTimesType.ScheduleTime)
                        .OrderBy(s => s.DayNumber)
                        .ToList();

                Type = SalaahTimesType.ScheduleTime;
            }
        }
Ejemplo n.º 42
0
        public async Task TestRemovePictureIdFromUserObityarysAsyncMethod()
        {
            var optionsBuilder   = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase("testDb4");
            var virtualDbContext = new ApplicationDbContext(optionsBuilder.Options);

            var obituaryRepository = new EFRepository <Obituary>(virtualDbContext);
            var pictureRepository  = new EFRepository <Picture>(virtualDbContext);

            var userPictureService = new UserPictureService(pictureRepository, obituaryRepository);

            var obituary = new Obituary
            {
                Id               = "ObituaryId1",
                UserId           = "UserId1",
                FrameId          = "frame1Id",
                TextTemplateId   = "ttId1",
                CustomTextId     = " CustomTextId1",
                CrossId          = "1",
                PictureId        = "PictureId1",
                AfterCrossTextId = "AfterCrossTextId1",
                CrossTextId      = "CrossTextId1",
                FromId           = "FromId1",
                FullNameId       = "FullNameId1",
                PanahidaId       = "PanahidaId1",
                YearId           = "YearId1",
            };

            await obituaryRepository.AddAsync(obituary);

            await obituaryRepository.SaveChangesAsync();

            await userPictureService
            .RemovePictureIdFromUserObityarysAsync("PictureId1");

            var dbObituary = obituaryRepository.All().FirstOrDefault();

            Assert.Null(dbObituary.PictureId);
        }
Ejemplo n.º 43
0
        public ActionResult Editar(int productoId, int maxiKioscoId)
        {
            var repo = new EFRepository <Entidades.MaxiKiosco>();
            var maxi = repo.Obtener(maxiKioscoId);

            repo.MaxiKioscosEntities.StockActualizar(maxi.Identifier, productoId);
            Stock stock = Uow.Stocks.Obtener(s => s.ProductoId == productoId &&
                                             s.MaxiKioscoId == maxiKioscoId,
                                             s => s.MaxiKiosco, s => s.Producto,
                                             s => s.StockTransacciones);

            if (stock == null)
            {
                stock = new Stock();

                var maxiKiosco = Uow.MaxiKioscos.Obtener(maxiKioscoId);
                var producto   = Uow.Productos.Obtener(productoId);

                stock.MaxiKioscoId      = maxiKioscoId;
                stock.ProductoId        = productoId;
                stock.MaxiKiosco        = maxiKiosco;
                stock.Producto          = producto;
                stock.FechaCreacion     = DateTime.Now;
                stock.OperacionCreacion = "Edición en web";
            }

            var model = new StockModel()
            {
                MaxiKiosco         = stock.MaxiKiosco.Nombre,
                MotivoCorreccionId = UsuarioActual.Cuenta.MotivoCorreccionPorDefecto,
                Producto           = stock.Producto.Descripcion,
                StockActual        = stock.StockActual,
                PrecioConIVA       = stock.Producto.PrecioConIVA,
                Stock = stock
            };

            return(PartialView(model));
        }
Ejemplo n.º 44
0
        public void Save_Does_Not_Save_New_Customer_When_UnitOfWork_Is_Aborted()
        {
            var rnd         = new Random();
            var newCustomer = new Customer
            {
                FirstName      = ("John_" + rnd.Next(30001, 50000)),
                LastName       = ("Doe_" + rnd.Next(30001, 50000)),
                StreetAddress1 = "This record was inserted via a test",
                City           = "Fictional city",
                State          = "LA",
                ZipCode        = "12345"
            };

            using (new UnitOfWorkScope())
            {
                var customerRepository = new EFRepository <Customer>();
                var recordCheckResult  = (from cust in customerRepository
                                          where cust.FirstName == newCustomer.FirstName &&
                                          cust.LastName == newCustomer.LastName
                                          select cust).FirstOrDefault();
                Assert.That(recordCheckResult, Is.Null);

                customerRepository.Add(newCustomer);
                //DO NOT CALL COMMIT TO SIMMULATE A ROLLBACK.
            }

            //Starting a completely new unit of work and repository to check for existance.
            using (var scope = new UnitOfWorkScope())
            {
                var customerRepository = new EFRepository <Customer>();
                var recordCheckResult  = (from cust in customerRepository
                                          where cust.FirstName == newCustomer.FirstName &&
                                          cust.LastName == newCustomer.LastName
                                          select cust).FirstOrDefault();
                Assert.That(recordCheckResult, Is.Null);
                scope.Commit();
            }
        }
Ejemplo n.º 45
0
        public void ReturnResultFromExpectedType_WhenIDFound()
        {
            // Arrange
            var contextMock     = new Mock <IPickAndBookDbContext>();
            var categorySetMock = new Mock <IDbSet <Category> >();

            categorySetMock.Setup(c => c.Find(It.IsAny <Guid>())).Returns(new Category()
            {
                CategoryId          = Guid.NewGuid(),
                CategoryName        = "Name",
                CategoryDescription = "Description",
                CategoryImage       = "Image"
            });
            contextMock.Setup(c => c.Set <Category>()).Returns(categorySetMock.Object);

            EFRepository <Category> categoryRepository = new EFRepository <Category>(contextMock.Object);

            // Act
            var result = categoryRepository.GetById(Guid.NewGuid());

            // Assert
            Assert.IsInstanceOf <Category>(result);
        }
Ejemplo n.º 46
0
        public void RecruitPersonsAndSaveIntoDB_can_recruit_5_Persons_and_save_all_into_EF_Database()
        {
            Fixture fix     = new Fixture();
            var     persons = fix.CreateMany <Person>(5);

            Mock <IDevice> hwMock = new Mock <IDevice>();
            IRepository    repo   = new EFRepository(new EFContext(connectionString)); // Echte DB

            hwMock.SetupSequence(x => x.RecruitPerson())
            .Returns(persons.ElementAt(0))
            .Returns(persons.ElementAt(1))
            .Returns(persons.ElementAt(2))
            .Returns(persons.ElementAt(3))
            .Returns(persons.ElementAt(4));

            Core core            = new Core(hwMock.Object, repo);
            int  numberOfPersons = 5;

            core.RecruitPersonsAndSaveIntoDB(numberOfPersons);

            // Test, ob auch alle in der DB sind
            repo.GetAll <Person>().Count().Should().Be(numberOfPersons); //  -> muss 100 sein
        }
Ejemplo n.º 47
0
        public bool Add_Coded(string Name, string Surname, string Email, string Username)
        {
            Resources new_resource = new Resources()
            {
                name     = Name,
                surname  = Surname,
                email    = Email,
                username = Username
            };

            try
            {
                EFRepository <Resources> ResourceRepo = new EFRepository <Resources>();
                ResourceRepo.Add(new_resource);
                DAL.GlobalUnitOfWork.Commit();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 48
0
        public void ReturnCorrect_RecordWhenValidIntIdIsPassed()
        {
            // Arrange
            int id          = 1;
            var mockedDbSet = new Mock <IDbSet <Comment> >();

            mockedDbSet.Setup(x => x.Find(It.IsAny <int>())).Returns(new Comment()
            {
                Id = id
            });
            var mockedContext = new Mock <IMeetMeDbContext>();

            mockedContext.Setup(x => x.Set <Comment>()).Returns(mockedDbSet.Object);
            var repo = new EFRepository <Comment>(mockedContext.Object);

            // Act
            var record = repo.GetById(id);

            // Assert
            Assert.IsNotNull(record);
            Assert.IsInstanceOf <Comment>(record);
            Assert.AreEqual(id, record.Id);
        }
Ejemplo n.º 49
0
        public void Can_query_using_specification()
        {
            using (var testData = new EFTestData(OrdersContextProvider()))
            {
                testData.Batch(actions =>
                {
                    actions.CreateOrdersForCustomers(actions.CreateCustomersInState("PA", 2));
                    actions.CreateOrdersForCustomers(actions.CreateCustomersInState("DE", 5));
                    actions.CreateOrdersForCustomers(actions.CreateCustomersInState("LA", 3));
                });

                using (new UnitOfWorkScope())
                {
                    var customersInPa = new Specification <Order>(x => x.Customer.State == "DE");

                    var ordersRepository = new EFRepository <Order>();
                    var results          = from order in ordersRepository.Query(customersInPa) select order;

                    Assert.That(results.Count(), Is.GreaterThan(0));
                    Assert.That(results.Count(), Is.EqualTo(5));
                }
            }
        }
Ejemplo n.º 50
0
        public ActionResult deleteProperty(string oper, string id)
        {
            var context = new EFRepository();

            if (oper.Equals("del"))
            {
                int propId   = Convert.ToInt32(id);
                var property = (from p
                                in context.EFProperties
                                where p.Id == propId
                                select p).Single();

                property.isDeleted            = true;
                context.Entry(property).State = EntityState.Modified;
                context.SaveChanges();

                //EFProperty deleteProperty = new EFProperty() { Id = Convert.ToInt32(id) };
                //context.EFProperties.Attach(deleteProperty);
                //context.EFProperties.Remove(deleteProperty);
                //context.SaveChanges();
            }
            return(Json(JSONResponseFactory.SuccessResponse()));
        }
Ejemplo n.º 51
0
        public void GenericMetodsTest()
        {
            TestModel testModel = new TestModel();

            Mock <EFDbContext>        context = new Mock <EFDbContext>();
            Mock <DbSet <TestModel> > dbset   = new Mock <DbSet <TestModel> >();

            context.Setup(x => x.Set <TestModel>()).Returns(dbset.Object);
            dbset.Setup(x => x.Add(It.IsAny <TestModel>())).Returns(testModel);
            Mock <IUnitOfWork> mockUow = new Mock <IUnitOfWork>();

            mockUow.Setup(x => x.GetSource()).Returns(context.Object);

            EFRepository <TestModel> repository = new EFRepository <TestModel>(mockUow.Object, null);

            //act
            repository.Create(testModel);

            //assert

            context.Verify(x => x.Set <TestModel>());
            dbset.Verify(x => x.Add(It.Is <TestModel>(y => y == testModel)));
        }
Ejemplo n.º 52
0
        public void NotThrow_WhenArgumentIsValid()
        {
            //Arrange
            var mockedSet    = new Mock <IDbSet <IDestination> >();
            var mockedAnimal = new Mock <IDestination>();

            mockedAnimal.SetupAllProperties();

            var mockedContext = new Mock <ITravelAdvisorDbContext>();

            //Act
            mockedContext.Setup(x => x.Set <IDestination>()).Returns(mockedSet.Object);
            var repository = new EFRepository <IDestination>(mockedContext.Object);

            try
            {
                repository.Delete(mockedAnimal.Object);
            }
            catch (NullReferenceException) { };

            //Assert
            mockedContext.Verify(x => x.Entry(mockedAnimal.Object), Times.AtLeastOnce);
        }
Ejemplo n.º 53
0
        public void ReturnCorrect_RecordWhenValidStringIdIsPassed()
        {
            // Arrange
            string id          = "abcd-some";
            var    mockedDbSet = new Mock <IDbSet <AspIdentityUser> >();

            mockedDbSet.Setup(x => x.Find(It.IsAny <string>())).Returns(new AspIdentityUser()
            {
                Id = id
            });
            var mockedContext = new Mock <IMeetMeDbContext>();

            mockedContext.Setup(x => x.Set <AspIdentityUser>()).Returns(mockedDbSet.Object);
            var repo = new EFRepository <AspIdentityUser>(mockedContext.Object);

            // Act
            var record = repo.GetById(id);

            // Assert
            Assert.IsNotNull(record);
            Assert.IsInstanceOf <AspIdentityUser>(record);
            Assert.AreEqual(id, record.Id);
        }
Ejemplo n.º 54
0
        public void EFRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ColumnValues()
        {
            //Arrange
            SetUpDatabase(TestConstants.EF_RecordCount);

            var repository = new EFRepository <Dog>(_efUnitOfWork, _cache.Object);
            var dog        = new Dog
            {
                Age  = TestConstants.EF_InsertDogAge,
                Name = TestConstants.EF_InsertDogName
            };

            //Act
            repository.Add(dog);
            _efUnitOfWork.Commit();

            //Assert
            DataTable table = DataUtil.GetTable(TestConstants.EF_DatabaseName, TestConstants.EF_TableName);
            DataRow   row   = table.Rows[table.Rows.Count - 1];

            Assert.AreEqual(TestConstants.EF_InsertDogAge, row["Age"]);
            Assert.AreEqual(TestConstants.EF_InsertDogName, row["Name"]);
        }
Ejemplo n.º 55
0
        private void ControlarCierreCaja()
        {
            var repo = new EFRepository <CierreCaja>();

            if (AppSettings.MaxiKioscoId == 0)
            {
                EventosFlags.CierreCajaEstado = CierreCajaEstadoEnum.Cerrado;
            }
            else
            {
                var cajas = repo.Listado().Where(c => c.MaxiKioskoId == AppSettings.MaxiKioscoId).ToList();
                if (cajas.Count == 0)
                {
                    EventosFlags.CierreCajaEstado = CierreCajaEstadoEnum.Cerrado;
                }
                else
                {
                    var ultima = cajas.OrderByDescending(c => c.CierreCajaId).First();
                    EventosFlags.CierreCajaEstado = (ultima.FechaFin != null)
                                                        ? CierreCajaEstadoEnum.Cerrado
                                                        : CierreCajaEstadoEnum.Abierto;
                }
            }
        }
Ejemplo n.º 56
0
        public void Repository_For_Uses_Registered_Fetching_Strategies()
        {
            IEnumerable <Order> orders;

            using (var testData = new EFDataGenerator(new TestModel()))
                using (new UnitOfWorkScope())
                {
                    testData.Batch(actions =>
                                   actions.CreateOrderForProducts(actions.CreateProducts(5)));
                    var strategies = new IFetchingStrategy <Order, EFRepositoryTests>[]
                    {
                        new OrderOrderItemsStrategy(),
                        new OrderItemsProductStrategy()
                    };

                    IRepository <Order> ordersRepository = null;
                    ServiceLocator.Current.Expect(x => x.GetAllInstances <IFetchingStrategy <Order, EFRepositoryTests> >())
                    .Return(strategies);

                    ordersRepository = new EFRepository <Order>().For <EFRepositoryTests>();
                    orders           = (from o in ordersRepository select o).ToList();
                }
            orders.ForEach(x => Assert.That(x.CalculateTotal(), Is.GreaterThan(0)));
        }
Ejemplo n.º 57
0
        public void Query_Allows_Projection_Using_Select_Projection()
        {
            using (var testData = new EFDataGenerator(new TestModel()))
                using (new UnitOfWorkScope())
                {
                    testData.Batch(actions => actions.CreateOrderForCustomer(actions.CreateCustomer()));

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

                    Assert.DoesNotThrow(() => results.ForEach(x =>
                    {
                        Assert.That(!string.IsNullOrEmpty(x.LastName));
                        Assert.That(!string.IsNullOrEmpty(x.FirstName));
                    }));
                }
        }
Ejemplo n.º 58
0
        public void ReturnCorrect_AllRecords()
        {
            // Arrange
            var data = new List <Comment>()
            {
                new Comment()
                {
                    Content = "Some"
                },
                new Comment()
                {
                    Content = "Other"
                },
                new Comment()
                {
                    Content = "Another"
                },
                new Comment()
                {
                    Content = "Again"
                }
            };
            var mockedDbContext = new Mock <IMeetMeDbContext>();
            var queryableData   = data.AsQueryable();
            var mockedDbSet     = this.GetMockedDbSet <Comment>(queryableData);

            mockedDbContext.Setup(x => x.Set <Comment>()).Returns(mockedDbSet.Object);
            var repo = new EFRepository <Comment>(mockedDbContext.Object);

            // Act
            var result = repo.All;

            // Assert
            Assert.AreEqual(data.Count, result.Count());
            CollectionAssert.AreEqual(data, result.ToList());
        }
Ejemplo n.º 59
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
            //init automapper
            AutoMapperController MapController = new AutoMapperController();

            //start scheluder
            Scheduler.Start();
            //create tasks jobs

            using (EFRepository efRepository = new EFRepository())
            {
                foreach (User user in efRepository.GetAllUsers())
                {
                    foreach (Task task in user.CreateTasks)
                    {
                        Scheduler.AddExpiredTaskJob(new System.Net.Mail.MailAddress(user.Email),
                                                    task.TaskID.ToString(),
                                                    task.Name,
                                                    task.DTExec);
                    }
                }
            }
            //init log4net
            LogFactory.InitializeLogServiceFactory(log4net.LogManager.GetLogger("ToDo"));

            //Task task2 = new Task();
            //task2.DTCreate = DateTime.Now;
            //task2.DTExec = DateTime.Now;
            //DBFabric.Repository.AddTask(DBFabric.Repository.GetAllUsers().First(), task2);
        }
Ejemplo n.º 60
0
        public ProfessionalDto Get(string id)
        {
            var repo = new EFRepository <Professional>();
            var prof = repo.Get(p => p.ProfessionalId == id);

            if (prof != null)
            {
                return(new ProfessionalDto
                {
                    Address = prof.Address,
                    City = prof.City,
                    CUIT = prof.CUIT,
                    DNI = prof.DNI,
                    FirstName = prof.FirstName,
                    LastName = prof.LastName,
                    MN = prof.MN,
                    MP = prof.MP,
                    Phone = prof.Phone,
                    Id = prof.ProfessionalId,
                    ProvinceId = prof.ProvinceId
                });
            }
            return(null);
        }