public void Add_NullCountry_ReturnsNullAndDoesNotInsert() { var result = _countryRepository.Add(null); Check.That(result).IsNull(); Check.That(_countryRepository.All()).CountIs(0); }
public async Task <IHttpActionResult> UpdateAsync(int id, CountryDto country) { var countryInDb = await _repository.GetAsync(id); if (countryInDb == null) { return(NotFound()); } _repository.Add(country.Map <Country>()); await _unitOfWork.CompleteAsync(); return(Ok()); }
public async Task <IActionResult> CreateCountry([FromBody] CountryDetailsDto countryResource) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (_countryRepo.CheckCountryCode(countryResource.Code1, countryResource.Code1)) { ModelState.AddModelError("Error", "The Country with this Code already exists."); return(BadRequest(ModelState)); } var country = _mapper.Map <CountryDetailsDto, Country>(countryResource); country.Deleted = false; country.Protected = false; _countryRepo.Add(country); await _unitOfWork.CompleteAsync(); country = await _countryRepo.GetCountry(country.Id); var result = _mapper.Map <Country, CountryDetailsDto>(country); return(Ok(result)); } catch (Exception ex) { ModelState.AddModelError("Error", "An error occured while performing this operation."); return(BadRequest(ModelState)); } }
public IActionResult Save(Country_VM country_VM) { if (country_VM != null) { if (country_VM.CountryID > 0) { if (_countryRepository.Update(country_VM, this.loginUserId) > 0) { TempData["Status"] = Helper.success_code; TempData["Message"] = Message.countryUpdated; } else { TempData["Message"] = Message.countryUpdateError; } } else { if (_countryRepository.Add(country_VM, this.loginUserId) > 0) { TempData["Status"] = Helper.success_code; TempData["Message"] = Message.countryAdded; } else { TempData["Message"] = Message.countryAddedError; } } } return(RedirectToAction("List", "Country")); }
public Country CreateCountry(CreateCountryParameters parameters) { var entity = entityService.CreateEntity(parameters.CountryName, EntityTypeEnum.Country); Country country = new Country() { ID = entity.EntityID, Color = parameters.Color, CountryPolicy = new CountryPolicy(), GreetingMessage = $"Welcome in {parameters.CountryName}!" }; var policy = country.CountryPolicy; policy.CountryCompanyBuildLawAllowHolder = (int)LawAllowHolderEnum.PresidentAndCongress; policy.TreasuryVisibilityLawAllowHolderID = (int)LawAllowHolderEnum.PresidentAndCongress; policy.CountryID = entity.EntityID; Currency currency = new Currency() { ShortName = parameters.CurrencyShortName, Name = parameters.CurrencyName, Symbol = parameters.CurrencySymbol, ID = parameters.CurrencyID }; country.Currency = currency; countryRepository.Add(country); countryRepository.SaveChanges(); CreateNewPresidentVoting(country, GameHelper.CurrentDay + country.CountryPolicy.PresidentCadenceLength); CreateNewCongressCandidateVoting(country, GameHelper.CurrentDay + country.CountryPolicy.CongressCadenceLength); Console.WriteLine($"Country {parameters.CountryName} created!"); return(country); }
public bool Save(List <Country> reasons, string state = "") { try { if (!string.IsNullOrEmpty(state) && state == "Save") { reasons.ForEach(x => reasonRepository.Add(x)); } else if (!string.IsNullOrEmpty(state) && state == "Update") { reasons.ForEach(x => reasonRepository.Update(x)); } } catch (DbEntityValidationException e) { string exceptionMessage = string.Empty; foreach (var eve in e.EntityValidationErrors) { exceptionMessage = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { exceptionMessage += string.Format("\n\n- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw new Exception(exceptionMessage); } catch (Exception ex) { throw new Exception(ex.Message); } return(true); }
public async Task <IActionResult> AddCountry([FromBody] CountryDTO country) { if (!ModelState.IsValid) { return(BadRequest("Invalid input")); } Country newCountry = new Country() { name = country.name, cities = country.cities }; if (_countryRepository.CheckIfExists(newCountry)) { return(Conflict("Country already exists")); } bool created = await _countryRepository.Add(newCountry); if (created) { return(Created("", newCountry)); } return(Conflict()); }
public async Task <IActionResult> New([FromBody] Country newCountry) { try { if (newCountry == null) { return(NotFound("New country cannot be null")); } if (newCountry.Name == string.Empty) { return(BadRequest("Country name cannot be empty")); } _countryRepo.Add(newCountry); await _countryRepo.SaveAsync(); return(Ok()); } catch (Exception ex) { _logger.LogError(ex.Message); var exMsg = new HttpResponseMessage(HttpStatusCode.InternalServerError); throw new System.Web.Http.HttpResponseException(exMsg); } }
public void Add(Country country) { ValidateModel(country); country.Id = Guid.NewGuid(); _countryRepository.Add(country); }
public void add(country country) { if (String.IsNullOrWhiteSpace(country.country1)) { throw new InvalidInputException("Must include country name"); } _repository.Add(country); }
public void AddState(params Country[] country) { foreach (var countries in country) { countries.Id = Guid.NewGuid(); } ; _countryRepository.Add(country); }
async Task <CountryDTO> IService <CountryDTO, int> .Add(CountryDTO entity) { Country country = (await _countryRepository.Get(prop => prop.Name == entity.Name)).FirstOrDefault(); if (country == null) { country = await _countryRepository.Add(_mapper.Map <CountryDTO, Country>(entity)); } return(_mapper.Map <Country, CountryDTO>(country)); }
public IActionResult AddCountry(JsonElement request) { var countryId = request.GetProperty("countryId").GetInt32(); var countryName = request.GetProperty("cityName").GetString(); _countryRepository.Add(new Country() { Name = countryName }); return(Ok("Successful")); }
public ActionResult Create([FromForm] Country country) { try { _repository.Add(country); return(RedirectToAction(nameof(Index))); } catch { return(new BadRequestResult()); } }
public Task <Country> Add(Country entity) { try { var id = countryRepository.Add(entity); var result = countryRepository.GetById(id.ToString()); return(result); } catch (Exception ex) { throw new RestException(HttpStatusCode.NotFound, ex.Message); } }
private static void FillTables(IStateRepository stateRepository, ICountryRepository countryRepository) { string json = File.ReadAllText(@"Resources\inputStates.txt"); List <State> states = JsonConvert.DeserializeObject <List <State> >(json); states = states.FindAll(s => !string.IsNullOrEmpty(s.Code) && !string.IsNullOrEmpty(s.Country)); states = states.FindAll(s => s.Country == "CO"); Console.WriteLine($"Full Table: {stateRepository.Add(states)}"); json = File.ReadAllText(@"Resources\inputCountries.txt"); List <Country> countries = JsonConvert.DeserializeObject <List <Country> >(json); countries = countries.FindAll(c => !string.IsNullOrEmpty(c.Code) && (c.Code == "CO" || c.Code == "US")); Console.WriteLine($"Full Table: {countryRepository.Add(countries)}"); }
public async Task <IActionResult> Create([FromBody] Country item) { if (item.CountryId == 0) { await _repository.Add(item); return(CreatedAtRoute("GetCountry", new { Controller = "Country", id = item.CountryId }, item)); } else { if (item.CountryId > 0) { await _repository.Update(item); } } return(BadRequest()); }
public ActionResult Add(CountryDTO entity) { try { Country country = new Country { Name = entity.Name }; countryRepository.Add(country); countryRepository.Save(); return(Json(country, JsonRequestBehavior.DenyGet)); } catch (Exception e) { } return(Json(false, JsonRequestBehavior.DenyGet)); }
public ActionResult CountryInsert(CountryViewModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } var countryModel = new Country() { Title = model.Title, Show = model.Show }; _countryRepository.Add(countryModel); _countryRepository.Complete(); return(Json("")); }
public IHttpActionResult Post([FromBody] Country country) { if (!ModelState.IsValid) { return(BadRequest()); } if (country == null) { return(BadRequest()); } countryRepository.Add(country); var response = Request.CreateResponse(HttpStatusCode.Created, country); response.Headers.Location = Request.RequestUri; return(ResponseMessage(response)); }
public async Task <ActionResult <Response> > CreateCountry(CountryModel model) { var country = model.ToEntity(); if (country.Invalid) { return(BadRequest(ResponseHelper.CreateResponse("Informações inválidas para cadastrar um país", model))); } if (await _countryRepository.CountryExist(country)) { return(BadRequest(ResponseHelper.CreateResponse("Esse país já foi cadastrado", model))); } _countryRepository.Add(country); return(Ok(ResponseHelper.CreateResponse("País cadastrado com sucesso!", (CountryModel)country))); }
public async Task <Result> CreateAsync(CreateCountryDto createCountryDto) { _logger.LogTrace("[CountryService:CreateAsync] Starting processing the command"); if (await _countryRepository.ExistsByCountryNameAsync(createCountryDto.Name)) { _logger.LogInformation( $"[CountryService:CreateAsync] Error: The country with name {createCountryDto.Name} already exists"); return(Result.Fail(new Error($"The country with name {createCountryDto.Name} already exists") .WithMetadata("errCode", "errCountryAlreadyExistsByName"))); } if (await _countryRepository.ExistsByCountryCodeAsync(createCountryDto.Code)) { _logger.LogInformation( $"[CountryService:CreateAsync] Error: The country with name {createCountryDto.Name} already exists"); return(Result.Fail(new Error($"The country with code {createCountryDto.Code} already exists") .WithMetadata("errCode", "errCountryAlreadyExistsByCode"))); } var country = new Country(createCountryDto.Name, createCountryDto.Code); _countryRepository.Add(country); var result = await _countryRepository.UnitOfWork.SaveEntitiesAsync(); if (!result) { _logger.LogInformation( "[CountryService:CreateAsync] Error: An error happened while trying to create the country"); return(Result.Fail(new Error("An error happened while trying to create the country") .WithMetadata("errCode", "errDbSaveFail"))); } var subject = "country"; _stanIntegrationEventBus.Publish(subject, "created", new CountryCreatedIntegrationEvent(country.Uuid, country.Name, country.Code)); return(Result.Ok()); }
public async Task <Address> EnsureAsync(Address address) { var existingAddress = await ExistsAsync(address); if (existingAddress != null) { return(existingAddress); } var country = await _countryRepository.FindByNameAsync(address.Country.Name); var ZIP = await _zipCodeRepository.FindByCodeAsync(address.ZIP.Code); var street = await _streetRepository.FindByNameAsync(address.Street.Name); if (country == null) { _countryRepository.Add(address.Country); await _countryRepository.SaveAll(); } if (ZIP == null) { _zipCodeRepository.Add(address.ZIP); await _zipCodeRepository.SaveAll(); } if (street == null) { _streetRepository.Add(address.Street); await _streetRepository.SaveAll(); } address.Country = await _countryRepository.FindByNameAsync(address.Country.Name); address.ZIP = await _zipCodeRepository.FindByCodeAsync(address.ZIP.Code); address.Street = await _streetRepository.FindByNameAsync(address.Street.Name); Add(address); await SaveAll(); return(address); }
public override async Task <Countries> Handle(AddCountryCommand command, CancellationToken cancellationToken) { var validado = await IsValidAsync(command, cancellationToken).ConfigureAwait(false); if (!validado) { return(null); } var region = await _regionQuery.Get(command.RegionId.Value, cancellationToken); var country = new Countries(command.CountryId, command.CountryName, region); _countryRepository.Add(country); await _countryRepository.SaveChanges(cancellationToken); return(country); }
public override async Task <int> HandleCommand(AddCommand request, CancellationToken cancellationToken) { if (request.Country == null || string.IsNullOrEmpty(request.Country.Code)) { throw new BusinessException("AddWrongInformation"); } var country = (await countryQueries.Gets($"code = '{request.Country.Code}' and is_deleted = 0")).FirstOrDefault(); if (country != null) { throw new BusinessException("Country.ExistedCode"); } request.Country = CreateBuild(request.Country, request.LoginSession); var rs = await countryRepository.Add(request.Country); return(rs == 0 ? -1 : 0); }
public CountryStatusViewModel CountryCreate(CountryCreateViewModel createCountry) { var searchCountry = _countryRepository.GetCountryByName(createCountry.Name); if (searchCountry != null) { return(CountryStatusViewModel.Dublication); } Country country = new Country { Name = createCountry.Name, Priority = createCountry.Priority, DateCreate = DateTime.Now }; _countryRepository.Add(country); _countryRepository.SaveChange(); return(CountryStatusViewModel.Success); }
public bool Add(CountryCreateModel entity) { if (GetByCountryPath(entity.Path)?.Path?.Length > 0) { throw new Exception("Country path already exist"); } Country country = new Country { Name = entity.Name, Path = entity.Path, Abbreviation = entity.Abbreviation, CreatedBy = entity.CreatedBy, CreatedAt = entity.CreatedAt, ModifiedAt = entity.ModifiedAt, ModifiedBy = entity.ModifiedBy }; return(_repository.Add(country)); }
public void AddRangeTest() { //Arrange InPortDbContext context = InPortContextFactory.Create(); UnitOfWorkContainer unitwork = new UnitOfWorkContainer(context); ICountryRepository countryRepository = unitwork.Repository.CountryRepository; Guid countryId1 = new Guid("A3C82D06-6A07-41FB-B7EA-903EC456BFC5"); Country country1 = new Country("Colombia", "CO"); country1.ChangeCurrentIdentity(countryId1); Guid countryId2 = new Guid("B3C82D06-6A07-41FB-B7EA-903EC456BFC5"); Country country2 = new Country("Venezuela", "VZ"); country2.ChangeCurrentIdentity(countryId2); List <Country> list = new List <Country>() { country1, country2 }; //Act countryRepository.Add(list); unitwork.SaveChanges(); Country countryF1 = countryRepository.Single(e => e.Id == countryId1); Country countryF2 = countryRepository.Single(e => e.Id == countryId2); //Assert countryF1.ShouldNotBeNull(); countryF1.CountryName.ShouldBe("Colombia"); countryF1.CountryISOCode.ShouldBe("CO"); countryF1.Id.ShouldBe(countryId1); countryF2.ShouldNotBeNull(); countryF2.CountryName.ShouldBe("Venezuela"); countryF2.CountryISOCode.ShouldBe("VZ"); countryF2.Id.ShouldBe(countryId2); }
public StatusCountryViewModel CountryAdd(CountryAddViewModel addCountry) { var searchCountry = _countryRepository.GetCountryByName(addCountry.Name); if (searchCountry != null) { return(StatusCountryViewModel.Dublication); } Country country = new Country { Name = addCountry.Name, DateCreate = DateTime.Now, Priority = addCountry.Priority }; _countryRepository.Add(country); _countryRepository.SaveChange(); return(StatusCountryViewModel.Success); }
public IActionResult Create([FromBody] CountryViewModel country) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //Country newCountry = Mapper.Map<CountryViewModel, Country>(country); Country newCountry = new Country { Name = country.Name, EpiIndex = country.EpiIndex }; countryRepository.Add(newCountry); countryRepository.Commit(); country = Mapper.Map <Country, CountryViewModel>(newCountry); CreatedAtRouteResult result = CreatedAtRoute("GetCountry", new { controller = "Country", id = country.Id }, country); return(result); }