public static CountryDTO MapCountryToDTO(this Country country) { try { var countryDTO = new CountryDTO() { ID = country.ID, Name = country.Name, IsDeleted = country.IsDeleted }; if (country.Breweries != null) { countryDTO.Breweries = country.Breweries.Select(n => n.MapBreweryToDTO()).ToList(); } else { countryDTO.Breweries = null; } return(countryDTO); } catch (Exception) { return(new CountryDTO()); } }
/// <summary> /// Updates a country record within the dimension table /// </summary> /// <param name="country"></param> public bool UpdateCountryDimension(CountryDTO country) { bool Success = false; SQLAzure.DbConnection dbConn = new SQLAzure.DbConnection(_connectionString); try { string query = @"UPDATE DimCountry SET CountryCode = @CountryCode, CountryName = @CountryName WHERE ID = @ID"; dbConn.Open(); SQLAzure.RetryLogic.DbCommand dbComm = new SQLAzure.RetryLogic.DbCommand(dbConn); dbComm.CommandText = query; dbComm.Parameters.Add(new SqlParameter("ID", country.ID)); dbComm.Parameters.Add(new SqlParameter("CountryCode", country.CountryCode)); dbComm.Parameters.Add(new SqlParameter("CountryName", country.CountryName)); dbComm.ExecuteNonQuery(System.Data.CommandType.Text); Success = true; } catch (SqlException) { throw; } finally { dbConn.Close(); } return(Success); }
/// <summary> /// Returns a single country dimension /// </summary> /// <returns></returns> public CountryDTO GetCountryDimension(int ID) { SQLAzure.DbConnection dbConn = new SQLAzure.DbConnection(_connectionString); CountryDTO country = new CountryDTO(); try { dbConn.Open(); SQLAzure.RetryLogic.DbCommand dbComm = new SQLAzure.RetryLogic.DbCommand(dbConn); dbComm.CommandText = "SELECT ID, CountryCode, CountryName FROM DimCountry WHERE ID = @ID"; dbComm.Parameters.Add(new SqlParameter("ID", ID)); System.Data.IDataReader rdr = dbComm.ExecuteReader(System.Data.CommandType.Text); while (rdr.Read()) { country.ID = Convert.ToInt32(rdr["ID"]); country.CountryCode = rdr["CountryCode"].ToString(); country.CountryName = rdr["CountryName"].ToString(); } } catch (SqlException) { throw; } finally { dbConn.Close(); } return(country); }
public IActionResult GetCountryById(int countryId) { var country = _countryRepository.GetCountry(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 recipes = _countryRepository.GetRecipesFromCountry(countryId); if (recipes.Count() <= 0) { ViewBag.Message = $"There are no recipes from country {country.Name}"; } var countryRecipesViewModel = new CountryRecipesViewModels { Country = country, Recipes = recipes }; return(View(countryRecipesViewModel)); }
/// <summary> /// Creates a country record within the dimension table /// </summary> /// <param name="country"></param> public bool CreateCountryDimension(CountryDTO country) { bool Success = false; SQLAzure.DbConnection dbConn = new SQLAzure.DbConnection(_connectionString); try { string query = @"IF NOT EXISTS (SELECT CountryCode from DimCountry WHERE CountryCode = @CountryCode) INSERT INTO DimCountry (CountryCode, CountryName) VALUES (@CountryCode, @CountryName)"; dbConn.Open(); SQLAzure.RetryLogic.DbCommand dbComm = new SQLAzure.RetryLogic.DbCommand(dbConn); dbComm.CommandText = query; dbComm.Parameters.Add(new SqlParameter("CountryCode", country.CountryCode)); dbComm.Parameters.Add(new SqlParameter("CountryName", country.CountryName)); dbComm.ExecuteNonQuery(System.Data.CommandType.Text); Success = true; } catch (SqlException) { throw; } finally { dbConn.Close(); } return(Success); }
public HttpResponseMessage SaveCountry(CountryDTO obj) { obj = Counobj.SaveCountry(obj); var Responce = Request.CreateResponse <CountryDTO>(HttpStatusCode.Created, obj); return(Responce); }
public async Task <ActionResult> pvwAddCountry([FromBody] CountryDTO _sarpara) { CountryDTO _Country = new CountryDTO(); try { string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token")); var result = await _client.GetAsync(baseadress + "api/Country/GetCountryById/" + _sarpara.Id); string valorrespuesta = ""; if (result.IsSuccessStatusCode) { valorrespuesta = await(result.Content.ReadAsStringAsync()); _Country = JsonConvert.DeserializeObject <CountryDTO>(valorrespuesta); } if (_Country == null) { _Country = new CountryDTO(); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); throw ex; } return(PartialView(_Country)); }
public async Task <ActionResult <CompanyViewModel> > GetCompany(int CompanyId) { CompanyDTO company = await companyServ.GetCompany(CompanyId); CountryDTO country = await countryServ.GetCountry(company.HGBasedInCountryId); CompanyQualification companyQualification = qualificationServ.GetQualifications().Result.Where(p => p.Id == company.QualificationId).FirstOrDefault(); string userName = ""; if (company.LeadOwnerId != null) { userName = await userRegistrationServ.GetUserFullName(company.LeadOwnerId); } string region = await regionServ.GetRegionName(country.RegionId); CompanyViewModel companyView = new CompanyViewModel { CompanyLegalName = company.CompanyLegalName, CompanyRegion = region, HGBasedInCountryName = country.Name, Id = company.Id, LeadOwnerFullName = userName, QualificationName = companyQualification.QualificationName, QualifiedDate = company.QualifiedDate, TradingName = company.TradingName, Website = company.Website }; return(Ok(companyView)); }
public async Task <ActionResult> RemoveCountry(long countryId) { LoginToken <Administrator> token = GetLoginToken(); string countryName = CountryDTO.returnNameFromId(countryId); if (countryName == null) { return(StatusCode(400, $"{{ error: \"{"Country id does not exists"}\" }}")); } Country country = new Country { Id = countryId, Name = countryName }; try { await Task.Run(() => { m_facade.RemoveCountry(token, country); }); } catch (AdministratorDoesntHaveSanctionException ex) { return(StatusCode(403, $"{{ error: \"{ex.Message}\" }}")); } catch (WasntActivatedByAdministratorException ex) { return(StatusCode(401, $"{{ error: \"{ex.Message}\" }}")); } return(Ok()); }
public int AddCountry(CountryDTO dto) { int id = 0; try { log.Debug(CountryDTO.FormatCountryDTO(dto)); R_Country t = CountryDTO.ConvertDTOtoEntity(dto); // add id = Repository.AddCountry(t); dto.CountryId = id; log.Debug("result: 'success', id: " + id); } catch (System.Exception e) { // error log.Error(e.ToString()); throw; } return(id); }
public CountryDTO GetCountry(int countryId) { try { //Requires.NotNegative("countryId", countryId); log.Debug("countryId: " + countryId + " "); // get R_Country t = Repository.GetCountry(countryId); CountryDTO dto = new CountryDTO(t); log.Debug(CountryDTO.FormatCountryDTO(dto)); return(dto); } catch (System.Exception e) { // error log.Error(e.ToString()); throw; } }
/// <summary> /// Updates the Country's Name /// </summary> /// <param name="id">ID of the Country to be updated.</param> /// <param name="model">Input object with update information.</param> /// <returns>Returns the reevaluated input object</returns> public async Task <CountryDTO> UpdateAsync(int?id, CountryDTO model) { var country = await this._context.Countries.FindAsync(id); if (country == null) { return(null); } country.Name = model.Name; country.ModifiedOn = DateTime.UtcNow; model.ID = country.ID; this._context.Update(country); try { await this._context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CountryExists(id)) { return(null); } } return(model); }
public static CountryApiModel ToCountryApi(this CountryDTO country) { if (country == null) { return(null); } return(new CountryApiModel { Capital = country.Capital, CommonName = country.CommonName, CountryCode = country.CountryCode, CountryCode3 = country.CountryCode3, CountryNumber = country.CountryNumber, CountrySubType = country.CountrySubType, CountryType = country.CountryType, CurrencyCode = country.CurrencyCode, CurrencyName = country.CurrencyName, Flags = country.Flags, FormalName = country.FormalName, Id = country.Id, InternetCountryCode = country.InternetCountryCode, IsDeleted = country.IsDeleted, IsPublished = country.IsPublished, SortOrder = country.SortOrder, Sovereignty = country.Sovereignty, TelephoneCode = country.TelephoneCode }); }
/// <summary> /// Get a country by a certain ID. /// </summary> /// <param name="id">ID of the country to get</param> /// <returns>Returns a city with certain ID or an appropriate error message.</returns> public CountryDTO Get(int id) { var country = FindCountry(id); CountryDTO countryDTO = new CountryDTO(country); return(countryDTO); }
public static CountryDTO SampleCountryDTO(int id = 1) { CountryDTO country = new CountryDTO(); // int country.CountryId = id; // string country.Name = "NameTestValue"; // string country.EnglishName = "EnglishNameTestValue"; // string country.IsoCode = "IsoCodeTestValue"; // string country.CapitalCity = "CapitalCityTestValue"; // double? country.Latitude = 1; // double? country.Longitude = 1; // double? country.PhonePrefix = 1; // bool country.Active = false; // bool country.IsDeleted = false; // int? country.CreateBy = 1; // System.DateTime? country.CreateOn = new System.DateTime(); // int? country.UpdateBy = 1; // System.DateTime? country.UpdateOn = new System.DateTime(); return(country); }
public static Country MapDTOToCountry(this CountryDTO dto) { try { var country = new Country() { ID = dto.ID, Name = dto.Name, IsDeleted = dto.IsDeleted }; if (dto.Breweries != null) { country.Breweries = dto.Breweries.Select(n => n.MapDTOToBrewery()).ToList(); } else { country.Breweries = null; } return(country); } catch (Exception) { return(new Country()); } }
public IEnumerable <DistrictDTO> ReadByCountryAndRegionAndProvince(string countryId, string regionCode, string provinceCode) { return(Connector.ExecuteReader(readByCountryAndRegionAndProvinceQuery, new Dictionary <string, object>() { { "Country", countryId }, { "Province", provinceCode } }, reader => { CountryDTO country = new CountryDTO() { Id = reader["Country"] as string }; string code = reader["Code"] as string; return new DistrictDTO() { Country = country, Code = code, Province = new ProvinceDTO() { Code = reader["Province"] as string, Country = country, Region = new RegionDTO() { Code = reader["Region"] as string, Country = country } }, DisplayName = new LocalizationDictionary(GetDisplayName(countryId, code)) }; })); }
public IActionResult DeleteCountry([FromBody] CountryDTO request) { var response = new OperationResponse <ICollection>(); try { var result = _lookupService.DeleteCountry(request.Tasks); if (result.Any(fn => !string.IsNullOrEmpty(fn.Message))) { response.State = ResponseState.ValidationError; response.Data = result.ToList(); return(new JsonResult(response)); } else { response.State = ResponseState.Success; } } catch (Exception exception) { response.State = ResponseState.Error; response.Messages.Add(exception.Message); _logger.LogError(exception, "Error in DeleteCountry ==>" + exception.StackTrace, request); } return(new JsonResult(response)); }
public void GetCountryListAdvancedSearch_Success_Test() { // Arrange string name = null; string englishName = null; string isoCode = null; string capitalCity = null; double?latitude = null; double?longitude = null; double?phonePrefix = null; bool? active = null; //int pageIndex = 0; int pageSize = 10; // list IList <R_Country> list = new List <R_Country>(); for (int i = 1; i <= pageSize; i++) { list.Add(SampleCountry(i)); } // create mock for repository var mock = new Mock <ICountryRepository>(); mock.Setup(s => s.GetCountryListAdvancedSearch( Moq.It.IsAny <string>() // name , Moq.It.IsAny <string>() // englishName , Moq.It.IsAny <string>() // isoCode , Moq.It.IsAny <string>() // capitalCity , Moq.It.IsAny <double?>() // latitude , Moq.It.IsAny <double?>() // longitude , Moq.It.IsAny <double?>() // phonePrefix , Moq.It.IsAny <bool?>() // active )).Returns(list); // service CountryService countryService = new CountryService(); CountryService.Repository = mock.Object; // Act var resultList = countryService.GetCountryListAdvancedSearch( name , englishName , isoCode , capitalCity , latitude , longitude , phonePrefix , active ); CountryDTO result = resultList.FirstOrDefault(); // Assert Assert.IsNotNull(result); Assert.AreEqual(1, result.CountryId); }
public ActionResult Save(CountryDTO ObjCt) { try { var client = new HttpClient(); if (ObjCt.CountryEdit.CID == 0) { var response = client.PostAsJsonAsync("http://localhost:6198/api/CountryApi/SaveCountry", ObjCt.CountryEdit).Result; if (response.IsSuccessStatusCode) { } return(RedirectToAction("Country")); } else { var response = client.PutAsJsonAsync("http://localhost:6198/api/CountryApi/UpdateCountry", ObjCt.CountryEdit).Result; if (response.IsSuccessStatusCode) { } return(RedirectToAction("Country")); } } catch (Exception ex) { throw ex; } }
public ActionResult Edit(Guid id) { CountryDTO countryDTO = _countryService.GetAll().FirstOrDefault(c => c.ID == id); var country = _countryMaper.Map(countryDTO); return(View("Edit", country)); }
public CountryDTO Edit(int?id) { try { var client = new HttpClient(); var modelGrid = client.GetAsync("http://localhost:6198/api/CountryApi/GetCountry").Result .Content.ReadAsAsync <List <CountryDTO> >().Result; if (id != null && id != 0) { var modelEdit = client.GetAsync("http://localhost:6198/api/CountryApi/GetCountry/" + id).Result .Content.ReadAsStringAsync().Result; var ss = JsonConvert.DeserializeObject <CountryDTO>(modelEdit); var model = new CountryDTO() { CountryGrid = modelGrid.OrderByDescending(item => item.CID), CountryEdit = ss }; return(model); } else { var model = new CountryDTO() { CountryGrid = modelGrid.OrderByDescending(item => item.CID), CountryEdit = null }; return(model); } } catch (Exception ex) { throw ex; } }
public async Task CreateAsync_ShouldReturnModifiedCountryDTOAsync() { //Arrange var options = InMemory.GetOptions("CreateAsync_ShouldReturnModifiedCountryDTOAsync"); using (var context = new BOContext(options)) { } using (var context = new BOContext(options)) { var countryDTO = new CountryDTO() { Name = "Bulgaria" }; //Act var sut = new CountriesService(context); var result = await sut.CreateAsync(countryDTO); var dbresult = await context.Countries.FirstOrDefaultAsync(c => c.Name == "Bulgaria"); //Assert Assert.AreEqual(result.ID, dbresult.ID); Assert.AreEqual(result.Name, dbresult.Name); } }
public async Task UpdateAsync_ShouldChangeNameOfCountryAsync() { //Arrange var options = InMemory.GetOptions("UpdateAsync_ShouldChangeNameOfCountryAsync"); using (var context = new BOContext(options)) { var country = new Country() { Name = "Bulgaria" }; context.Countries.Add(country); await context.SaveChangesAsync(); } using (var context = new BOContext(options)) { var countryDTO = new CountryDTO() { Name = "Belgium" }; //Act var sut = new CountriesService(context); var result = await sut.UpdateAsync(1, countryDTO); var dbresult = await context.Countries.FindAsync(1); //Assert Assert.AreEqual(dbresult.Name, "Belgium"); } }
private void AddEditProperty_BasePost(Connector connector, PropertyDTO property) { RegionBLL regionBLL = new RegionBLL(connector); ProvinceBLL provinceBLL = new ProvinceBLL(connector); DistrictBLL districtBLL = new DistrictBLL(connector); CountryDTO country = property.Country; RegionDTO region = property.Region; ProvinceDTO province = property.Province; DistrictDTO district = property.District; if (country != null) { country.Regions = regionBLL.ReadByCountry(country.Id); if (region != null) { region.Country = country; } if (province != null) { province.Country = country; } if (district != null) { district.Country = country; } } if (region != null) { region.Provinces = provinceBLL.ReadByCountryAndRegion(country.Id, region.Code); } if (province != null) { province.Districts = districtBLL.ReadByCountryAndRegionAndProvince(country.Id, region.Code, province.Code); } }
public async Task CreateAsync_ShouldUndeleteRecordIfExist() { //Arrange var options = InMemory.GetOptions("CreateAsync_ShouldUndeleteRecordIfExist"); using (var context = new BOContext(options)) { var country = new Country() { Name = "Bulgaria", DeletedOn = DateTime.UtcNow, IsDeleted = true }; context.Countries.Add(country); await context.SaveChangesAsync(); } using (var context = new BOContext(options)) { var countryDTO = new CountryDTO() { Name = "Bulgaria" }; //Act var sut = new CountriesService(context); await sut.CreateAsync(countryDTO); var dbresult = await context.Countries.FirstOrDefaultAsync(c => c.Name == "Bulgaria"); //Assert Assert.AreEqual(dbresult.Name, "Bulgaria"); Assert.AreEqual(dbresult.DeletedOn, null); Assert.AreEqual(dbresult.IsDeleted, false); } }
public IEnumerable <ProvinceDTO> ReadByCountryAndRegion(string countryId, string regionCode) { DistrictRepository districtRepository = new DistrictRepository(Connector); return(Connector.ExecuteReader(readByCountryAndRegionQuery, new Dictionary <string, object>() { { "Country", countryId }, { "Region", regionCode } }, reader => { CountryDTO country = new CountryDTO() { Id = reader["Country"] as string }; string code = reader["Code"] as string, region = reader["Region"] as string; return new ProvinceDTO() { Country = country, Code = code, Region = new RegionDTO() { Code = region, Country = country }, DisplayName = new LocalizationDictionary(GetDisplayName(country.Id, code)), Districts = districtRepository.ReadByCountryAndRegionAndProvince(country.Id, region, code) }; })); }
public async Task UpdateCountry_UpdatesCorrect_When_Params_AreValid() { //Arrange var options = Utils.GetOptions(nameof(UpdateCountry_UpdatesCorrect_When_Params_AreValid)); var country = new Country { Id = Guid.NewGuid(), Name = "Bulgariaaa" }; var countryDTO = new CountryDTO { Name = "Bulgaria" }; using (var arrangeContext = new CMContext(options)) { await arrangeContext.Countries.AddAsync(country); await arrangeContext.SaveChangesAsync(); } //Act, Assert using (var assertContext = new CMContext(options)) { var sut = new CountryServices(assertContext); var result = await sut.UpdateCountry(country.Id, countryDTO); Assert.AreEqual("Bulgaria", result.Name); Assert.IsInstanceOfType(result, typeof(CountryDTO)); } }
public async Task CreateCountry_Fail_IfAlreadyExists() { var options = TestUtils.GetOptions(nameof(CreateCountry_Fail_IfAlreadyExists)); var mockDateTime = new Mock <IDateTimeProvider>(); var country = new Country { Name = "Bulgaria" }; var countryDTO = new CountryDTO { Name = "Bulgaria" }; using (var arrangeContext = new BeeroverflowContext(options)) { await arrangeContext.Countries.AddAsync(country); await arrangeContext.SaveChangesAsync(); } using (var assertContext = new BeeroverflowContext(options)) { var sut = new CountryService(assertContext, mockDateTime.Object); await Assert.ThrowsExceptionAsync <ArgumentNullException>(() => sut.CreateCountryAsync(countryDTO)); } }
public async Task <OutputResponse> Update(CountryDTO country) { var countryToUpdate = await _context.Countries.FirstOrDefaultAsync(x => x.CountryCode.Equals(country.CountryCode)); if (countryToUpdate == null) { return(new OutputResponse { IsErrorOccured = true, Message = "Country specified does not exist, update cancelled" }); } //update details countryToUpdate.CountryName = country.CountryName; countryToUpdate.ExternalReferenceNumber = country.ExternalReferenceNumber; countryToUpdate.RowAction = "U"; countryToUpdate.ModifiedBy = country.CreatedBy; countryToUpdate.DateModified = DateTime.UtcNow.AddHours(2); await _context.SaveChangesAsync(); return(new OutputResponse { IsErrorOccured = false, Message = MessageHelper.UpdateSuccess }); }
/// <summary> /// Gets the country list. /// </summary> private void GetCountries() { try { var client = new ERPModuleServiceClient(); client.FindCountriesInPageCompleted += delegate(object sender, FindCountriesInPageCompletedEventArgs e) { if (e.Error == null) { Countries = e.Result; SelectedCountry = Countries.Where(c=> c.Id == _currentCustomer.CountryId).FirstOrDefault(); } else if (e.Error is FaultException<ServiceError>) { var fault = e.Error as FaultException<ServiceError>; MessageBox.Show(fault.Detail.ErrorMessage, "Error", MessageBoxButton.OK); } else { Debug.WriteLine("GetCountries: Error at Service:" + e.Error.ToString()); } }; client.FindCountriesInPageAsync(0, 100); } catch (FaultException<ServiceError> excep) { Debug.WriteLine("GetCountries: Error at Service:" + excep.ToString()); } }
public Country Map(CountryDTO dto) { if (dto == null) return null; var country = Mapper.Map<CountryDTO, Country>(dto); return country; }