Ejemplo n.º 1
0
        public bool Run()
        {
            if (_countryService.Get().Count > 0)
            {
                return(false);
            }

            var jsonData      = File.ReadAllText(countriesJsonPath);
            var seedCountries = JsonConvert.DeserializeObject <List <Country> >(jsonData);

            foreach (var country in seedCountries)
            {
                var output = _countryService.Create(country);

                var imagepath = Path.Combine(flagFolderPath, $"{country.Alpha2Code}.png");
                if (File.Exists(imagepath))
                {
                    var flagImage = File.ReadAllBytes(imagepath);

                    _flagService.Create(new FlagImage()
                    {
                        Id = output.Id, Value = flagImage
                    });
                }
            }

            return(true);
        }
        public CountriesControllerTests()
        {
            var list = new List <Country>
            {
                new Country {
                    Id = 1, Name = "test 1"
                },
                new Country {
                    Id = 2, Name = "test 2"
                }
            }.AsQueryable();

            var mockContext                   = Substitute.For <TtContext>();
            var countryRepository             = Substitute.For <Repository <Country> >(mockContext);
            var organizationCountryRepository = Substitute.For <Repository <OrganizationCountry> >(mockContext);
            var organizationRepository        = Substitute.For <Repository <Organization> >(mockContext);

            _service = Substitute.For <CountryService>(countryRepository, organizationCountryRepository, organizationRepository);
            _service.GetList().Returns(list);
            _service.GetItem(Arg.Any <int>()).Returns(new Country {
                Id = 1, Name = "test 1"
            });
            _service.Create(Arg.Any <Country>());
            _service.Update(Arg.Any <int>(), Arg.Any <Country>());
            _service.Delete(Arg.Any <int>());

            var mockLogger = Substitute.For <ILoggerFactory>();

            _controller = new CountriesController(_service, mockLogger);
        }
Ejemplo n.º 3
0
        public async void Create_ErrorsOccurred_ShouldReturnErrorResponse()
        {
            var mock          = new ServiceMockFacade <ICountryService, ICountryRepository>();
            var model         = new ApiCountryServerRequestModel();
            var validatorMock = new Mock <IApiCountryServerRequestModelValidator>();

            validatorMock.Setup(x => x.ValidateCreateAsync(It.IsAny <ApiCountryServerRequestModel>())).Returns(Task.FromResult(new FluentValidation.Results.ValidationResult(new List <ValidationFailure>()
            {
                new ValidationFailure("text", "test")
            })));
            var service = new CountryService(mock.LoggerMock.Object,
                                             mock.MediatorMock.Object,
                                             mock.RepositoryMock.Object,
                                             validatorMock.Object,
                                             mock.DALMapperMockFactory.DALCountryMapperMock,
                                             mock.DALMapperMockFactory.DALCountryRequirementMapperMock,
                                             mock.DALMapperMockFactory.DALDestinationMapperMock);

            CreateResponse <ApiCountryServerResponseModel> response = await service.Create(model);

            response.Should().NotBeNull();
            response.Success.Should().BeFalse();
            validatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiCountryServerRequestModel>()));
            mock.MediatorMock.Verify(x => x.Publish(It.IsAny <CountryCreatedNotification>(), It.IsAny <CancellationToken>()), Times.Never());
        }
Ejemplo n.º 4
0
 public ActionResult Create(Country country)
 {
     // TODO: Add insert logic here
     if (ModelState.IsValid)
     {
         _CountryService.Create(country);
         return(RedirectToAction("Index"));
     }
     return(View(country));
 }
Ejemplo n.º 5
0
        public void CreateCountry()
        {
            var country = new FormModel
            {
                Name = "Test3",
            };

            var result = countryService.Create(country);

            Assert.IsNotNull(result);
        }
Ejemplo n.º 6
0
        public void CreateTest()
        {
            var country = new Country {
                Id = 1, OrganizationCountries = { new OrganizationCountry {
                                                      OrganizationId = 1
                                                  } }
            };

            _service.Create(country);
            _countryRepository.Received(1).Create(country);
        }
Ejemplo n.º 7
0
        public void Create_Country()
        {
            CountryView view = ObjectFactory.CreateCountryView(1);

            service.Create(view);

            Country     actual   = context.Set <Country>().AsNoTracking().Single(model => model.Id != country.Id);
            CountryView expected = view;

            Assert.Equal(expected.CreationDate, actual.CreationDate);

            Assert.True(false, "Not all properties tested");
        }
Ejemplo n.º 8
0
        private static void AddCountry(BancoContext context, CountryService service)
        {
            string name = "";

            Console.Write("Write the name: ");
            name = Console.ReadLine();
            Country country = new Country()
            {
                Name = name
            };

            service.Create(country);
            Paused();
        }
