public async Task ReturnUpdatedCityDTO_WhenParamsAreValid()
        {
            //Arrange
            var mockIDateTimeProvider = new Mock <IDateTimeProvider>();
            var mockICityMapper       = new Mock <ICityMapper>();
            var mockIBarMapper        = new Mock <IBarMapper>();

            var options = Utils.GetOptions(nameof(ReturnUpdatedCityDTO_WhenParamsAreValid));

            var updatedCityDTO = new CityDTO {
                Id = 2, Name = "Shumen"
            };

            mockICityMapper
            .Setup(x => x.MapToCityDTO(It.IsAny <City>()))
            .Returns <City>(c => new CityDTO {
                Id = c.Id, Name = c.Name
            });

            Utils.GetInMemoryDataBase(options);

            //Act & Assert
            using (var assertContext = new CocktailMagicianContext(options))
            {
                var sut = new CityService(mockIDateTimeProvider.Object, assertContext, mockICityMapper.Object, mockIBarMapper.Object);

                var result = await sut.UpdateCityAsync(2, updatedCityDTO);

                Assert.AreEqual(updatedCityDTO.Id, result.Id);
                Assert.AreEqual(updatedCityDTO.Name, result.Name);
            }
        }
Пример #2
0
        public void EditCity(CityDTO cityDto)
        {
            var city = Context.Cities.Where(x => x.Id == cityDto.Id).FirstOrDefault();

            city.Name        = cityDto.Name;
            city.DateUpdated = DateTime.Now;
        }
Пример #3
0
        public void AddCityToWish(CityDTO cityDTO, string currentUser)
        {
            //чи вже є в базі місто з таким id?
            City city = Dbase.Cities.Get(cityDTO.Id);

            if (city == null)
            {
                //чи вже є в базі місто з цими координатами?
                city = Dbase.Cities.Find(c => Math.Abs(c.GeoLat - cityDTO.GeoLat) > 1 && Math.Abs(c.GeoLong - cityDTO.GeoLong) > 1).FirstOrDefault();
                if (city == null)
                {
                    //add city to DB
                    Mapper.Initialize(cfg => cfg.CreateMap <CityDTO, City>());
                    City newCity = Mapper.Map <CityDTO, City>(cityDTO);
                    Dbase.Cities.Create(newCity);
                    city = Dbase.Cities.Find(c => c.GeoLat == newCity.GeoLat && c.GeoLong == newCity.GeoLong).First();
                }
            }
            //add wish to DB
            Wish wish = new Wish
            {
                CityId   = city.Id,
                UserName = currentUser
            };

            Dbase.Wishes.Create(wish);
            Dbase.Save();
        }
