Beispiel #1
0
        private void DeleteUserButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = this.lvCity.SelectedItem;

            if (selectedItem != null)
            {
                CityEntity city = selectedItem as CityEntity;

                CityService service = new CityService();
                if (MessageBox.Show("Sei sicuro di voler eliminare \"" + city.CityName + " \" ?", "Elimina Città", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    if (service.Delete(city) == 0)
                    {
                        MessageBox.Show("cancellato!");
                        this.RefreshData();
                    }
                    else
                    {
                        MessageBox.Show("NON cancellato!");
                    }
                }
                else
                {
                    MessageBox.Show("NON cancellato!");
                }
            }
        }
Beispiel #2
0
        public int Insert(CityEntity entity)
        {
            _context.Cities.Add(entity);
            _context.SaveChanges();

            return(entity.CityId);
        }
        public DijkstraAlgorithmTest()
        {
            cityLS = new CityEntity("Los Santos", "LS");
            citySF = new CityEntity("San Fierro", "SF");
            cityLV = new CityEntity("Las Venturas", "LV");
            cityRC = new CityEntity("Red County", "RC");
            cityWS = new CityEntity("Whetstone", "WS");
            cityBC = new CityEntity("Bone County", "BC");
            cityNF = new CityEntity("Not Found", "NF");

            routes = new List <RouteEntity>
            {
                new RouteEntity(cityLS, citySF, 1),
                new RouteEntity(citySF, cityLS, 2),
                new RouteEntity(cityLS, cityLV, 1),
                new RouteEntity(cityLV, cityLS, 1),
                new RouteEntity(citySF, cityLV, 2),
                new RouteEntity(cityLV, citySF, 2),
                new RouteEntity(cityLS, cityRC, 1),
                new RouteEntity(cityRC, cityLS, 2),
                new RouteEntity(citySF, cityWS, 1),
                new RouteEntity(cityWS, citySF, 2),
                new RouteEntity(cityLV, cityBC, 1),
                new RouteEntity(cityBC, cityLV, 1),
            };
        }
        private void DFS(CityEntity city, int distance, Dictionary <CityEntity, int> furthestCityIds, int maxDist, List <CityEntity> visited)
        {
            visited.Add(city);

            if (city.RoadFrom.Count == 0 || !city.RoadFrom.Any(r => !visited.Contains(r.To)))
            {
                if (distance > maxDist)
                {
                    maxDist = distance;

                    if (furthestCityIds.ContainsKey(city))
                    {
                        furthestCityIds[city]++;
                    }
                    else
                    {
                        furthestCityIds.Add(city, 1);
                    }
                }
            }
            else
            {
                foreach (var road in city.RoadFrom)
                {
                    if (!visited.Contains(road.To))
                    {
                        distance += road.Distance;
                        DFS(road.To, distance, furthestCityIds, maxDist, visited);
                    }
                }
            }
        }
Beispiel #5
0
        private City CreateDomainObject(CityEntity cityEntity)
        {
            List <Stop> stops = _cityRepository.GetStopByCityId(cityEntity.CityId).ToStopList();
            City        city  = cityEntity.ToDomainObject(stops);

            return(city);
        }
Beispiel #6
0
        public async Task AddAsync_Should_Add_City()
        {
            var city = City.Builder()
                       .SetId(Guid.NewGuid())
                       .SetRowVersion(Array.Empty <byte>())
                       .SetName("CityRepositoryTestAddAsync")
                       .SetPolishName("CityRepositoryTestAddAsync")
                       .SetStateId(_stateEntity.Id)
                       .Build();
            var cityEntity = new CityEntity
            {
                Id         = city.Id,
                Name       = city.Name,
                PolishName = city.PolishName,
                RowVersion = city.RowVersion.ToArray(),
                StateId    = city.StateId
            };

            _mapperMock.Setup(x => x.Map <City, CityEntity>(It.IsAny <City>()))
            .Returns(cityEntity);
            _memoryCacheMock.Setup(x => x.Remove(It.IsAny <object>()));

            Func <Task> result = async() => await _repository.AddAsync(city);

            await result.Should().NotThrowAsync <Exception>();

            var addedCity = await _dbContext.Cities.FindAsync(city.Id);

            addedCity.Should().NotBeNull();
            _memoryCacheMock.Verify(x => x.Remove(It.Is <object>(key => ReferenceEquals(key, CacheKeys.CitiesKey))));
        }
