public async Task GetCountriesForTrip_TripWithNoStops_EmptyListOfCountries() { var dbOptions = DbSettingHellper.GetDbOptions(_output); //Arrange using (var context = new MCBContext(dbOptions)) { context.Database.OpenConnection(); context.Database.EnsureCreated(); context.Add(new Trip() { Id = 8, Name = "Trip 1" }); await context.SaveChangesAsync(); } using (var context = new MCBContext(dbOptions)) { var geoRepository = new GeoRepository(context); // Act var countries = await geoRepository.GetCountriesForTrip(8); // Assert Assert.Empty(countries); } }
public object Post(Geo pModel) { if (ModelState.IsValid) { _repo = new GeoRepository(); var newId = _repo.Insert(pModel); var message = JsonSerializer.Serialize(pModel, typeof(Geo)); Task t = InvokeAsync(message, (model, ea) => { _repo = new GeoRepository(); var body = ea.Body.ToArray(); var jsonReply = Encoding.UTF8.GetString(body); if (jsonReply == "") { pModel.Estado = Geo.eEstados.ErrorOSM; _repo.Update(pModel); return; } var g = JsonSerializer.Deserialize(jsonReply, typeof(Geo)); if (g is Geo) { (g as Geo).Estado = Geo.eEstados.Terminado; _repo.Update(g as Geo); } return; }); return("{Id: " + newId + "}"); } return("Error en la carga!"); }
public JsonResult ListGeo2(string parentFullName) { GeoRepository geoRepository = new GeoRepository(); Geo e = geoRepository.GetByFullname(parentFullName); return(Json(e.Children.Select(r => new { r.ID, r.FullName }).OrderBy(r => r.FullName))); }
public JsonResult GetCities(string country, string state) { var result = new JsonResult(); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; var repo = new GeoRepository(); result.Data = repo.GetCities(state); return(result); }
public object Get([FromQuery(Name = "id")] string id) { _repo = new GeoRepository(); Regex r = new Regex(@"[^0-9]"); if (id != null && id != "" && !r.IsMatch(id)) { return(Models.Response.Parse(_repo.Get(int.Parse(id)))); } return(_repo.Get()); }
public ActionResult Index(ReaderViewModel model) { var repo = new GeoRepository(); var repoReader = new ReaderRepository(); model.CountryOptions = repo.GetCountries(); model.StateOptions = (!string.IsNullOrWhiteSpace(model.Country)) ? repo.GetStates(model.Country) : defaultListItem; model.CityOptions = (!string.IsNullOrWhiteSpace(model.State)) ? repo.GetCities(model.State) : defaultListItem; model.CategoryOptions = repo.GetCategory(); model.SubCategoryOptions = defaultListItem; model.information = repoReader.GetRecords(model); return(View(model)); }
// GET: Search public ActionResult Index() { var repo = new GeoRepository(); var model = new ReaderViewModel() { CountryOptions = repo.GetCountries(), StateOptions = defaultListItem, CityOptions = defaultListItem, CategoryOptions = repo.GetCategory(), SubCategoryOptions = defaultListItem }; return(View(model)); }
public async Task GetCountriesForTrip_TripWithTwoStopsAndOneCountry_ListOfOneCountry() { var dbOptions = DbSettingHellper.GetDbOptions(_output); //Arrange using (var context = new MCBContext(dbOptions)) { context.Database.OpenConnection(); context.Database.EnsureCreated(); var trip1 = new Trip() { Id = 8, Name = "Trip 1", Stops = new List <Stop>() { new Stop() { Name = "Stop 1", CountryId = 5, Country = new Country { Id = 5, Name = "Poland" } }, new Stop() { Name = "Stop 2", CountryId = 5, Country = new Country { Id = 5, Name = "Poland" } } } }; context.Add(trip1); await context.SaveChangesAsync(); } using (var context = new MCBContext(dbOptions)) { var geoRepository = new GeoRepository(context); // Act var countries = await geoRepository.GetCountriesForTrip(8); // Assert Assert.Single(countries); } }
static void Main(string[] args) { IGeoRepository _dal = new GeoRepository(); var districts = _dal.GetDistricts(); string url = "https://nominatim.openstreetmap.org/search?q={0}&limit=5&format=json&addressdetails=1"; string pingUrl; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.UserAgent.Clear(); client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("f1ana.Nominatim.API", Assembly.GetExecutingAssembly().GetName().Version.ToString())); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); foreach (var dis in districts) { try { pingUrl = string.Format(url, dis.Name).ToString(); HttpResponseMessage response = client.GetAsync(pingUrl).Result; string data = response.Content.ReadAsStringAsync().Result; List <GeoLocations> result = JsonConvert.DeserializeObject <List <GeoLocations> >(data); foreach (var item in result) { Locations loc = new Locations(); loc.PlaceId = item.place_id; loc.Lon = item.lon; loc.Lat = item.lat; loc.DisplayName = item.display_name; loc.DistrictId = dis.Id; _dal.SaveLocation(loc); } System.Threading.Thread.Sleep(1000); } catch { continue; } } }
public static MvcHtmlString DropDownListForGeo1 <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression) { GeoRepository geoRepository = new GeoRepository(); return(htmlHelper.DropDownListFor(expression, geoRepository.GetByParentID().ToSelectListItem(), OAMSSetting.messageL.SelectNone)); }
public GeoService() { _geoRepository = new GeoRepository(); }
void DoWork() { try { Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyyHH:mm:ss")} Сервис запущен"); DownloadService service = new DownloadService(); Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт скачивание файла GeoLite2-City-CSV.zip "); if (string.IsNullOrEmpty(ConfigurationService.DownloadFileHref)) { throw new Exception("Настройте ключ DownloadFileHref в конфиг файле App.config"); } string filePath = service.DownloadFile(ConfigurationService.DownloadFileHref); // обновляем только в среду, так как данные на сайте обновляются только во вторник или указана AlwaysUpdate=true в конфиге if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || ConfigurationService.AlwaysUpdate) { CSVService csvServ = new CSVService(); GeoRepository repository = new GeoRepository(); string filePathLocations = string.Format($"{filePath}\\{fileNameLocations}"); if (!File.Exists(filePathLocations)) { throw new Exception($"Загруженный файл {fileNameLocations} не был найден"); } Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт считывание файла GeoLite2-City-Locations-ru.csv, подождите... "); var itemsLocations = csvServ.GetDataTabletFromCSVFile(filePathLocations); // загружаем файл Locations Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Запись в базу файла GeoLite2-City-Locations-ru.csv, подождите..."); repository.DeleteData("Stp_ClearCityLocationRu"); repository.InsertDataUsingSQLBulkCopy(itemsLocations, "CityLocationsRu"); string filePathCity = string.Format($"{filePath}\\{fileNameCity}"); if (!File.Exists(filePathCity)) { throw new Exception($"Загруженный файл {fileNameCity} не был найден"); } Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Идёт считывание файла GeoLite2-City-Blocks-IPv4.csv, подождите... "); var itemsCity = csvServ.GetDataTabletFromCSVFile(filePathCity); // загружаем файл City Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Запись в базу файла GeoLite2-City-Blocks-IPv4.csv, подождите..."); repository.DeleteData("Stp_ClearCityBlocksIPv4"); repository.InsertDataUsingSQLBulkCopy(itemsCity, "CityBlocksIPv4"); Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Данные в базе были обновлены"); } else { Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Данные не требуют обновления"); } Console.WriteLine($"{ DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} Работа сервиса завершена успешно "); Thread.Sleep(new TimeSpan(ConfigurationService.AfterDaysToRunApp, 0, 0, 0)); // настраиваем через какое время запускаться, ключ вынесен в конфиг DoWork(); } catch (Exception ex) { Console.WriteLine($"{ex?.Message} {ex?.InnerException}"); Console.ReadLine(); } }