public IHttpActionResult Post(HomeworkRequestModel model)
        {
            if (model == null)
            {
                return this.BadRequest();
            }

            var db = new StudentSystemDbContext();
            var homeworsRepo = new GenericRepository<Homework>(db);
            var coursesRepo = new GenericRepository<Course>(db);
            var studentsRepo = new GenericRepository<Student>(db);
            Course defaultCourse = coursesRepo.All().ToList().FirstOrDefault();
            Student defaultStudent = studentsRepo.All().ToList().FirstOrDefault();
            var homeworkToAdd = new Homework
            {
                FileUrl = model.FileUrl,
                TimeSent = new DateTime(model.TimeSentTicks),
                Course = defaultCourse,
                CourseId = defaultCourse.Id,
                Student = defaultStudent,
                StudentIdentification = defaultStudent.StudentIdentification
            };

            homeworsRepo.Add(homeworkToAdd);
            homeworsRepo.SaveChanges();
            return this.Ok();
        }
        public object Add(AddTripModel model)
        {
            GenericRepository<Trip> TripRepo = new GenericRepository<Trip>();
            GenericRepository<User> userRepo = new GenericRepository<User>();
             User user = userRepo.GetSingle(u => u.Username == User.Identity.Name);
            DateTime departDate;
            if (!DateTime.TryParse(model.Depdate, out departDate))
            {
                return false;
            }

            Trip Trip = new Trip()
            {
                UserId =user.UserId,
                DepartDate = departDate,
                AvailableSeatNumber = model.Seatnum,
                Price = model.Price,
                DepMin=model.Min,
                DepHour=model.Hour,
                EstimatedHour=model.EstHour,
                EstimatedMin=model.EstMin,
                DepartLocationId=model.DepLocId,
                ArrivalLocationId=model.ArrLocId,
                CarId = 1,

            };
            TripRepo.Add(Trip);
            return true;
        }
        public IHttpActionResult Post(TestRequestModel model)
        {
            if (model == null)
            {
                return this.BadRequest();
            }

            var db = new StudentSystemDbContext();
            var testsRepo = new GenericRepository<Test>(db);
            var coursesRepo = new GenericRepository<Course>(db);
            List<Course> allCourses = coursesRepo.All().ToList();
            var testCourse = new Course
            {
                Name = model.Course.Name,
                Description = model.Course.Description
            };

            var testToAdd = new Test
            {
                Course = testCourse
            };

            testsRepo.Add(testToAdd);
            testsRepo.SaveChanges();
            return this.Ok();
        }
        public void Can_Add_New_Entity()
        {
            // Arrange
            var routesRepository = new GenericRepository<Route>(this.dataBaseContext);

            // Act
            routesRepository.Add(new Route { Id = 4, Name = "newRoute" });

            // Assert
            Assert.AreEqual(2, routesRepository.Count);
            Assert.AreNotEqual(null, routesRepository.GetById(1));
        }
        private async Task SaveEntity()
        {
            var VehicleModel = new VehicleModel()
            {
                Description    = txtDescription.Text.Trim(),
                Status         = (StatusEnum)cbStatus.SelectedItem,
                VehicleBrandId = int.TryParse(cbBrand.SelectedValue.ToString(), out int idVehicleBrand) ? idVehicleBrand : 0,
                VehicleTypeId  = int.TryParse(cbType.SelectedValue.ToString(), out int idVehicleType) ? idVehicleType : 0
            };
            await _VehicleModel.Add(VehicleModel);

            await _VehicleModel.SaveAsync();
        }
示例#6
0
        public ActionResult RequestCode()
        {
            unitOfWork = (GenericUnitOfWork)Session["UNITOFWORK"];
            GenericRepository <RequestCode> reqRepo = unitOfWork.GetRepoInstance <RequestCode>();
            String      Email = this.Request.Form["Email"];
            RequestCode Req   = new RequestCode();

            Req.Email = Email;

            reqRepo.Add(Req);
            unitOfWork.SaveChanges();
            return(RedirectToAction("Code"));
        }
示例#7
0
 // POST api/<controller>
 public void Post([FromBody] Order order)
 {
     if (order.lawnAdress != null || order.lawnArea >= 0)
     {
         Order newOrder = new Order(order.nameService, order.lawnArea)
         {
             idClient = order.idClient, lawnAdress = order.lawnAdress
         };
         IGenericRepository <Order> RepO = new GenericRepository <Order>();
         RepO.Add(newOrder);
         RepO.Save();
     }
 }
        public void AddNews_Should_Throw_Exception_If_Data_Is_Invalid()
        {
            var repository = new GenericRepository<News>(new NewsContext());
            var news = new News
            {
                Title = "shor",
                Content = "Sample Content",
                PublishDate = DateTime.Now
            };

            repository.Add(news);
            repository.SaveChanges();
        }
        public void TransferLocations()
        {
            GenericRepository<Location> locationRepo = new GenericRepository<Location>();
            string file = System.Web.HttpContext.Current.Server.MapPath("~/files/provinces.csv");
            using (StreamReader reader = new StreamReader(file, Encoding.UTF8))
            {
                string line = string.Empty;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] components = line.Split(',');
                    Location location = new Location()
                    {
                        Name = components[2],
                        Lat = Convert.ToDouble(components[3]),
                        Lon = Convert.ToDouble(components[4]),
                        ParentId = -1
                    };
                    locationRepo.Add(location);
                }
            }

            file = System.Web.HttpContext.Current.Server.MapPath("~/files/districts.csv");
            using (StreamReader reader = new StreamReader(file, Encoding.UTF8))
            {
                string line = string.Empty;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] components = line.Split(',');
                    Location location = new Location()
                    {
                        Name = components[2],
                        Lat = Convert.ToDouble(components[3]),
                        Lon = Convert.ToDouble(components[4]),
                        ParentId = Convert.ToInt32(components[1])
                    };
                    locationRepo.Add(location);
                }
            }
        }
        public User SignUpApplicationUser(UserRegistrationModel model)
        {
            var user = new User()
            {
                ChatId   = model.ChatId,
                UserName = model.UserName,
                UserId   = model.ChatId
            };

            _userStorage.Add(user);

            return(user);
        }