Пример #4
0
        public IActionResult DeleteCity([FromBody] CityDTO request)
        {
            var response = new OperationResponse <ICollection>();

            try
            {
                var result = _lookupService.DeleteCity(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 DeleteCity ==>" + exception.StackTrace, request);
            }
            return(new JsonResult(response));
        }
        public async Task <IActionResult> AddCity([FromBody] CityDTO cityDTO)
        {
            if (cityDTO == null)
            {
                return(StatusCode(400, new { message = Constants.MissingOrInvalidBody }));
            }

            if (!ModelState.IsValid)
            {
                return(StatusCode(400, new { message = Constants.MissingOrInvalidBody }));
            }

            try
            {
                var result = await _movieService.AddCity(cityDTO);

                return(Created("AddedCity", new { id = result.CityId, Name = result.CityName }));
            }
            catch (CustomException ex)
            {
                return(StatusCode(400, new { message = ex.Message }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, new { message = ex.Message }));
            }
        }
Пример #6
0
        private async Task UploadPhotoAsync(CityDTO city)
        {
            var oldImageName = (await _repoWrapper.City.GetFirstOrDefaultAsync(i => i.ID == city.ID))?.Logo;
            var logoBase64   = city.Logo;

            if (!string.IsNullOrWhiteSpace(logoBase64) && logoBase64.Length > 0)
            {
                var logoBase64Parts = logoBase64.Split(',');
                var extension       = logoBase64Parts[0].Split(new[] { '/', ';' }, 3)[1];

                if (!string.IsNullOrEmpty(extension))
                {
                    extension = (extension[0] == '.' ? "" : ".") + extension;
                }

                var fileName = Guid.NewGuid() + extension;

                await _cityBlobStorage.UploadBlobForBase64Async(logoBase64Parts[1], fileName);

                city.Logo = fileName;

                if (!string.IsNullOrEmpty(oldImageName))
                {
                    await _cityBlobStorage.DeleteBlobAsync(oldImageName);
                }
            }
            else
            {
                city.Logo = oldImageName ?? null;
            }
        }
Пример #7
0
        public static bool AddCity(string name)
        {
            CityDTO cDTO = new CityDTO();

            cDTO.CityName = name;
            return(PropertyDAL.AddCity(CityDTO.ToDAL(cDTO)));
        }
Пример #8
0
        public AddressDTO FindBy(string type)
        {
            AddressDTO address;
            CityDTO    city;
            string     queryString = "SELECT * FROM dbo.Address WHERE addressType = @type";

            try
            {
                // The connection is automatically closed at the end of the using block.
                using (SqlConnection con = new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(queryString, con))
                    {
                        cmd.Parameters.AddWithValue("@type", SqlDbType.VarChar).Value = type;
                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        if (reader.Read())
                        {
                            address = new AddressDTO();
                            city    = new CityDTO();
                            address = GenerateAddress(reader, address, city);
                            //return product instance as data object
                            Debug.Print("AddressDAL: /FindByType/ " + address.ToString());
                            return(address);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                e.GetBaseException();
            }
            return(null);
        }
Пример #9
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,DateUpdated")] CityDTO city)
        {
            if (id != city.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _dbAccess.EditCity(city);
                    _dbAccess.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CityExists(city.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(city));
        }
Пример #10
0
        public bool Delete(CityDTO oCityData)
        {
            string          sProcName;
            DatabaseManager oDB;

            try
            {
                oDB = new DatabaseManager();

                sProcName = "up_Del_CityMaster";
                oDB.DbCmd = oDB.GetStoredProcCommand(sProcName);
                oDB.DbDatabase.AddInParameter(oDB.DbCmd, "@CityId", DbType.Int32, oCityData.CityId);
                oDB.ExecuteNonQuery(oDB.DbCmd);
            }
            catch (Exception exp)
            {
                oDB       = null;
                oCityData = null;
                GF.LogError("clsCityMaster.Delete", exp.Message);
                return(false);
            }
            finally
            {
                oDB       = null;
                oCityData = null;
            }
            return(true);
        }
Пример #11
0
        public ExecutionResponse <CityDTO> Update(City city)
        {
            var res = new ExecutionResponse <CityDTO>();

            try
            {
                unitOfWork.CreateTransaction();
                var cityRes = cityRepository.Update(city);
                var cityDto = new CityDTO()
                {
                    Id   = cityRes.Id,
                    Name = cityRes.Name
                };
                unitOfWork.Save();
                unitOfWork.Commit();


                res.Result = cityDto;
                return(res);
            }
            catch (Exception ex)
            {
                res.Exception = ex;
                unitOfWork.Rollback();
                return(res);
            }
        }
Пример #12
0
        public async Task <IActionResult> PutCity([FromRoute] int id, [FromBody] CityDTO cityDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != cityDTO.CityId)
            {
                return(BadRequest());
            }

            var city = await cityRepository.Edit(id, cityDTO);

            if (city == null)
            {
                return(BadRequest());
            }

            CityDTO dto = new CityDTO();

            dto.CityId    = city.CityId;
            dto.Name      = city.Name;
            dto.Latitude  = city.Latitude;
            dto.Longitude = city.Longitude;

            return(Ok(dto));
        }
Пример #13
0
        public CityDTO[] GetData(int CityId)
        {
            CityDTO[] oCityData;
            oCityData = null;
            DataSet ds;
            string  query = "select CityId, CityCode, CityName from tblCityMaster where 1=1";

            if (CityId != 0)
            {
                query += " and CityId=" + CityId;
                query += " order by CityCode";
            }
            ds = GetDataFromDB(query);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                oCityData = new CityDTO[ds.Tables[0].Rows.Count];
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    oCityData[i]          = new CityDTO();
                    oCityData[i].CityId   = Convert.ToInt32(ds.Tables[0].Rows[i][0]);
                    oCityData[i].CityCode = Convert.ToString(ds.Tables[0].Rows[i][1]);
                    oCityData[i].CityName = Convert.ToString(ds.Tables[0].Rows[i][2]);
                }
            }
            return(oCityData);
        }
Пример #14
0
        public string Replace(CityDTO model)
        {
            var entity = _context.Cities.Find(model.Id);

            if (entity == null)
            {
                return("City not found");
            }

            var duplicateName = _context.Cities.Any(x => x.Active && x.Name.ToLower() == model.Name.ToLower() && x.Id != model.Id);

            if (duplicateName)
            {
                return("Duplicate name in the database");
            }

            entity.Name   = model.Name;
            entity.UF     = model.Uf;
            entity.Active = model.Active;

            try
            {
                _context.Cities.Update(entity);
                _context.SaveChanges();

                return(entity.Name);
            }
            catch (Exception ex)
            {
                ex.Message.ToLower();
            }

            return("An unexpected error has happened");
        }
Пример #15
0
        public string Create(CityDTO model)
        {
            var duplicateName = _context.Cities.Any(x => x.Active && x.Name.ToLower() == model.Name.ToLower() && x.UF.ToLower() == model.Uf.ToLower());

            if (duplicateName)
            {
                return("Duplicate name in the database");
            }

            var entity = new City()
            {
                Id     = Guid.NewGuid(),
                Name   = model.Name,
                UF     = model.Uf,
                Active = model.Active
            };

            try
            {
                _context.Cities.Add(entity);
                _context.SaveChanges();

                return(entity.Name);
            }
            catch (Exception ex)
            {
                return(ex.Message.ToLower());
            }

            return("An unexpected error has happened");
        }
Пример #16
0
        public IHttpActionResult PutCity(int id, CityDTO city)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != city.CityId)
            {
                return(BadRequest());
            }

            Handin22.City city1 = _unitOfWork.Cities.Get(id);

            if (city1 == null)
            {
                return(NotFound());
            }

            city1.Name    = city.Name;
            city1.ZipCode = city.ZipCode;

            _unitOfWork.Complete();

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #17
0
        public ActionResult <CityDTO> Post(CityDTO newCity)
        {
            City city         = _autoMapper.Map <City>(newCity);
            City insertedCity = this._cityService.CreateCity(city);

            return(CreatedAtAction("Post", _autoMapper.Map <CityDTO>(insertedCity)));
        }