Beispiel #7
0
        public async Task <CityEntity> GetCityAsync(int Id)
        {
            CityEntity cityEntity = await _context.Cities
                                    .FirstOrDefaultAsync(m => m.Id == Id);

            return(cityEntity);
        }
Beispiel #8
0
        public async Task SeedAsync()
        {
            await _dataContext.Database.EnsureCreatedAsync();

            await CheckRolesAsync();
            await CheckUserAsync("1010", "Juan", "Londono", "*****@*****.**", "319 627 1487", UserType.Admin);

            UserEntity Employee = await CheckUserAsync("2020", "Juan", "Londono", "*****@*****.**", "319 627 1487", UserType.Employee);

            UserEntity Employee2 = await CheckUserAsync("3030", "Juan", "Londono", "*****@*****.**", "300 842 3521", UserType.Employee);

            ExpenseTypeEntity Expense1 = await _expenseTyperHelper.AddExpenseTypeAsync("Estancia");

            ExpenseTypeEntity Expense2 = await _expenseTyperHelper.AddExpenseTypeAsync("Manutención");

            ExpenseTypeEntity Expense3 = await _expenseTyperHelper.AddExpenseTypeAsync("Locomoción");

            CityEntity City1 = await _citierHelper.AddCityAsync("Medellín");

            CityEntity City2 = await _citierHelper.AddCityAsync("Bogotá");

            await CheckLegalizeAsync(Employee, Employee2, City1, City2, Expense1, Expense2, Expense3);
            await CheckCityAsync();

            // await CheckExpenseTypeAsync();
        }
        public async Task <bool> CheckDuplicateAsync(CityEntity city)
        {
            CityEntity duplicate =
                _citiesData.FirstOrDefault(x => x.Name == city.Name && x.CountryId == city.CountryId);

            return(duplicate != null);
        }
Beispiel #10
0
        /* This method applies Prim's algorithm to the cities and routes
         * saved in the database*/
        private List <RouteEntity> ApplyPrim(CityEntity node)
        {
            int allNodes = dataAccessService.CityRepository.GetCount();
            List <RouteEntity> treeRoutes    = new List <RouteEntity>();
            List <RouteEntity> available     = new List <RouteEntity>();
            List <CityEntity>  visitedCities = new List <CityEntity>();
            List <RouteEntity> routes        = dataAccessService.RouteRepository.GetRoutesByCity(node.Id, visitedCities.Select(c => c.Id).ToArray());

            //getting available routes
            available.AddRange(routes);

            /*until all the routes are visited or the tree routes are not as many as
             * the number of the cities - 1*/
            while (treeRoutes.Count != allNodes - 1 && available.Count != 0)
            {
                //selecting the min route
                RouteEntity forAdd = available.Where(a => a.Distance == available.Min(a2 => a2.Distance)).FirstOrDefault();
                if (forAdd != null)
                {
                    treeRoutes.Add(forAdd);
                    available.Remove(forAdd);
                    if (visitedCities.Contains(forAdd.Start))
                    {
                        visitedCities.Add(forAdd.End);
                    }
                    else if (visitedCities.Contains(forAdd.End))
                    {
                        visitedCities.Add(forAdd.Start);
                    }
                    else
                    {
                        visitedCities.Add(node);
                    }
                    if (forAdd.End?.Id != node.Id)
                    {
                        node = forAdd.End;
                    }
                    else
                    {
                        node = forAdd.Start;
                    }
                }
                routes = dataAccessService.RouteRepository.GetRoutesByCity(node.Id, visitedCities.Select(c => c.Id).ToArray());
                foreach (var route in routes)
                {
                    if (!available.Contains(route))
                    {
                        available.Add(route);
                    }
                }
                //removing routes that connect already visited cities
                List <RouteEntity> forRemoval = available.Where(r => visitedCities.Select(c => c.Id).ToArray().Contains(r.Start.Id) &&
                                                                visitedCities.Select(c => c.Id).ToArray().Contains(r.End.Id)).ToList();
                foreach (var item in forRemoval)
                {
                    available.Remove(item);
                }
            }
            return(treeRoutes);
        }