示例#11
0
        public void SalvarTarefa(Tarefa model)
        {
            if (model.IdTarefa == 0)
            {
                _repository.Add(model);
            }
            else
            {
                _repository.Edit(model);
            }

            _uow.Commit();
        }
示例#12
0
        public ActionResult Create([Bind(Include = "ID,Name,Gender,DOB")] Student student)
        {
            if (ModelState.IsValid)
            {
                studentRepo.Add(student);
                _unitOfWork.SaveChanges();
                //db.Students.Add(student);
                //db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(student));
        }
示例#13
0
 public void Add(Category item)
 {
     if (item.CategoryName == "" || item.CategoryName.Length <= 3 ||
         item.CategoryDescription == "" ||
         item.CategoryName.Length > 51)
     {
         //hata mesajı verilir.
     }
     else
     {
         genericRepository.Add(item);
     }
 }
        public ActionResult Registerion(RegisterModel user)
        {
            if (!ModelState.IsValid)
            {
                return(View("Register", user));
            }
            else

            {
                //working
                unitOfWork = (GenericUnitOfWork)Session["UNITOFWORK"];
                GenericRepository <User>    userRepo    = unitOfWork.GetRepoInstance <User>();
                GenericRepository <Startup> startupRepo = unitOfWork.GetRepoInstance <Startup>();
                string passHash   = Cryptography.GetRandomKey(64);
                Guid   g          = Guid.NewGuid();
                string GuidString = Convert.ToBase64String(g.ToByteArray());
                GuidString = GuidString.Replace("=", "");
                GuidString = GuidString.Replace("+", "");

                User us = new User()
                {
                    VerificationToken = GuidString,
                    FirstName         = user.FirstName,
                    LastName          = user.LastName,
                    Email             = user.Email,
                    IsVerified        = false,
                    Mobile            = user.Mobile,
                    Active            = true,
                    CreatedAt         = DateTime.Now,
                    Hash     = passHash,
                    Password = Cryptography.Encrypt(user.Password, passHash)
                };

                //Db.Users.Add(us);
                userRepo.Add(us);

                Startup s = new Startup()
                {
                    CompanyID     = us.UserID,
                    CompanyName   = user.CompanyName,
                    CompanyNumber = user.CompanyNumber
                };
                startupRepo.Add(s);
                unitOfWork.SaveChanges();
                SendEmail.send(us.Email, us.FirstName, this.Request, us.VerificationToken, null, "~/Validate.html");
                //Db.Startups.Add(s);
                //Db.SaveChanges();

                return(RedirectToAction("Login", "User"));
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(List <FornecedorDadosBancariosModel> model)
        {
            var ok = false;

            #region Regras
            foreach (var item in model)
            {
                if (item.flgDelete && item.Id > 0)
                {
                    ok = _rep.Delete(item.Id);
                }

                if (item.Id == 0 && !item.flgDelete)
                {
                    var c = new FornecedorDadosBancariosModel
                    {
                        Agencia          = item.Agencia,
                        Conta            = item.Conta,
                        Tipo             = item.Tipo,
                        BancoId          = item.BancoId,
                        Ativo            = true,
                        DataCadastro     = DateTime.Now,
                        FornecedorId     = item.FornecedorId,
                        Titular          = item.Titular,
                        DocumentoTitular = item.DocumentoTitular,
                        Observacoes      = item.Observacoes
                    };

                    ok = _rep.Add(c);
                }
                else if (item.Id > 0 && !item.flgDelete)
                {
                    var update = Get(item.Id);
                    update.Agencia          = !string.IsNullOrEmpty(item.Agencia) ? item.Agencia : update.Agencia;
                    update.Conta            = !string.IsNullOrEmpty(item.Conta) ? item.Conta : update.Conta;
                    update.Tipo             = !string.IsNullOrEmpty(item.Tipo) ? item.Tipo : update.Tipo;
                    update.BancoId          = item.BancoId > 0 ? item.BancoId : update.BancoId;
                    update.Ativo            = item.Ativo;
                    update.DataAlteracao    = DateTime.Now;
                    update.Titular          = !string.IsNullOrEmpty(item.Titular) ? item.Titular : update.Titular;
                    update.DocumentoTitular = !string.IsNullOrEmpty(item.DocumentoTitular) ? item.DocumentoTitular : update.DocumentoTitular;
                    update.Observacoes      = !string.IsNullOrEmpty(item.Observacoes) ? item.Observacoes : update.Observacoes;

                    ok = _rep.Update(update);
                }
            }

            #endregion

            return(ok);
        }
示例#16
0
文件: DALTest.cs 项目: aleksam/EF101
        public void ShouldPerformCRUD()
        {
            using (IUnitOfWork _unitOfWork = new UnitOfWork())
            {
                // (C)reate
                Movie newMovie = new Movie()
                {
                    ID          = 0,
                    Title       = "Test Movie",
                    Genre       = "Comedy",
                    Price       = 10.00M,
                    ReleaseDate = DateTime.Now
                };

                var MoviesRepository = new GenericRepository <Movie>(_unitOfWork.context);

                MoviesRepository.Add(newMovie);

                _unitOfWork.SaveChanges();

                int newMovieId = newMovie.ID;

                // (R)ead
                var MoviesRepositorySpecific = new MovieRepository(_unitOfWork.context);

                List <Movie> listOfMovies = MoviesRepositorySpecific.GetMoviesByGenre("Comedy");

                // (U)pdate
                //newMovie.Genre = "Drama";

                //MoviesRepository.Edit(newMovie);

                //_unitOfWork.SaveChanges();

                //Movie updatedMovie = MoviesRepository.GetById(newMovieId);

                // (D)elete
                MoviesRepository.Delete(newMovie);

                _unitOfWork.SaveChanges();

                Movie testMovie = MoviesRepository.GetById(newMovieId);

                // Test
                Assert.IsTrue(newMovieId > 0);
                Assert.IsTrue(listOfMovies != null);
                Assert.IsTrue(listOfMovies.Count > 0);
                // Assert.IsTrue(updatedMovie.Genre == "Drama");
                Assert.IsTrue(testMovie == null);
            }
        }
示例#17
0
        public void Add(CSVTransaction obj)
        {
            var user = userRepository.Context.Set <User>()
                       .Where(usr => usr.UserName == obj.Client)
                       .FirstOrDefault();

            if (user == null)
            {
                user = new User {
                    UserName = obj.Client
                };
                userRepository.Add(user);
            }


            var manager = managerRepository.Context.Set <Manager>()
                          .Where(mngr => mngr.ManagerName == obj.Manager)
                          .FirstOrDefault();

            if (manager == null)
            {
                manager = new Manager {
                    ManagerName = obj.Manager
                };
                managerRepository.Add(manager);
            }


            var product = productRepository.Context.Set <Product>()
                          .Where(prod => prod.ProductName == obj.Product)
                          .FirstOrDefault();

            if (product == null)
            {
                product = new Product {
                    ProductName = obj.Product, Cost = obj.TotalCost
                };
                productRepository.Add(product);
            }

            transactionRepository.Add(new Transaction
            {
                Date    = obj.Date,
                User    = user,
                Product = product,
                Manager = manager,
                Coast   = obj.TotalCost
            });

            this.Save();
        }
示例#18
0
        private static void ImportOrdersToDatabase(IEnumerable <Order> orders)
        {
            var sqlRepo  = new GenericRepository <Order>(new GirlsAgencyContext());
            var girlRepo = new GenericRepository <Girl>(new GirlsAgencyContext());
            var ctx      = new GirlsAgencyContext();

            foreach (var order in orders)
            {
                sqlRepo.Add(order);
                //ctx.Customers.
            }

            sqlRepo.SaveChanges();
        }
示例#19
0
        // POST api/Albums
        public IHttpActionResult Post([FromBody] AlbumServiceModel value)
        {
            var artists = new GenericRepository <Artist>(Data);
            var songs   = new GenericRepository <Song>(Data);

            if (value.Artists != null)
            {
                foreach (var artist in value.Artists)
                {
                    if (!artists.All().Any(x => x.Name == artist))
                    {
                        var newArtist = new Artist {
                            Name = artist
                        };
                        artists.Add(newArtist);
                    }

                    Data.SaveChanges();
                }
            }

            if (value.Songs != null)
            {
                foreach (var song in value.Songs)
                {
                    if (!songs.All().Any(x => x.Title == song))
                    {
                        var newSong = new Song {
                            Title = song
                        };
                        songs.Add(newSong);
                    }

                    Data.SaveChanges();
                }
            }

            var album = new Album
            {
                Title      = value.Title,
                Genre      = value.Genre,
                ReleasedOn = value.ReleasedOn,
                Artists    = artists.All().Where(x => value.Artists.Contains(x.Name)).ToList(),
                Songs      = songs.All().Where(x => value.Songs.Contains(x.Title)).ToList()
            };

            AlbumsRepository.Add(album);
            Data.SaveChanges();
            return(this.StatusCode(HttpStatusCode.Created));
        }
        public void CheckGenenricRepositoryDeleteCustomer()
        {
            using (var context = new CustomerContext(builder.Options))
            {
                var customerRepository = new GenericRepository <Customer>(context);

                customerRepository.Add(customer);
                customerRepository.SaveChanges();

                customerRepository.Delete(customer.Id);
                var result = customerRepository.SaveChanges();
                Assert.IsTrue(result);
            }
        }
示例#21
0
        private static void ExportCountriesFromMSSqlToMySql(GenericRepository <Country> sqlCountriesRepo, GenericRepository <Country> mySqlCountriesRepo)
        {
            var countriesFromMSsql = sqlCountriesRepo.GetAll().ToList();

            foreach (var countryFromMSsql in countriesFromMSsql.ToList())
            {
                var country = new Country()
                {
                    Name = countryFromMSsql.Name
                };
                mySqlCountriesRepo.Add(country);
                mySqlCountriesRepo.SaveChanges();
            }
        }
示例#22
0
        //add House
        public void addHouse(int BlockId, String Floor, String HouseName, String Description, float Area)
        {
            House house = new House();

            house.Block.Id = BlockId;


            house.Floor       = Floor;
            house.HouseName   = HouseName;
            house.Description = Description;
            house.Area        = Area;

            allHouseInfo.Add(house);    //Add to house object
        }
示例#23
0
        public void AddTestServiceType()
        {
            GenericRepository <ServiceType> RepST = new GenericRepository <ServiceType>();
            ServiceType TestServiceType           = new ServiceType {
                nameService = "AddTestName", priceService = 100
            };
            int count = RepST.GetAll().Where(item => item.priceService == 100).Count();

            RepST.Add(TestServiceType);
            RepST.Save();
            Assert.AreEqual(count + 1, RepST.FindBy(item => item.priceService == 100).Count());
            RepST.Delete(TestServiceType);
            RepST.Save();
        }
        public void QGetAllTest()
        {
            Questions TestQuestion = new Questions {
                Question = "GetAllTestQuestion?", TimeQuestion = DateTime.Now, UserName = "******", UserMail = "*****@*****.**"
            };
            GenericRepository <Questions> RepQ = new GenericRepository <Questions>();
            int x = RepQ.GetAll().Count();

            RepQ.Add(TestQuestion);
            RepQ.Save();
            Assert.IsTrue(RepQ.GetAll().Count() > x);
            RepQ.Delete(TestQuestion);
            RepQ.Save();
        }
示例#25
0
        private async Task SaveEntity()
        {
            var Employee = new Employee()
            {
                Name           = txtName.Text.Trim(),
                Identification = mTxtIdentification.Text.Trim(),
                Schedule       = cbSchedule.Text,
                Commission     = (int)numericUpDown1.Value,
                Status         = cbStatus.Text
            };
            await _Employee.Add(Employee);

            await _Employee.SaveAsync();
        }
        public void AddTest()
        {
            log.Error("Test");
            var rep = new GenericRepository <Person>(_db.Persons);

            var p = new Person(5)
            {
                FirstName = "Claudia", LastName = "Stoever"
            };

            rep.Add(p);
            var res = rep.GetItems();

            Assert.AreEqual(res.Count(), 5);
        }
示例#27
0
        public void FindByTestClient()
        {
            Client TestClient = new Client {
                clientName = "FindByName", clientPhone = "FindByPhone"
            };
            GenericRepository <Client> RepС = new GenericRepository <Client>();

            RepС.Add(TestClient);
            RepС.Save();
            Client findByClient = RepС.FindBy(item => item.clientName == "FindByName").First();

            Assert.AreEqual(findByClient.clientPhone, "FindByPhone");
            RepС.Delete(TestClient);
            RepС.Save();
        }
示例#28
0
        public void AddsSuccesfully_When_InvokedWithCorrectValues()
        {
            var mockContext = DatabaseProvider.GetDatabase();

            var followeeRepository = new GenericRepository <Followee>(mockContext);

            var testFollowee1 = new Followee {
                ScreenName = "TestScreenName1", Bio = "TestBio1TestBio1TestBio1TestBio1TestBio1", FolloweeId = "TestFolloweeId1", Name = "TestFolloweeName1"
            };
            var testFollowee2 = new Followee {
                ScreenName = "TestScreenName2", Bio = "TestBio2TestBio2TestBio2TestBio2TestBio2", FolloweeId = "TestFolloweeId2", Name = "TestFolloweeName2"
            };
            var testFollowee3 = new Followee {
                ScreenName = "TestScreenName3", Bio = "TestBio3TestBio3TestBio3TestBio3TestBio3", FolloweeId = "TestFolloweeId3", Name = "TestFolloweeName3"
            };

            followeeRepository.Add(testFollowee1);
            followeeRepository.Add(testFollowee2);
            followeeRepository.Add(testFollowee3);

            mockContext.SaveChanges();

            Assert.AreEqual(3, mockContext.Followees.Count());
        }
        private async Task SaveEntity()
        {
            var Customer = new Customer()
            {
                Name           = txtName.Text.Trim(),
                Identification = mTxtIdentification.Text.Trim(),
                CreditCard     = txtCreditCard.Text.Trim(),
                CreditLimit    = (int)numericUpDown1.Value,
                PersonType     = cbType.Text,
                Status         = cbStatus.Text
            };
            await _Customer.Add(Customer);

            await _Customer.SaveAsync();
        }
示例#30
0
        public void DeleteTestClient()
        {
            GenericRepository <Client> RepC = new GenericRepository <Client>();
            Client TestClient = new Client {
                clientName = "DeleteTestClient", clientPhone = "DeleteTestPhone"
            };

            RepC.Add(TestClient);
            RepC.Save();
            int count = RepC.GetAll().Where(item => item.clientName == "DeleteTestClient").Count();

            RepC.Delete(TestClient);
            RepC.Save();
            Assert.AreEqual(count - 1, RepC.FindBy(item => item.clientName == "DeleteTestClient").Count());
        }
示例#31
0
        public async Task <Dictionary <string, string> > AddWithIdMapAsync(IEnumerable <WorkorderDoor> items)
        {
            var idMap = new Dictionary <string, string>();

            foreach (var item in items)
            {
                var oldItemId = item.Id;
                item.Id = null;
                var createdItem = await GenericRepository.Add(item);

                idMap.Add(oldItemId, createdItem.Id);
            }

            return(idMap);
        }
示例#32
0
        public void _Call_DbContext_SetAdded()
        {
            //Arrange
            var mockedDbContext = new Mock <IPhotoLifeEntities>();

            var repository = new GenericRepository <MockedGenericRepositoryType>(mockedDbContext.Object);

            var entity = new Mock <MockedGenericRepositoryType>();

            //Act
            repository.Add(entity.Object);

            //Assert
            mockedDbContext.Verify(mdb => mdb.SetAdded(entity.Object), Times.Once);
        }
示例#33
0
        public void FindByTestServiceType()
        {
            ServiceType TestServiceType = new ServiceType {
                nameService = "FindByName", priceService = 100
            };
            GenericRepository <ServiceType> RepST = new GenericRepository <ServiceType>();

            RepST.Add(TestServiceType);
            RepST.Save();
            ServiceType findByClient = RepST.FindBy(item => item.nameService == "FindByName").First();

            Assert.AreEqual(findByClient.priceService, 100);
            RepST.Delete(TestServiceType);
            RepST.Save();
        }
        public ActionResult Create(StudioViewModel studio)
        {
            if (ModelState.IsValid)
            {
                studios.Add(new Studio()
                {
                    Name    = studio.Name,
                    Address = studio.Address
                });
                studios.SaveChanges();
                return(Content("Done!"));
            }

            return(PartialView("_Create", studio));
        }
示例#35
0
        private async Task SaveEntity()
        {
            var Employee = new Employee()
            {
                Name           = txtName.Text.Trim(),
                Identification = mTxtIdentification.Text.Trim(),
                Schedule       = (EmployeeScheduleEnum)cbStatus.SelectedItem,
                Commission     = (int)numericUpDown1.Value,
                Status         = (StatusEnum)cbStatus.SelectedItem,
                EntryDate      = DateTime.Now
            };
            await _Employee.Add(Employee);

            await _Employee.SaveAsync();
        }
        public ResturantPackageEditViewModel Add(ResturantPackageEditViewModel _ResturantPackage)
        {
            if (_ResturantPackage.ID == 0)
            {
                var returned =
                    ResturantPackageRepo.Add(_ResturantPackage.toModel());
                UnitOfWork.commit();
                _ResturantPackage.ID = returned.ID;
            }
            if (_ResturantPackage.PackageItems != null &&
                _ResturantPackage.PackageItems.Count > 0)
            {
                foreach (var packageItem in _ResturantPackage.PackageItems)
                {
                    packageItem.ResturantPackageID = _ResturantPackage.ID;
                    PackageItemRepo.Add(packageItem.toModel());
                }
            }
            UnitOfWork.commit();



            return(_ResturantPackage);
        }
        public void AddMovieWhenMovieIsInvalidShouldThrowException()
        {
            //Arrange -> prepare the objects
            var repo = new GenericRepository<Movie>(new MoviesGalleryContext());
            var invalidMovie = new Movie()
            {
                Id = 1,
                Length = 20,
                Ration = 20
            };

            //Act -> perform some logic
            repo.Add(invalidMovie);
            repo.SaveChanges();

            //Asssert -> expect and exception
        }
        // POST api/Albums
        public IHttpActionResult Post([FromBody]AlbumServiceModel value)
        {
            var artists = new GenericRepository<Artist>(Data);
            var songs = new GenericRepository<Song>(Data);

            if (value.Artists != null)
            {
                foreach (var artist in value.Artists)
                {
                    if (!artists.All().Any(x => x.Name == artist))
                    {
                        var newArtist = new Artist { Name = artist };
                        artists.Add(newArtist);
                    }

                    Data.SaveChanges();
                }
            }

            if (value.Songs != null)
            {
                foreach (var song in value.Songs)
                {
                    if (!songs.All().Any(x => x.Title == song))
                    {
                        var newSong = new Song { Title = song };
                        songs.Add(newSong);
                    }

                    Data.SaveChanges();
                }
            }

            var album = new Album
            {
                Title = value.Title,
                Genre = value.Genre,
                ReleasedOn = value.ReleasedOn,
                Artists = artists.All().Where(x => value.Artists.Contains(x.Name)).ToList(),
                Songs = songs.All().Where(x => value.Songs.Contains(x.Title)).ToList()
            };

            AlbumsRepository.Add(album);
            Data.SaveChanges();
            return this.StatusCode(HttpStatusCode.Created);
        }
        public IHttpActionResult Post(CourseRequestModel model)
        {
            if (model == null)
            {
                return this.BadRequest();
            }

            var db = new StudentSystemDbContext();
            var coursesRepo = new GenericRepository<Course>(db);
            var courseToAdd = new Course
            {
                Name = model.Name,
                Description = model.Description
            };

            coursesRepo.Add(courseToAdd);
            coursesRepo.SaveChanges();
            return this.Ok();
        }
示例#40
0
        public void Add_NULL_Object_Must_Not_Add()
        {
            //
            // Arrange
            //
            var mockDbSet = new Mock<DbSet<IModel>>();
            var mockContext = new Mock<EFDbContext>();

            mockContext.Setup(x => x.Set<IModel>()).Returns(mockDbSet.Object);

            var repository = new GenericRepository<IModel>(mockContext.Object);
            //
            // Act
            //
            repository.Add(null);
            //
            // Assert
            //
            mockDbSet.Verify(x => x.Add(It.IsAny<IModel>()), Times.Never);
        }
        public ResponseMessageModel DoUpsert(SignageDigitalEntities db, Media model)
        {
            var repository = new GenericRepository<Media>(db);

            if (model.MediaId == EntityConstants.NULL_VALUE)
            {
                repository.Add(model);
            }
            else
            {
                repository.Update(model);
            }

            return new ResponseMessageModel
            {
                HasError = false,
                Title = ResShared.TITLE_REGISTER_SUCCESS,
                Message = ResShared.INFO_REGISTER_SAVED
            };
        }
        public IHttpActionResult Post(StudentRequestModel model)
        {
            if (model == null)
            {
                return this.BadRequest();
            }

            var db = new StudentSystemDbContext();
            var studentsRepo = new GenericRepository<Student>(db);
            var studentToAdd = new Student
            {
                FirstName = model.FirstName,
                LastName = model.LastName,
                Level = model.Level
            };

            studentsRepo.Add(studentToAdd);
            studentsRepo.SaveChanges();
            return this.Ok();
        }
        public void AddNews_Should_Successfully_Add_Specified_News_To_The_Repository()
        {
            var repository = new GenericRepository<News>(new NewsContext());
            var news = new News
            {
                Title = "Sample Title",
                Content = "Sample Content",
                PublishDate = DateTime.Now
            };

            repository.Add(news);
            repository.SaveChanges();

            var newsFromDb = repository.Find(news.Id);

            Assert.IsNotNull(newsFromDb);
            Assert.AreEqual(news.Content, newsFromDb.Content);
            Assert.AreEqual(news.Title, newsFromDb.Title);
            Assert.AreEqual(news.PublishDate, newsFromDb.PublishDate);
            Assert.IsTrue(newsFromDb.Id != 0);
        }
        public void AddMovieWhenMovieIsAddedToDbShouldReturnMovie()
        {
            //Arange -> prepare the objects
            var repo = new GenericRepository<Movie>(new MoviesGalleryContext());
            var movie = new Movie()
            {
                Id = 1,
                Length = 1,
                Ration = 3
            };

            //Act -> perform some logic
            repo.Add(movie);
            repo.SaveChanges();

            //Assert -> validate the results
            var movieFromDb = repo.GetById(movie.Id);

            Assert.IsNotNull(movieFromDb);
            Assert.AreEqual(movie.Length, movieFromDb.Length);
            Assert.AreEqual(movie.Ration, movieFromDb.Ration);
            Assert.IsTrue(movieFromDb.Id != 0);
        }
示例#45
0
        public void Add_Valid_Object_Must_Add()
        {
            //
            // Arrange
            //
            var mockModel = new Mock<IModel>();
            mockModel.Setup(x => x.Id).Returns(1);

            var mockDbSet = new Mock<DbSet<IModel>>();
            var mockContext = new Mock<EFDbContext>();

            mockContext.Setup(x => x.Set<IModel>()).Returns(mockDbSet.Object);

            var repository = new GenericRepository<IModel>(mockContext.Object);
            //
            // Act
            //
            repository.Add(mockModel.Object);
            //
            // Assert
            //
            mockDbSet.Verify(x => x.Add(It.IsAny<IModel>()), Times.Once);
        }
        // POST api/Songs
        public IHttpActionResult Post([FromBody]SongServiceModel value)
        {
            var artists = new GenericRepository<Artist>(Data);

            if (!artists.All().Any(x => x.Name == value.Artist))
            {
                var newArtist = new Artist { Name = value.Artist };
                artists.Add(newArtist);
                Data.SaveChanges();
            }

            var song = new Song
            {
                Title = value.Title,
                Genre = value.Genre,
                ReleasedOn = value.ReleasedOn,
                Artist = artists.All().FirstOrDefault(x => x.Name == value.Artist),
                ArtistId = artists.All().Where(x => x.Name == value.Artist).Select(x => x.ArtistId).FirstOrDefault()
            };

            SongsRepository.Add(song);
            Data.SaveChanges();
            return this.StatusCode(HttpStatusCode.Created);
        }
示例#47
0
        public void AddTest()
        {
            string cmdText = null;
            var cmdMock = new Mock<IDbCommand>();
            cmdMock.SetupSet(x => x.CommandText)
                .Callback(s => cmdText = s);

            var uowMock = new Mock<IUnitOfWork>();
            uowMock.Setup(x => x.GetCommand())
                .Returns(cmdMock.Object);                

            var rpstr = new GenericRepository<Area>(uowMock.Object);

            var area = new Area{Name = "Test Name", SOATO = "1703"};

            rpstr.Add(area);

            cmdMock.VerifySet(x => x.CommandText);
            cmdMock.Verify(x => x.ExecuteNonQuery());

            var etalon = "insert into Areas (Name,SOATO) values ('Test Name','1703')";

            Assert.AreEqual(etalon, cmdText);
        }
示例#48
0
 private static void ExportGirlsFromMSSqlToMySql(GenericRepository<Girl> sqlGirlsRepo, GenericRepository<Girl> mySqlGirlsRepo)
 {
     var girlsFromMSsql = sqlGirlsRepo.GetAll().ToList();
     foreach (var girlFromMSsql in girlsFromMSsql.ToList())
     {
         var girl = new Girl()
         {
             FirstName = girlFromMSsql.FirstName,
             LastName = girlFromMSsql.LastName,
             Age = girlFromMSsql.Age,
             BreastSizeId = girlFromMSsql.BreastSizeId,
             HairColorId = girlFromMSsql.HairColorId,
             CityId = girlFromMSsql.CityId,
             PricePerHour = girlFromMSsql.PricePerHour,
             Features = girlFromMSsql.Features,
             CountyId = girlFromMSsql.CountyId,
             // City = girlFromMSsql.City,
             // Country = girlFromMSsql.Country
         };
         mySqlGirlsRepo.Add(girl);
         mySqlGirlsRepo.SaveChanges();
     }
 }
示例#49
0
        private static void ExportOrdersFromMSSqlToMySql(GenericRepository<Order> sqlOrdersRepo, GenericRepository<Order> mysSqlOrdersRepo)
        {
            var girlsMysql = new GenericRepository<Girl>(new GirlAgencyMySql.Data.MySql());
            var customersMysq = new GenericRepository<Customer>(new GirlAgencyMySql.Data.MySql());
            foreach (var orderFromSql in sqlOrdersRepo.GetAll().ToList())
            {
                //Console.WriteLine(orderFromSql.);
                var order = new Order()
                {
                    GirlId =
                        girlsMysql
                            .GetAll()
                            .FirstOrDefault(g => g.FirstName == orderFromSql.Girl.FirstName && g.LastName == orderFromSql.Girl.LastName).Id,
                    CustomerId =
                        customersMysq
                            .GetAll()
                            .FirstOrDefault(c => c.FirstName == orderFromSql.Customer.FirstName &&
                                    c.LastName == orderFromSql.Customer.LastName).Id,
                    Duration = orderFromSql.Duration,
                    Date = orderFromSql.Date
                };

                mysSqlOrdersRepo.Add(order);
            }

            mysSqlOrdersRepo.SaveChanges();
        }
示例#50
0
        private static void ExportCustomerFromMSSqlToMySQL()
        {
            var mssqlClients = new GenericRepository<Customer>(new GirlsAgencyContext());
            var girlsMySql = new GenericRepository<Girl>(new GirlAgencyMySql.Data.MySql());
            var mysqlClients = new GenericRepository<Customer>(new GirlAgencyMySql.Data.MySql());
            foreach (var mssqlCustomer in mssqlClients.GetAll().ToList())
            {
                var customer = new Customer()
                {
                    CityId = mssqlCustomer.CityId,
                    CountryId = mssqlCustomer.CountryId,
                    FirstName = mssqlCustomer.FirstName,
                    LastName = mssqlCustomer.LastName,
                    Girls = GetGirls(mssqlCustomer, girlsMySql)
                };

                mysqlClients.Add(customer);
            }

            mysqlClients.SaveChanges();
        }
示例#51
0
        private static void ExportGirlsFromMSSqlToMySql()
        {
            var mssqlFeatures = new GenericRepository<Feature>(new GirlsAgencyContext());
            var mysllFeatures = new GenericRepository<Feature>(new GirlAgencyMySql.Data.MySql());

            foreach (var mssqlFeature in mssqlFeatures.GetAll().ToList())
            {
                var feature = new Feature()
                {
                    Name = mssqlFeature.Name
                };

                mysllFeatures.Add(feature);
            }

            mysllFeatures.SaveChanges();
        }
示例#52
0
 private static void ExportCitiesFromMSSqlToMySQL(GenericRepository<City> sqlCitiesRepo, GenericRepository<City> mySqlCitiesRepo)
 {
     var mysqlCountries = new GenericRepository<Country>(new GirlAgencyMySql.Data.MySql());
     var citiesFromMSsql = sqlCitiesRepo.GetAll().ToList();
     foreach (var cityFromMSsql in citiesFromMSsql.ToList())
     {
         var city = new City()
         {
             Name = cityFromMSsql.Name,
             CountryId = mysqlCountries.
                 GetAll()
                 .FirstOrDefault(n => n.CountryId == cityFromMSsql.CountryId).CountryId
         };
         mySqlCitiesRepo.Add(city);
         mySqlCitiesRepo.SaveChanges();
     }
 }
示例#53
0
 private static void ExportCountriesFromMSSqlToMySql(GenericRepository<Country> sqlCountriesRepo, GenericRepository<Country> mySqlCountriesRepo)
 {
     var countriesFromMSsql = sqlCountriesRepo.GetAll().ToList();
     foreach (var countryFromMSsql in countriesFromMSsql.ToList())
     {
         var country = new Country()
         {
             Name = countryFromMSsql.Name
         };
         mySqlCountriesRepo.Add(country);
         mySqlCountriesRepo.SaveChanges();
     }
 }
        public void ListAllMovieShouldReturnAllMovies()
        {
            var repo = new GenericRepository<Movie>(new MoviesGalleryContext());
            var fakeMovies = new List<Movie>()
            {
                new Movie()
                {
                    Id = 1,
                    Length = 1,
                    Ration = 1
                },
                new Movie()
                {
                    Id = 2,
                    Length = 2,
                    Ration = 2
                },
                new Movie()
                {
                    Id = 3,
                    Length = 3,
                    Ration = 3
                },
            };

            foreach (var fakeMovie in fakeMovies)
            {
                repo.Add(fakeMovie);
                repo.SaveChanges();
            }

            var fakeMovieLengths = fakeMovies.Select(m => m.Length).ToList();
            var movieDbLengths = repo.All().Select(m => m.Length).ToList();

            CollectionAssert.AreEqual(fakeMovieLengths, movieDbLengths);
        }
示例#55
0
        private static void ImportOrdersToDatabase(IEnumerable<Order> orders)
        {
            var sqlRepo = new GenericRepository<Order>(new GirlsAgencyContext());
            var girlRepo = new GenericRepository<Girl>(new GirlsAgencyContext());
            var ctx = new GirlsAgencyContext();
            foreach (var order in orders)
            {
                sqlRepo.Add(order);
                //ctx.Customers.
            }

            sqlRepo.SaveChanges();
        }
        public void DeleteMovieWhenExistingItemShouldDelete()
        {
            //Arrange -> prepare the objects
            var repo = new GenericRepository<Movie>(new MoviesGalleryContext());
            var movie = new Movie()
            {
                Id = 1,
                Length = 10,
                Ration = 10
            };

            //Act -> perform some logic
            repo.Add(movie);
            repo.SaveChanges();

            var movieFromDb = repo.GetById(movie.Id);

            repo.Delete(movieFromDb);
            repo.SaveChanges();

            var newMovieFromDb = repo.GetById(movie.Id);
            
            //Asssert -> expect and exception
            Assert.IsNull(newMovieFromDb);
        }
 public object Register(RegisterModel model)
 {
     GenericRepository<User> userRepo = new GenericRepository<User>();
     User user = new User()
     {
         Name = model.Name,
         Surname = model.Lastname,
         Email = model.Email,
         Username = model.Username,
         Password = CryptoHelper.HashPassword(model.Password),
         Gender = (model.Gender == "Female") ? true : false,
         Age = model.Age
     };
     userRepo.Add(user);
     return true;
 }
 public void Initialize()
 {
     storage = new GenericRepository<Course>(new FakeStorageContext<Course>());
     prereqs = new GenericRepository<PrerequisiteCourse>(new FakeStorageContext<PrerequisiteCourse>());
     controller = new CoursesController(storage, prereqs);
     storage.Add(new Course(){
         ID = 1,
         coursePrefix = "AAA",
         courseNumber = 123,
         courseTitle = "Test Course 1",
         courseDescription = "This is a test course for the testing framework.",
         minHours = 3,
         maxHours = 4,
         undergrad = true,
         variable = false
     });
     storage.Add(new Course()
     {
         ID = 2,
         coursePrefix = "BBB",
         courseNumber = 456,
         courseTitle = "Test Course 2",
         courseDescription = "This is a test course for the testing framework.",
         minHours = 5,
         maxHours = 6,
         graduate = true,
         variable = false
     });
     storage.Add(new Course(){
         ID = 3,
         coursePrefix = "AAA",
         courseNumber = 122,
         courseTitle = "Test Course 3",
         courseDescription = "This is a test course for the testing framework.",
         minHours = 7,
         maxHours = 8,
         undergrad = true,
         variable = true
     });
 }
        private async Task InsertOrUpdateArticleAndTraces(ArticleModel article, IDataService dataService)
        {
            try
            {
                using (var unitOfWork = new UnitOfWork(false))
                {
                    article.PrepareForSave();

                    var addimages = new List<ImageModel>();
                    var updateimages = new List<ImageModel>();
                    //article

                    var addgalleries = new List<GalleryModel>();
                    var updategalleries = new List<GalleryModel>();
                    var addgalleryImages = new List<ImageModel>();
                    var updategalleryImages = new List<ImageModel>();
                    var addcontents = new List<ContentModel>();
                    var updatecontents = new List<ContentModel>();


                    var articleRepo = new GenericRepository<ArticleModel, ArticleEntity>(dataService);
                    var imageRepo = new GenericRepository<ImageModel, ImageEntity>(dataService);
                    var galleryRepo = new GenericRepository<GalleryModel, GalleryEntity>(dataService);
                    var contentRepo = new GenericRepository<ContentModel, ContentEntity>(dataService);

                    if (article.LeadImage != null)
                    {
                        if (article.LeadImage.Id == 0)
                            addimages.Add(article.LeadImage);
                        else
                            updateimages.Add(article.LeadImage);
                    }
                    if (article.Content != null && article.Content.Any())
                    {
                        foreach (var contentModel in article.Content)
                        {
                            if (contentModel.Id == 0)
                                addcontents.Add(contentModel);
                            else
                                updatecontents.Add(contentModel);

                            if (contentModel.ContentType == ContentType.Gallery && contentModel.Gallery != null)
                            {
                                if (contentModel.Gallery.Id == 0)
                                    addgalleries.Add(contentModel.Gallery);
                                else
                                    updategalleries.Add(contentModel.Gallery);

                                if (contentModel.Gallery.Images != null)
                                {
                                    foreach (var imageModel in contentModel.Gallery.Images)
                                    {
                                        if (imageModel.Id == 0)
                                            addgalleryImages.Add(imageModel);
                                        else
                                            updategalleryImages.Add(imageModel);
                                    }
                                    addgalleryImages.AddRange(contentModel.Gallery.Images);
                                }
                            }
                            else if (contentModel.ContentType == ContentType.Image && contentModel.Image != null)
                            {
                                if (contentModel.Image.Id == 0)
                                    addimages.Add(contentModel.Image);
                                else
                                    updateimages.Add(article.LeadImage);
                            }
                        }
                    }

                    if (article.Themes != null)
                        await _themeRepository.SetThemesByArticle(article.Id, article.Themes.Select(t => t.Id).ToList());

                    if (article.RelatedArticles != null)
                        await SetRelatedArticlesByArticleId(article.Id, article.RelatedArticles.Select(t => t.Id).ToList(), dataService);

                    await imageRepo.AddAll(addimages);
                    await galleryRepo.AddAll(addgalleries);
                    await imageRepo.AddAll(addgalleryImages);
                    await contentRepo.AddAll(addcontents);

                    if (article.Id == 0)
                        await articleRepo.Add(article);
                    else
                        await articleRepo.Update(article);

                    await imageRepo.UpdateAll(updateimages);
                    await galleryRepo.UpdateAll(updategalleries);
                    await imageRepo.UpdateAll(updategalleryImages);
                    await contentRepo.UpdateAll(updatecontents);

                    await _themeRepository.SaveChanges();

                    await unitOfWork.Commit();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.Log(LogLevel.Error, this, "Article cannot be saved", ex);
            }
        }
        // PUT api/Songs/5
        public IHttpActionResult Put(int id, [FromBody]SongServiceModel value)
        {
            var songToUpdate = SongsRepository.All().FirstOrDefault(x => x.SongId == id);

            if (songToUpdate == null)
            {
                return this.BadRequest("No such song");
            }

            if (value.Title != null)
            {
                songToUpdate.Title = value.Title;
            }

            if (value.Genre != null)
            {
                songToUpdate.Genre = value.Genre;
            }

            if (value.ReleasedOn != null)
            {
                songToUpdate.ReleasedOn = value.ReleasedOn;
            }

            if (value.Artist != null)
            {
                var artists = new GenericRepository<Artist>(Data);

                if (!artists.All().Any(x => x.Name == value.Artist))
                {
                    var newArtist = new Artist { Name = value.Artist };
                    artists.Add(newArtist);
                    Data.SaveChanges();
                }

                songToUpdate.Artist = artists.All().FirstOrDefault(x => x.Name == value.Artist);
                songToUpdate.ArtistId =
                    artists.All().Where(x => x.Name == value.Artist).Select(x => x.ArtistId).FirstOrDefault();
            }

            Data.SaveChanges();

            return this.ResponseMessage(new HttpResponseMessage(HttpStatusCode.Accepted));
        }