Пример #18
0
        public async Task <ActionResult> pvwAddCity([FromBody] CityDTO _sarpara)

        {
            CityDTO _City = new CityDTO();

            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/City/GetCityById/" + _sarpara.Id);

                string valorrespuesta = "";
                if (result.IsSuccessStatusCode)
                {
                    valorrespuesta = await(result.Content.ReadAsStringAsync());
                    _City          = JsonConvert.DeserializeObject <CityDTO>(valorrespuesta);
                }

                if (_City == null)
                {
                    _City = new CityDTO();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                throw ex;
            }



            return(PartialView(_City));
        }
Пример #19
0
        public static City CityDTOMapToModel(this CityDTO cityDTO)
        {
            var city = new City();

            city.Name = cityDTO.Name;
            return(city);
        }
        public async Task TestPutCityFail()
        {
            CityDTO dto = new CityDTO();

            dto.CityId    = 1000;
            dto.Latitude  = -40.0;
            dto.Longitude = 8.0;
            dto.Name      = "Second_Test_City";

            //Should not update if the city does not exist
            var result = await controller.PutCity(1000, dto);

            Assert.IsType <BadRequestResult>(result);

            //Should not update if there is a mismatch between a route id and CityId
            dto.CityId = 1;

            var result1 = await controller.PutCity(1000, dto);

            Assert.IsType <BadRequestResult>(result1);

            //Should not update if the city name already exists
            var result2 = await controller.PutCity(1, dto);

            Assert.IsType <BadRequestResult>(result2);

            //Should not update if the combination latitude/longitude already exists
            dto.Name = "Test_City_Update";
            var result3 = await controller.PutCity(1, dto);

            Assert.IsType <BadRequestResult>(result3);
        }
