public CountryDto GetCountryDetails(int?id) { CountryModel country = countryRepository.GetById(id); CountryDto countryDto = ObjectConverter <CountryModel, CountryDto> .Convert(country); return(countryDto); }
public CountryDto EditCountry(CountryDto countryDto, int userId, int tenantId) { var countryObj = _countryService.Query(x => x.CountryId == countryDto.CountryId && x.TenantId == tenantId).Select().FirstOrDefault(); if (countryObj == null) { throw new NotFoundException(ErrorCodes.ProductNotFound); } ValidateCountry(countryDto, tenantId); foreach (var countryName in countryDto.TitleDictionary) { var countryTranslation = countryObj.CountryTranslations.FirstOrDefault(x => x.Language.ToLower() == countryName.Key.ToLower() && x.CountryId == countryDto.CountryId); if (countryTranslation == null) { countryObj.CountryTranslations.Add(new CountryTranslation { Title = countryName.Value, Language = countryName.Key }); } else { countryTranslation.Title = countryName.Value; } } countryObj.LastModificationTime = Strings.CurrentDateTime; countryObj.LastModifierUserId = userId; countryObj.IsDeleted = countryDto.IsDeleted; _countryService.Update(countryObj); SaveChanges(); return(countryDto); }
public IActionResult GetCountry(int countryId) { // Return Not Found Page if the country doesn't exist in the Database if (!_countryRepository.CountryExists(countryId)) { return(NotFound()); } var country = _countryRepository.GetCountry(countryId); // Check if Model State is valid or invalid if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var countryDto = new CountryDto() { Id = country.Id, Name = country.Name }; // Return status code with countries return(Ok(countryDto)); }
public CountryDto CreateCountry(CountryDto countryDto, int userId, int tenantId) { if (GetCountry(countryDto.CountryId, tenantId) != null) { return(EditCountry(countryDto, userId, tenantId)); } ValidateCountry(countryDto, tenantId); var countryObj = Mapper.Map <Country>(countryDto); foreach (var countryName in countryDto.TitleDictionary) { countryObj.CountryTranslations.Add(new CountryTranslation { Title = countryName.Value, Language = countryName.Key, }); } countryObj.CreationTime = Strings.CurrentDateTime; countryObj.CreatorUserId = userId; countryObj.TenantId = tenantId; _typeTranslationService.InsertRange(countryObj.CountryTranslations); _countryService.Insert(countryObj); SaveChanges(); return(countryDto); }
public ActionResult EditSettings(FormCollection collection) { try { UserService service = new UserService(); UserDto user = new UserDto { Id = int.Parse(Session["UserId"].ToString()) }; CountryDto country = new CountryDto { Id = int.Parse(collection["CountryId"]) }; //user.Country.Id = int.Parse(collection["CountryId"].ToString()); user.Country = country; //TODO: add attributes in user for default currency and sorting service.Update(user); TempData["SuccessMessage"] = "Your settings has been updated successfully"; return(RedirectToAction("Settings")); } catch { TempData["ErrorMessage"] = "An error has occured. Please try again."; return(RedirectToAction("Settings")); } }
//Update public string update(CountryDto tCountryDto) { try { Country tCountryUpdate = _context.Country.Find(tCountryDto.Id); if (tCountryUpdate == null) { return("1"); } tCountryUpdate.Name = tCountryDto.Name; tCountryUpdate.Description = tCountryDto.Description; tCountryUpdate.Status = tCountryDto.Status; tCountryUpdate.Id = tCountryDto.Id; tCountryUpdate.Code = tCountryDto.Code; tCountryUpdate.CreateDate = tCountryDto.CreateDate; tCountryUpdate.CreateUser = tCountryDto.CreateUser; _context.Country.Update(tCountryUpdate); _context.SaveChanges(); return("0"); } catch (Exception ex) { return("1"); } }
public virtual CountryDto.CountryRow GetCountryByCountryCode(string countryCode) { CountryDto dataset = CountryManager.GetCountry(countryCode, false); CountryDto.CountryDataTable table = dataset.Country; return (table.Rows.Count == 1) ? table.Rows[0] as CountryDto.CountryRow : null; }
public CountryDto Insert(CountryInsertDto dto) { CountryDto countryDto = null; try { var country = Mapper.Map <CountryInsertDto, Country>(dto); country.CreatedBy = _appSession.GetUserName(); country.IsEnabled = true; _unitOfWork.CreateTransaction(); _unitOfWork.GenericRepository <Country>().Insert(country); _unitOfWork.Save(); _unitOfWork.Commit(); countryDto = Mapper.Map <Country, CountryDto>(country); } catch (Exception ex) { Tracing.SaveException(ex); _unitOfWork.Rollback(); } return(countryDto); }
public async Task <IActionResult> UpdateCountryById(long countryId, CountryDto countryDto) { try { if (countryId != countryDto.Id) { return(BadRequest()); } var country = await _countryService.GetCountryById(countryId); if (country == null) { return(NotFound()); } _mapper.Map(countryDto, country); _countryService.UpdateCountry(countryId, country); await _unitOfWork.Save(); return(NoContent()); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public IActionResult UpdateCountry(CountryDto countryToUpdate) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:60039/api/"); var responseTask = client.PutAsJsonAsync($"countries/{countryToUpdate.Id}", countryToUpdate); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { TempData["SuccessMessage"] = $"Country {countryToUpdate.Name} was successfully updated."; return(RedirectToAction("GetCountryById", new { countryId = countryToUpdate.Id })); } if ((int)result.StatusCode == 422) { ModelState.AddModelError("", "Country Already Exists!"); } else { ModelState.AddModelError("", "Some kind of error. Country not created!"); } } var countryDto = _countryRepository.GetCountryById(countryToUpdate.Id); return(View(countryDto)); }
public IActionResult GetCountryById(int countryId) { var country = _countryRepositoryGUI.GetCountryByID(countryId); if (country == null || country.Id == 0) { ModelState.AddModelError(string.Empty, "Error Getting a Country"); ViewBag.msg = "There is a Problem retrieving the Country " + "from the database or no country exist"; country = new CountryDto(); } var authors = _countryRepositoryGUI.GetAuthorsFromCountry(countryId); if (authors.Count() <= 0) { ViewBag.AuthorMsg = $"There is No Author from the Country with id => {countryId}"; } var countryAuthorModel = new CountryAuthorViewModel { Authors = authors, Country = country }; ViewBag.SuccessMessage = TempData["SuccessMessage"]; return(View(countryAuthorModel)); }
public IActionResult GetCountry(int countryId) { if (!_countryRepository.CountryExists(countryId)) { return(NotFound()); } var country = _countryRepository.GetCountry(countryId); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var countryDto = new CountryDto() { Id = country.Id, Name = country.Name }; return(Ok(countryDto)); }
public bool UpdateCountry(Country country) { var countryDto = new CountryDto(); countryDto = convert.ToCountryDto(country); var model = new bool(); using (var client = new TeamService.TeamServiceClient()) { try { client.Open(); model = client.UpdateCountry(countryDto); client.Close(); } catch (FaultException <CustomException> customEx) { log.Error(customEx.Message); return(false); } catch (CommunicationException commEx) { log.Error(commEx.Message); return(false); } } return(model); }
public CountryDto GetCountryById(int countryId) { var model = new CountryDto(); using (var client = new TeamService.TeamServiceClient()) { try { client.Open(); model = client.GetCountryById(countryId); client.Close(); if (model == null) { throw new NullReferenceException(); } } catch (FaultException <CustomException> customEx) { log.Error(customEx.Message); return(null); } catch (CommunicationException commEx) { log.Error(commEx.Message); return(null); } catch (NullReferenceException nullEx) { log.Error(nullEx.Message); return(null); } } return(model); }
public async Task <CountryDto> GetID(int ID) { CountryDto CountryDto = new CountryDto(); Country Country = new Country(); try { int CacheTimeOutInHours = this.configuration.GetValue <int>("MemoryCache:CacheTimeOutInHours"); if (CacheTimeOutInHours <= 0) { CacheTimeOutInHours = 1; } IEnumerable <Country> countries = new List <Country>(); countries = cache.Get <IEnumerable <Country> >(string.Format("{0}", CacheEnum.COUNTRIES.ToString())); if (countries == null || !countries.Any()) { Country = await this.countryRepository.GetByID(ID); return(this.mapper.Map <CountryDto>(Country)); } CountryDto = this.mapper.Map <CountryDto>(countries.FirstOrDefault(x => x.CountryID == ID)); } catch (Exception er) { logger.LogError(string.Format("{0}===================={1}====================\n", DateTime.Now.ToString(), er.ToString())); } return(CountryDto); }
public IActionResult Post([FromBody] CountryDto dto) { try { addCountry.Execute(dto); return(StatusCode(201)); } catch (EntityAlreadyExistsException e) { return(StatusCode(409, new { Errors = new List <string> { e.Message } })); } catch (Exception e) { return(StatusCode(500, new { Errors = new List <string> { e.Message } })); } }
public IHttpActionResult FindCountryForArticle(int id) { //Finds the first country which has any articles //that match the input articleid Country Country = db.Countries .Where(t => t.Articles.Any(p => p.ArticleID == id)) .FirstOrDefault(); //if not found, return 404 status code. if (Country == null) { return(NotFound()); } //put into a 'friendly object format' CountryDto CountryDto = new CountryDto { CountryID = Country.CountryID, CountryName = Country.CountryName, Population = Country.Population, Infected = Country.Infected, Vaccinated = Country.Vaccinated, Variants = Country.Variants }; //pass along data as 200 status code OK response return(Ok(CountryDto)); }
public IHttpActionResult GetCountries() { List <Country> Countries = db.Countries.ToList(); List <CountryDto> CountryDtos = new List <CountryDto> { }; foreach (var Country in Countries) { Console.WriteLine("country object-" + Country); CountryDto NewCountry = new CountryDto { CountryID = Country.CountryID, CountryName = Country.CountryName, Population = Country.Population, Infected = Country.Infected, Vaccinated = Country.Vaccinated, Variants = Country.Variants }; CountryDtos.Add(NewCountry); } return(Ok(CountryDtos)); }
public async Task UpdateCountry() { // Initialize the database await _countryRepository.CreateOrUpdateAsync(_country); await _countryRepository.SaveChangesAsync(); var databaseSizeBeforeUpdate = await _countryRepository.CountAsync(); // Update the country var updatedCountry = await _countryRepository.QueryHelper().GetOneAsync(it => it.Id == _country.Id); // Disconnect from session so that the updates on updatedCountry are not directly saved in db //TODO detach updatedCountry.CountryName = UpdatedCountryName; CountryDto updatedCountryDto = _mapper.Map <CountryDto>(_country); var response = await _client.PutAsync("/api/countries", TestUtil.ToJsonContent(updatedCountryDto)); response.StatusCode.Should().Be(HttpStatusCode.OK); // Validate the Country in the database var countryList = await _countryRepository.GetAllAsync(); countryList.Count().Should().Be(databaseSizeBeforeUpdate); var testCountry = countryList.Last(); testCountry.CountryName.Should().Be(UpdatedCountryName); }
public void Generate( CountryResearchRequest request, CountryDto dto) { DirectoryInfo currentFolder = new DirectoryInfo(Directory.GetCurrentDirectory()); DirectoryInfo projectFolder = currentFolder.Parent.Parent; DirectoryInfo generatedReportFolder = new DirectoryInfo(projectFolder.FullName + @"\" + "GeneratedReports"); DirectoryInfo documentTemplates = new DirectoryInfo(projectFolder.FullName + @"\" + "DocumentTemplates"); FileInfo file = new FileInfo(documentTemplates.FullName + @"\" + "CountryReportTemplate.docx"); string pathToOutput = generatedReportFolder.FullName + @"\" + $"ReportForUser_{request.RequestedUserId}.docx"; File.Copy(file.FullName, pathToOutput); var valuesToFill = new Content( new FieldContent("CountryName", dto.Name), new FieldContent("CountryCode", dto.Alpha3Code), new FieldContent("Population", dto.Population.ToString()), new FieldContent("Gini", dto.Gini.ToString())); using (var outputDocument = new TemplateProcessor(pathToOutput) .SetRemoveContentControls(true)) { outputDocument.FillContent(valuesToFill); outputDocument.SaveChanges(); } }
public async Task EditCountry(CountryDto input) { var country = await _countryRepository.GetAsync(input.Id); country.Name = input.Name; await _countryRepository.UpdateAsync(country); }
public async Task GetCountries() { using (var mock = AutoMock.GetLoose()) { var country = new Country { CountryName = "CountryName" }; var countries = new List <Country>(); countries.Add(country); var eCountries = countries.AsEnumerable(); var countryDto = new CountryDto { Name = "CountryName" }; var dto = new List <CountryDto>(); dto.Add(countryDto); mock.Mock <ICountryData>().Setup(x => x.GetAllAsync()).Returns(Task.FromResult(eCountries)); mock.Mock <IMap>().Setup(x => x.MapToCountryDto(countries)).Returns(dto); var cls = mock.Create <UtilityRepo>(); var expected = dto; var actual = await cls.GetCountriesAsync(); Assert.True(actual != null); Assert.Equal(expected, actual); // More Tests needed } }
public async Task <CountryDto> GetAsync(int id) { Country country = this._countryRepository.GetAllIncluding(c => c.Translations).FirstOrDefault(c => c.Id == id); CountryDto dto = this._mapper.Map <CountryDto>(country); return(await Task.FromResult(dto).ConfigureAwait(false)); }
public CountryDto Update(CountryUpdateDto dto) { CountryDto countryDto = null; try { var country = _unitOfWork.GenericRepository <Country>().GetById(dto.Id); Mapper.Map <CountryUpdateDto, Country>(dto, country); country.ModifiedBy = _appSession.GetUserName(); _unitOfWork.CreateTransaction(); _unitOfWork.GenericRepository <Country>().Update(country); _unitOfWork.Save(); _unitOfWork.Commit(); CheckForDelete(dto.Provinces, country.Provinces); CheckForAdd(dto.Provinces, country.Id); countryDto = Mapper.Map <Country, CountryDto>(country); } catch (Exception ex) { Tracing.SaveException(ex); } return(countryDto); }
public bool UpdateCountry(CountryDto countryDto) { if (countryDto == null) { GenerateFaultException("UpdateCountry", "ArgumentException"); } var parameters = new List <Parameter>(); parameters.Add(new Parameter { Type = DbType.Int32, Name = "@CountryId", Value = countryDto.CountryId }); parameters.Add(new Parameter { Type = DbType.String, Name = "@Name", Value = countryDto.Name }); var connection = new Connection <CountryDto>(); try { return(connection.GetConnectionUpdate(CommandType.StoredProcedure, "UpdateCountry", parameters)); } catch (SqlException sqlEx) { var exception = new CustomException(); exception.Title = "UpdateCountry"; log.Error(sqlEx.Message); throw new FaultException <CustomException>(exception, sqlEx.Message); } }
public IActionResult GetCountryById(int countryId) { var country = _countryRepository.GetCountryById(countryId); //country = null; if (country == null) { ModelState.AddModelError("", "Error getting a country"); ViewBag.Message = $"There was a problem retrieving country with id {countryId} " + $"from the database or no country with that id exists"; country = new CountryDto(); } var authors = _countryRepository.GetAuthorsFromACountry(countryId); if (authors.Count() <= 0) { ViewBag.AuthorMessage = $"There are no authors from country with id {country.Id}"; } var countryAuthorsViewModel = new CountryAuthorsViewModel { Country = country, Authors = authors }; ViewBag.SuccessMessage = TempData["SuccessMessage"]; return(View(countryAuthorsViewModel)); }
public async void GetCountryCovidData(CountryDto countryDto) { var results = await ApiMethods.GetCountryCovidData(countryDto); CountryCovidResults = new ObservableCollection <CountryCovidResult>(results); InitializeChart(); }
// GET: Article/Details/5 public ActionResult Details(int id) { ShowArticle ViewModel = new ShowArticle(); string url = "articledata/findarticle/" + id; HttpResponseMessage response = client.GetAsync(url).Result; //Can catch the status code (200 OK, 301 REDIRECT), etc. if (response.IsSuccessStatusCode) { //Article goes in Data Transfer Object ArticleDto SelectedArticle = response.Content.ReadAsAsync <ArticleDto>().Result; ViewModel.article = SelectedArticle; url = "articledata/findcountryforarticle/" + id; response = client.GetAsync(url).Result; CountryDto SelectedCountry = response.Content.ReadAsAsync <CountryDto>().Result; ViewModel.country = SelectedCountry; return(View(ViewModel)); } else { return(RedirectToAction("Error")); } }
public IActionResult AddACountry([FromBody] CountryDto countryDto) { if (countryDto == null) { return(BadRequest(ModelState)); } if (_npRepo.CountryExists(countryDto.Name)) { ModelState.AddModelError("", "Country already exists."); return(StatusCode(404, ModelState)); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // var ContactInfoObj = _mapper.Map<CreateEmployeeDto, ContactInfo>(createEmployeeDto); var countryObj = _mapper.Map <CountryDto, Country>(countryDto); // employeePIObj.ContactInfo = ContactInfoObj; if (!_npRepo.CreateCountry(countryObj)) { ModelState.AddModelError("", $"Something went wrong when saving the record {countryObj.Name}"); return(StatusCode(500, ModelState)); } return(Ok()); }
public IHttpActionResult FindCountry(int id) { //Find the data Country Country = db.Countries.Find(id); //if not found, return 404 status code. if (Country == null) { return(NotFound()); } //put into a 'friendly object format' CountryDto CountryDto = new CountryDto { CountryID = Country.CountryID, CountryName = Country.CountryName, Population = Country.Population, Infected = Country.Infected, Vaccinated = Country.Vaccinated, Variants = Country.Variants }; //pass along data as 200 status code OK response return(Ok(CountryDto)); }
private IEnumerable<CountryDto.StateProvinceRow> GetRegionOptionsFromCountry(CountryDto.CountryRow country) { if (country == null) { return _emptyRegionList; } return country.GetStateProvinceRows().ToList(); }
public void UpdateCountry(CountryDto input) { var instanse = Mapper.Map<Country>(input); this.unitOfWork.Entities<Country, int>().Update(instanse); }
private IEnumerable<string> GetRegionsForCountry(CountryDto.CountryRow country) { return country == null ? Enumerable.Empty<string>() : country.GetStateProvinceRows().Select(x => x.Name).ToList(); }