Beispiel #11
0
        public async Task SaveAsync(ICity city)
        {
            using (var databaseContext = _databaseContextFactory.Create())
            {
                var cityEntity = await databaseContext
                                 .City
                                 .SingleOrDefaultAsync(entity => entity.Code == city.Code);

                if (cityEntity == null)
                {
                    cityEntity = new CityEntity
                    {
                        Code = city.Code
                    };

                    databaseContext.City.Add(cityEntity);
                }

                if (cityEntity.Name == city.Name)
                {
                    return;
                }

                cityEntity.Name = city.Name;

                await databaseContext.SaveChangesAsync();
            }
        }
Beispiel #12
0
        public async Task UpdateAsync_Should_Update_City()
        {
            var city = _fixture.InsertCity("CityRepositoryTestUpdateAsync");

            city.ChangeName("CityRepositoryTestUpdateAsyncNewName");
            var cityEntity = new CityEntity
            {
                Id         = city.Id,
                Name       = city.Name,
                PolishName = city.PolishName,
                RowVersion = city.RowVersion.ToArray(),
                StateId    = city.StateId
            };

            _mapperMock.Setup(x => x.Map <City, CityEntity>(It.IsAny <City>()))
            .Returns(cityEntity);
            _memoryCacheMock.Setup(x => x.Remove(It.IsAny <object>()));

            Func <Task> result = async() => await _repository.UpdateAsync(city);

            await result.Should().NotThrowAsync <Exception>();

            var updatedCity = await _dbContext.Cities.FindAsync(city.Id);

            updatedCity.Name.Should().BeEquivalentTo(city.Name);
            _memoryCacheMock.Verify(x => x.Remove(It.Is <object>(key => ReferenceEquals(key, CacheKeys.CitiesKey))));
        }
        public async Task <CityData> GetCityByIdAsync(int id)
        {
            CityEntity x = await _context.Cities.Include(x => x.Coord).SingleOrDefaultAsync(x => x.Id == id);

            if (x == null)
            {
                return(new CityData()
                {
                    Id = id,
                    Name = "Not Found"
                });
            }

            return(new CityData()
            {
                Id = x.Id,
                Name = x.Name,
                State = x.State,
                Country = x.Country,
                Coord = new Coord()
                {
                    Lon = (x.Coord == null) ? 0 : x.Coord.Lon,
                    Lat = (x.Coord == null) ? 0 : x.Coord.Lat
                }
            });
        }
        public JsonResultEntity Create([FromBody] CityEntity cityEntity)
        {
            CityBL           cityBL   = new CityBL();
            JsonResultEntity response = new JsonResultEntity();

            try
            {
                var result = cityBL.Create(cityEntity);

                if (result.HasWarning())
                {
                    response.Message = String.Join(",", result.Warning);
                    return(response);
                }

                response.Success = true;
                response.Data    = result.Value;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                LoggerHelper.Error(ex);
            }

            return(response);
        }
Beispiel #15
0
        public OkResult Post([FromBody] CityViewModel city)
        {
            CityEntity entity = mapper.Map <CityEntity>(city);

            this.cityService.AddCity(entity);
            return(Ok());
        }
        public async Task <IActionResult> Edit(int id, CityEntity cityEntity)
        {
            if (id != cityEntity.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                _context.Update(cityEntity);
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (Exception ex)
                {
                    if (ex.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, $"Already exists  type: {cityEntity.Name}.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.InnerException.Message);
                    }
                }
            }
            return(View(cityEntity));
        }