Пример #21
0
        public async Task <IActionResult> Put([FromBody] CityDTO cityData)
        {
            try
            {
                var city = await _repository.GetByIdAsync((int)cityData.Id);

                if (city == null)
                {
                    return(NotFound(_errorHandler.JsonErrorMessage((int)HttpStatusCode.NotFound)));
                }
                if (ModelState.IsValid)
                {
                    var updatedcity = _mapper.Map <CityDTO, City>(cityData, city);
                    updatedcity.ModifiedDate = DateTimeOffset.UtcNow;
                    await _repository.UpdateAsync(updatedcity);

                    return(Ok(CityDTO.FromCity(updatedcity)));
                }
                return(Json(ModelState));
            }
            catch (Exception ex)
            {
                return(BadRequest(_errorHandler.JsonErrorMessage((int)HttpStatusCode.BadRequest, ex.Message)));
            }
        }
Пример #22
0
        public void AddCity(CityDTO cityDTO)
        {
            var city = MappingDTO.MapCity(cityDTO);

            _dataBase.Cites.Create(city);
            _dataBase.Save();
        }
Пример #23
0
        public ActionResult <CityDTO> Post(CityDTO newCity)
        {
            var mappedCityDomain = _mapper.Map <City>(newCity);
            var insertedCity     = this._cityService.CreateCity(mappedCityDomain);

            return(CreatedAtAction("Post", _mapper.Map <CityDTO>(insertedCity)));
        }
Пример #24
0
        public async Task <IActionResult> AddCity([FromBody] CityDTO city)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid input"));
            }

            City newCity = new City()
            {
                name        = city.name,
                country     = city.country,
                attractions = city.attractions
            };

            if (_cityRepository.CheckIfExists(newCity))
            {
                return(Conflict("City already exists"));
            }

            bool created = await _cityRepository.Add(newCity);

            if (created)
            {
                return(Created("", newCity));
            }

            return(Conflict());
        }
Пример #25
0
        private async Task UploadPhotoAsync(CityDTO city, IFormFile file)
        {
            var cityId       = city.ID;
            var oldImageName = (await _repoWrapper.City.GetFirstOrDefaultAsync(
                                    predicate: i => i.ID == cityId))
                               ?.Logo;

            if (file != null && file.Length > 0)
            {
                using (var img = Image.FromStream(file.OpenReadStream()))
                {
                    var uploads = Path.Combine(_env.WebRootPath, "images\\Cities");
                    if (!string.IsNullOrEmpty(oldImageName))
                    {
                        var oldPath = Path.Combine(uploads, oldImageName);
                        if (File.Exists(oldPath))
                        {
                            File.Delete(oldPath);
                        }
                    }

                    var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                    var filePath = Path.Combine(uploads, fileName);
                    img.Save(filePath);
                    city.Logo = fileName;
                }
            }
            else
            {
                city.Logo = oldImageName ?? null;
            }
        }
Пример #26
0
        public StoreDTO GetStoreByUser(string strUserName)
        {
            StoreDTO strToReturn = null;
            UserDTO  userUser    = this.GetUserDTOByUserName(strUserName);

            if (userUser != null &&
                userUser.profile != null &&
                userUser.profile.address != null)
            {
                int?cityCode = userUser.profile.address.city;
                if (cityCode.HasValue)
                {
                    CityDTO city = this.Cities.Where(x => x._id == cityCode.Value).FirstOrDefault();
                    if (city != null)
                    {
                        strToReturn = this.GetStoreByCity(city.cityName);
                    }
                }
            }

            if (strToReturn == null)
            {
                strToReturn = this.Stores.FirstOrDefault();
            }

            return(strToReturn);
        }