Ejemplo n.º 9
0
        public void Create_CountryNull_ThrowsArgumentNullException()
        {
            //Arrange
            Country invalidCountry = null;

            Mock <ICountryRepository> countryRepository = new Mock <ICountryRepository>();
            ICountryService           countryService    = new CountryService(countryRepository.Object);

            //Act
            Action actual = () => countryService.Create(invalidCountry);

            //Assert
            Assert.Throws <ArgumentNullException>(actual);
        }
Ejemplo n.º 10
0
        public void TestCreate()
        {
            Mock <ICountryDao> countryDaoMock = new Mock <ICountryDao>();

            countryDaoMock.Setup(x => x.Create(It.IsAny <Country>()));

            string countryName = "D";

            ICountryService countryService = new CountryService(countryDaoMock.Object);

            countryService.Create(countryName);

            countryDaoMock.Verify(x => x.Create(It.Is <Country>(y => y.Name == countryName)));
        }
        public void CountryService_CheckInsert_Created()
        {
            // Arrange
            var mock = new Mock <ICountryRepository>();

            mock.Setup(repo => repo.Create(StubsObjects.Country.ToEntity()))
            .Returns(() => Task.CompletedTask);

            var service = new CountryService(mock.Object);

            // Act
            var result = service.Create(StubsObjects.Country).Result;

            // Assert
            Assert.Equal(StatusCode.Created, result);
        }
        public void CountryService_CheckInsert_ThrowNameException()
        {
            // Arrange
            var mock = new Mock <ICountryRepository>();

            mock.Setup(repo => repo.Create(new CountryEntity()))
            .Returns(() => Task.CompletedTask);

            var service = new CountryService(mock.Object);

            // Act
            var ex = Assert.ThrowsAnyAsync <NameException>(() => service.Create(new Country()));

            // Assert
            Assert.Equal("The Country have not empty or null name.", ex.Result.Message);
        }
Ejemplo n.º 13
0
        public void Create_IdSpecified_ThrowsArgumentException()
        {
            //Arrange
            Country invalidCountry = new Country {
                Id = 1, Name = "Netherlands"
            };

            Mock <ICountryRepository> countryRepository = new Mock <ICountryRepository>();
            ICountryService           countryService    = new CountryService(countryRepository.Object);

            //Act
            Action actual = () => countryService.Create(invalidCountry);

            //Assert
            Assert.Throws <ArgumentException>(actual);
        }
Ejemplo n.º 14
0
        public ActionResult Save(CountryEditorModel model, string @return)
        {
            var country = new Country();

            model.UpdateTo(country);

            if (country.Id > 0)
            {
                _countryService.Update(country);
            }
            else
            {
                _countryService.Create(country);
            }

            return(AjaxForm().RedirectTo(@return));
        }
Ejemplo n.º 15
0
        public async void Create()
        {
            var mock  = new ServiceMockFacade <ICountryRepository>();
            var model = new ApiCountryRequestModel();

            mock.RepositoryMock.Setup(x => x.Create(It.IsAny <Country>())).Returns(Task.FromResult(new Country()));
            var service = new CountryService(mock.LoggerMock.Object,
                                             mock.RepositoryMock.Object,
                                             mock.ModelValidatorMockFactory.CountryModelValidatorMock.Object,
                                             mock.BOLMapperMockFactory.BOLCountryMapperMock,
                                             mock.DALMapperMockFactory.DALCountryMapperMock,
                                             mock.BOLMapperMockFactory.BOLProvinceMapperMock,
                                             mock.DALMapperMockFactory.DALProvinceMapperMock);

            CreateResponse <ApiCountryResponseModel> response = await service.Create(model);

            response.Should().NotBeNull();
            mock.ModelValidatorMockFactory.CountryModelValidatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiCountryRequestModel>()));
            mock.RepositoryMock.Verify(x => x.Create(It.IsAny <Country>()));
        }
Ejemplo n.º 16
0
        private void PrepareCountryImport(StructureInfo structureInfo)
        {
            foreach (var country in structureInfo.Website.Countries)
            {
                var existCountry = _countryService.Get(country.Id)?.MakeWritableClone();
                if (existCountry != null)
                {
                    structureInfo.Mappings.Add(country.SystemId, existCountry.SystemId);
                    foreach (var countryToTaxClassLink in country.TaxClassLinks)
                    {
                        var taxclass = existCountry.TaxClassLinks.FirstOrDefault(x => x.TaxClassSystemId == structureInfo.Id(countryToTaxClassLink.TaxClassSystemId));
                        if (taxclass != null)
                        {
                            taxclass.VatRate = countryToTaxClassLink.VatRate;
                        }
                        else
                        {
                            existCountry.TaxClassLinks.Add(new CountryToTaxClassLink(structureInfo.Id(countryToTaxClassLink.TaxClassSystemId))
                            {
                                VatRate = countryToTaxClassLink.VatRate
                            });
                        }
                    }
                    _countryService.Update(existCountry);
                }
                else
                {
                    var countryId = Guid.NewGuid();
                    structureInfo.Mappings.Add(country.SystemId, countryId);

                    var newCountry = country.MakeWritableClone();
                    newCountry.SystemId      = countryId;
                    newCountry.TaxClassLinks = country.TaxClassLinks.Select(x => new CountryToTaxClassLink(structureInfo.Id(x.TaxClassSystemId))
                    {
                        VatRate = x.VatRate
                    }).ToList();
                    newCountry.CurrencySystemId = structureInfo.Id(country.CurrencySystemId);
                    _countryService.Create(newCountry);
                }
            }
        }