Beispiel #17
0
        public async Task <City> GetByIdAsync(int id)
        {
            CityEntity foundCityDal = await _cityRepository.GetAsync(id);

            City foundCity = _mapper.Map <City>(foundCityDal);

            return(foundCity);
        }
 public int InsertOrUpdate(CityEntity entity)
 {
     if (entity.ID != 0)
     {
         return(CityDatabase.UpdateAsync(entity).Result);
     }
     return(CityDatabase.InsertAsync(entity).Result);
 }
Beispiel #19
0
 public async Task UpdateCityAsync(CityEntity city)
 {
     await Task.Run(() =>
     {
         _uow.Repository <CityEntity>().Update(city);
         _uow.Save();
     });
 }
Beispiel #20
0
 public CityResponse ToCityResponse(CityEntity cityEntity)
 {
     return(new CityResponse
     {
         Id = cityEntity.Id,
         Name = cityEntity.Name
     });
 }
Beispiel #21
0
        public City GetCity(int id)
        {
            CityEntity cityEntity = _cityRepository.GetById(id);

            City city = CreateDomainObject(cityEntity);

            return(city);
        }
Beispiel #22
0
 // PUT api/city/5
 public bool Put(int id, [FromBody] CityEntity cityEntity)
 {
     if (id > 0)
     {
         return(_cityServices.UpdateCity(id, cityEntity));
     }
     return(false);
 }
        /// <summary>Creates a new, empty CityEntity object.</summary>
        /// <returns>A new, empty CityEntity object.</returns>
        public override IEntity Create()
        {
            IEntity toReturn = new CityEntity();

            // __LLBLGENPRO_USER_CODE_REGION_START CreateNewCity
            // __LLBLGENPRO_USER_CODE_REGION_END
            return(toReturn);
        }
Beispiel #24
0
        public CityEntity FindLogisticCenter(CityEntity node)
        {
            //applying Prim's algorithm could provide us the Minimum Spanning tree
            List <RouteEntity> maxSpanningTreeRoutes = ApplyPrim(node);
            List <CityEntity>  cities = dataAccessService.CityRepository.GetAll().ToList();

            /*for each of the cities we define the Closeness Centrality Coeficient
             * which is a 1 divided by the sum of all routes between a given city and
             * all other cities */
            foreach (CityEntity city in cities)
            {
                double             fullDistance = 0;
                List <RouteEntity> visited      = new List <RouteEntity>();
                //keep the calculated path weight for every city in a dictionary
                Dictionary <int, double> calculatedRoutes = new Dictionary <int, double>();
                //the path weight from the current city to itself is evaluated as 0
                calculatedRoutes.Add(city.Id, 0);
                int currentId;
                //when going through the tree we keep tracking cities in a queue
                Queue <int> queue = new Queue <int>();
                queue.Enqueue(city.Id);
                while (queue.Any())
                {
                    currentId = queue.Dequeue();
                    List <RouteEntity> routes = maxSpanningTreeRoutes.Where(r => r.Start.Id == currentId || r.End.Id == currentId).ToList();
                    foreach (var route in routes)
                    {
                        if (!visited.Contains(route))
                        {
                            //the calculated path is equal to the path before the dequeued city added to the route's distance
                            if (route.End.Id == currentId)
                            {
                                calculatedRoutes.Add(route.Start.Id, calculatedRoutes[currentId] + route.Distance);
                                queue.Enqueue(route.Start.Id);
                            }
                            else if (route.Start.Id == currentId)
                            {
                                calculatedRoutes.Add(route.End.Id, calculatedRoutes[currentId] + route.Distance);
                                queue.Enqueue(route.End.Id);
                            }
                            visited.Add(route);
                        }
                    }
                }
                fullDistance = calculatedRoutes.Values.Sum();
                if (fullDistance != 0)
                {
                    city.ClosenessCentralityCoefficient = 1 / fullDistance;
                }
                else
                {
                    city.ClosenessCentralityCoefficient = 0;
                }
                this.dataAccessService.CityRepository.Update(city);
            }
            //returns the city with the highest Closeness Centrality Coeficient
            return(cities.Where(c => c.ClosenessCentralityCoefficient == cities.Max(c1 => c1.ClosenessCentralityCoefficient)).FirstOrDefault());
        }