Пример #27
0
        public void Execute(CityDTO request)
        {
            var city = Context.Cities.Find(request.Id);

            if (city == null || city.Deleted == true)
            {
                throw new DataNotFoundException();
            }

            if (city.CityName != request.CityName)
            {
                if (Context.Cities.Any(c => c.CityName == request.CityName))
                {
                    throw new DataAlreadyExistsException();
                }

                city.CityName  = request.CityName;
                city.UpdatedAt = DateTime.Now;
                Context.SaveChanges();
            }
            else
            {
                throw new DataNotAlteredException();
            }
        }
        public async Task ReturnNull_IfCityDoesNotExist()
        {
            //Arrange
            var mockIDateTimeProvider = new Mock <IDateTimeProvider>();
            var mockICityMapper       = new Mock <ICityMapper>();
            var mockIBarMapper        = new Mock <IBarMapper>();

            var options = Utils.GetOptions(nameof(ReturnNull_IfCityDoesNotExist));

            var updatedCityDTO = new CityDTO {
                Id = 1, Name = "Varna"
            };

            mockICityMapper
            .Setup(x => x.MapToCityDTO(It.IsAny <City>()))
            .Returns <City>(c => new CityDTO {
                Id = c.Id, Name = c.Name
            });

            Utils.GetInMemoryDataBase(options);

            //Act & Assert
            using (var assertContext = new CocktailMagicianContext(options))
            {
                var sut = new CityService(mockIDateTimeProvider.Object, assertContext, mockICityMapper.Object, mockIBarMapper.Object);

                var result = await sut.UpdateCityAsync(4, updatedCityDTO);

                Assert.IsNull(result);
            }
        }
Пример #29
0
 public bool UpdateCity(CityDTO obj)
 {
     using (DeveloperEntities DB = new DeveloperEntities())
     {
         using (var dbContextTransaction = DB.Database.BeginTransaction())
         {
             try
             {
                 DB.Configuration.ProxyCreationEnabled = false;
                 DB.Configuration.LazyLoadingEnabled   = false;
                 if (obj == null)
                 {
                     throw new ArgumentNullException("item");
                 }
                 DB.InsertCity(obj.CID, obj.CountryID, obj.CityName);
                 DB.SaveChanges();
                 dbContextTransaction.Commit();
                 return(true);
             }
             catch (Exception)
             {
                 dbContextTransaction.Rollback();
                 throw;
             }
         }
     }
 }
Пример #30
0
    private void Save()
    {
        if (!base.ValidateIfCommandAllowed(Request.Url.AbsoluteUri, ENums.PageCommand.Add))
        {
            return;
        }

        bool    bActionCompleted = false;
        CityDTO oCityData        = new CityDTO();

        oCityData.CityCode = Convert.ToString(txtCityCode.Text);
        oCityData.CityName = Convert.ToString(txtCityName.Text);
        CityMaster oCityMaster = new CityMaster();

        bActionCompleted = oCityMaster.Insert(oCityData);
        if (bActionCompleted == true)
        {
            base.DisplayAlert("The record has been inserted successfully");
            txtCityName.Text = "";
            txtCityCode.Text = "";
        }
        else
        {
            lblStatus.Text = "Error Occured while insertion: Please refer to the error log.";
        }
    }
Пример #31
0
        public OktmoDtoTests()
        {
            var xCity = new CityDTO {Name = "Москва", Type = "город"};
            var yCity = new CityDTO {Name = "Спб", Type = "город"};

            var xSet = new SettlementDTO();

            x = new OktmoRowDTO{Subject = "Москва",Region = "город Москва",City =xCity,Settlement = xSet};
            y = new OktmoRowDTO{Subject = "Спб",Region = "город Спб",City =yCity,Settlement = xSet};
            z = new OktmoRowDTO{Subject = "Москва",Region = "город Москва",City =xCity,Settlement = xSet};
        }
Пример #32
0
 public OktmoRowDTO()
 {
     Settlement = new SettlementDTO();
     City = new CityDTO();
 }
Пример #33
0
 public VgtRowDTO()
 {
     City = new CityDTO();
 }