Ejemplo n.º 17
0
        public async void Create_NoErrorsOccurred_ShouldReturnResponse()
        {
            var mock = new ServiceMockFacade <ICountryService, ICountryRepository>();

            var model = new ApiCountryServerRequestModel();

            mock.RepositoryMock.Setup(x => x.Create(It.IsAny <Country>())).Returns(Task.FromResult(new Country()));
            var service = new CountryService(mock.LoggerMock.Object,
                                             mock.MediatorMock.Object,
                                             mock.RepositoryMock.Object,
                                             mock.ModelValidatorMockFactory.CountryModelValidatorMock.Object,
                                             mock.DALMapperMockFactory.DALCountryMapperMock,
                                             mock.DALMapperMockFactory.DALProvinceMapperMock);

            CreateResponse <ApiCountryServerResponseModel> response = await service.Create(model);

            response.Should().NotBeNull();
            response.Success.Should().BeTrue();
            mock.ModelValidatorMockFactory.CountryModelValidatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiCountryServerRequestModel>()));
            mock.RepositoryMock.Verify(x => x.Create(It.IsAny <Country>()));
            mock.MediatorMock.Verify(x => x.Publish(It.IsAny <CountryCreatedNotification>(), It.IsAny <CancellationToken>()));
        }
Ejemplo n.º 18
0
        public void Create_CountryValid_ReturnsCreatedCountryWithId()
        {
            //Arrange
            Country validCountry = new Country {
                Name = "Netherlands"
            };
            Country expected = new Country {
                Id = 1, Name = validCountry.Name
            };

            Mock <ICountryRepository> countryRepository = new Mock <ICountryRepository>();

            countryRepository.Setup(repo => repo.Create(validCountry)).
            Returns(expected);

            ICountryService countryService = new CountryService(countryRepository.Object);

            //Act
            Country actual = countryService.Create(validCountry);

            //Assert
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 19
0
        void menuCountry(BancoContext context)
        {
            CountryService service = new CountryService(new UnitOfWork(context), new CountryRepository(context));
            char           seguir  = 's';

            do
            {
                System.Console.Clear();
                System.Console.WriteLine("MENU COUNTRY");
                System.Console.WriteLine("1º) Crear Country");
                System.Console.WriteLine("2º) Eliminar Country");
                System.Console.WriteLine("3º) Listar Country");
                System.Console.WriteLine("4º) Regresar");
                System.Console.Write("Seleccione una opción:  ");
                switch (System.Console.Read())
                {
                case '1':
                    System.Console.Clear();
                    System.Console.WriteLine("Crear Country");
                    #region  Crear Country
                    string texto = Microsoft.VisualBasic.Interaction.InputBox(
                        "Texto de la pregunta",
                        "Titulo del diálogo",
                        "Respuesta por defecto");
                    Country country = new Country()
                    {
                        Name = texto
                    };

                    service.Create(country);

                    #endregion
                    System.Console.ReadKey();
                    // Continuar lógica y extraer métodos //
                    break;

                case '2':
                    System.Console.Clear();
                    System.Console.WriteLine("Eliminar Country");
                    #region  Eliminar Country
                    string  nombre = "venezuela";
                    Country coun   = service.Find(nombre);
                    service.Delete(coun);
                    #endregion
                    System.Console.ReadKey();
                    // Continuar lógica y extraer métodos //
                    break;

                case '3':
                    System.Console.Clear();
                    System.Console.WriteLine("Listar Country");
                    #region  Listar Country
                    List <Country> countries = service.GetAll().ToList();
                    foreach (var item in countries)
                    {
                        System.Console.WriteLine(item.Name);
                    }
                    #endregion
                    // Continuar lógica y extraer métodos //
                    System.Console.ReadKey();
                    break;

                case '4':
                    System.Console.Clear();
                    System.Console.WriteLine("Regresando al principal..   ");
                    System.Console.ReadKey();
                    seguir = 'n';
                    break;
                }
            } while (seguir == 's');
        }
Ejemplo n.º 20
0
 public ActionResult Create(CountryViewModel countryVM)
 {
     countryService.Create(countryVM);
     return(RedirectToAction("Index"));
 }
Ejemplo n.º 21
0
        private void BenDBTests(CountryService countryService, RouteService routeService)
        {
            try
            {

                CountryDataHelper cdh = new CountryDataHelper();

                // create country if doesn't exist
                Country country = new Country { ID = 1, Name = "Wellington", Code = "WLG" };
                if (!countryService.Exists(country))
                {
                    country = countryService.Create("Wellington", "WLG");
                }

                country = countryService.Update(country.ID, "WLN");
                country = countryService.Update(country.ID, "BEN");

                // get latest version
                Country loadedCountry = countryService.Get(country.ID);

                cdh.LoadAll(DateTime.Now);

                // create new zealand
                country = new Country { Name = "New Zealand", Code = "NZ" };
                if (!countryService.Exists(country))
                {
                    country = countryService.Create(country.Name, country.Code);
                }

                // create australia
                country = new Country { Name = "Australia", Code = "AUS" };
                if (!countryService.Exists(country))
                {
                    country = countryService.Create(country.Name, country.Code);
                }

                // load all countries
                var allCountries = countryService.GetAll();

                // create christchurch depot
                RouteNode routeNode = new DistributionCentre("Christchurch");
                if (!locationService.Exists(routeNode))
                {
                    routeNode = locationService.CreateDistributionCentre("Christchurch");
                }

                // wellington depot
                routeNode = new DistributionCentre("Wellington");
                if (!locationService.Exists(routeNode))
                {
                    routeNode = locationService.CreateDistributionCentre("Wellington");
                }

                // australia port
                country = countryService.GetAll().AsQueryable().First(t => t.Name == "Australia");
                var destination = new InternationalPort(country);
                if (!locationService.Exists(destination))
                {
                    destination = locationService.CreateInternationalPort(country.ID);
                }

                // get a company
                var company = new Company() { Name = "NZ Post" };
                if (!companyService.Exists(company))
                {
                    company = companyService.Create(company.Name);
                }

                // create a new route
                Route route = new Route()
                    {
                        Origin = routeNode,
                        Destination = destination,
                        Company = company,
                        Duration = 300,
                        MaxVolume = 5000,
                        MaxWeight = 5000,
                        CostPerCm3 = 3,
                        CostPerGram = 5,
                        TransportType = TransportType.Air,
                        DepartureTimes = new List<WeeklyTime> { new WeeklyTime(DayOfWeek.Monday, 5, 30) }
                    };

                var routeDataHelper = new RouteDataHelper();

                int id = routeDataHelper.GetId(route);
                Logger.WriteLine("Route id is: " + id);
                if (id == 0)
                {
                    routeDataHelper.Create(route);
                }

                //route = routeDataHelper.Load(1);

                // edit departure times
                route.DepartureTimes.Add(new WeeklyTime(DayOfWeek.Wednesday, 14, 35));

                // update
                //routeDataHelper.Update(route);

                // delete
                routeDataHelper.Delete(route.ID);

                var routes = routeDataHelper.LoadAll();

                var delivery = new Delivery { Origin = routeNode, Destination = destination, Priority = Priority.Air, WeightInGrams = 200, VolumeInCm3 = 2000, TotalPrice = 2500, TotalCost = 1000, TimeOfRequest = DateTime.UtcNow, TimeOfDelivery = DateTime.UtcNow.AddHours(5.5), Routes = new List<RouteInstance> { new RouteInstance(route, DateTime.UtcNow)} };

                var deliveryDataHelper = new DeliveryDataHelper();

                deliveryDataHelper.Create(delivery);

                deliveryDataHelper.Load(delivery.ID);

                deliveryDataHelper.LoadAll();

                var price = new Price { Origin = routeNode, Destination = destination, Priority = Priority.Air, PricePerCm3 = 3, PricePerGram = 5 };
                var priceDataHelper = new PriceDataHelper();
                //priceDataHelper.Create(price);

                price.PricePerGram = 10;
                price.ID = 1;

                Logger.WriteLine(price.ToString());

            }
            catch (Exception e)
            {
                Logger.WriteLine(e.Message);
                Logger.Write(e.StackTrace);
            }
        }
Ejemplo n.º 22
0
        public ActionResult <Country> Create(Country items)
        {
            _service.Create(items);

            return(CreatedAtRoute("GetCountry", new { id = items.Id.ToString() }, items));
        }
Ejemplo n.º 23
0
        public ActionResult <Country> Create(Country country)
        {
            _countryService.Create(country);

            return(CreatedAtRoute("GetCountry", new { id = country.Id.ToString() }, country));
        }
Ejemplo n.º 24
0
        public IActionResult Create(Country country)
        {
            country = _countryService.Create(country);

            return(CreatedAtRoute(nameof(GetById), new { id = country.Id.ToString() }, country));
        }