Beispiel #25
0
        public async Task <IActionResult> PostEstablishmentLocation([FromBody] EstablishmentLocationRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Bad request",
                    Result = ModelState
                }));
            }

            EstablishmentEntity establishment = await _context.Establishments.FirstOrDefaultAsync(e => e.Id == request.IdEstablishment);

            CityEntity city = await _context.Cities.FirstOrDefaultAsync(c => c.Id == request.IdCity);

            TypeEstablishmentEntity typeEstablishment = await _context.TypeEstablishments.FirstOrDefaultAsync(te => te.Id == request.IdTypeEstablishment);

            List <EstablishmentLocationEntity> establishmentLocationEntity = await _context.EstablishmentLocations
                                                                             .Include(m => m.Establishments)
                                                                             .Include(m => m.Foods)
                                                                             .ThenInclude(m => m.TypeFoods)
                                                                             .Include(m => m.Foods)
                                                                             .ThenInclude(m => m.User)
                                                                             .Include(m => m.Cities)
                                                                             .Include(m => m.TypeEstablishment)
                                                                             .Where(e => e.Establishments.Id == request.IdEstablishment)
                                                                             .ToListAsync();

            var LatitudeValidation  = establishmentLocationEntity.FirstOrDefault(el => el.SourceLatitude == request.SourceLatitude);
            var LongitudeValidation = establishmentLocationEntity.FirstOrDefault(el => el.SourceLongitude == request.SourceLongitude);

            if (LatitudeValidation != null & LongitudeValidation != null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Establishment location exist"
                }));
            }

            EstablishmentLocationEntity establishmentLocation = new EstablishmentLocationEntity
            {
                SourceLatitude    = request.SourceLatitude,
                SourceLongitude   = request.SourceLongitude,
                TargetLatitude    = request.TargetLatitude,
                TargetLongitude   = request.TargetLongitude,
                Remarks           = request.Remarks,
                Establishments    = establishment,
                Cities            = city,
                TypeEstablishment = typeEstablishment
            };

            _context.EstablishmentLocations.Add(establishmentLocation);
            await _context.SaveChangesAsync();

            return(Ok(_converterHelper.ToEstablishmentLocationResponse(establishmentLocation)));
        }
        public static CityEntity CityResponseToEntity(CityResponse cityResponse)
        {
            CityEntity cityEntity = new CityEntity()
            {
                Name = cityResponse.Name
            };

            return(cityEntity);
        }
        public static CityResponse CityEntityToResponse(CityEntity cityEntity)
        {
            CityResponse cityResponse = new CityResponse()
            {
                Name = cityEntity.Name
            };

            return(cityResponse);
        }
Beispiel #28
0
        private CityDTO ToDTO(CityEntity city)
        {
            CityDTO dto = new CityDTO();

            dto.CreateDateTime = city.CreateDateTime;
            dto.Id             = city.Id;
            dto.Name           = city.Name;
            return(dto);
        }
Beispiel #29
0
        public CityDTO ToDTO(CityEntity city)
        {
            CityDTO cityDto = new CityDTO();

            cityDto.Name           = city.Name;
            cityDto.Id             = city.Id;
            cityDto.CreateDateTime = city.CreateDateTime;
            return(cityDto);
        }
Beispiel #30
0
 /// <summary> setups the sync logic for member _city</summary>
 /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param>
 private void SetupSyncCity(IEntity2 relatedEntity)
 {
     if (_city != relatedEntity)
     {
         DesetupSyncCity(true, true);
         _city = (CityEntity)relatedEntity;
         base.PerformSetupSyncRelatedEntity(_city, new PropertyChangedEventHandler(OnCityPropertyChanged), "City", CityZipEntity.Relations.CityEntityUsingCityId, true, new string[] {  });
     }
 }