public void TearDown() { DbContext.WeatherReading.RemoveRange(DbContext.WeatherReading); DbContext.Place.RemoveRange(DbContext.Place); DbContext.User.RemoveRange(DbContext.User); DbContext.SaveChanges(); }
public ActionResult PutPreferedCities(InsertCities insertCities) { var userName = User.Claims.Single(a => a.Type == System.Security.Claims.ClaimTypes.NameIdentifier).Value; var settings = _context.UserSettings.Include(x => x.FavoriteCities).FirstOrDefault(x => x.User == userName); settings.FavoriteCities.Clear(); var cities = _context.Cities.ToList(); foreach (var city in insertCities.CitiesId) { if (cities.FirstOrDefault(i => i.Id == city.CityId) == null) { continue; } settings.FavoriteCities.Add(new FavoriteCities { UserId = settings.Id, City = cities.FirstOrDefault(i => i.Id == city.CityId) }); } _context.SaveChanges(); return(Ok()); }
public IActionResult Post() { try { var weatherStations = _importService.GetAllStations(); var simpleStationList = new List <SimpleStation>(); foreach (var station in weatherStations.Station) { var simpleStation = new SimpleStation { Name = station.Name, Id = station.Id.ToString(), Latitude = station.Latitude, Longitude = station.Longitude, Altitude = station.Height }; simpleStationList.Add(simpleStation); } _db.Stations.AddRange(simpleStationList); _db.SaveChanges(); return(Ok("Import complete")); } catch (Exception) { return(StatusCode(503)); } }
public ActionResult <Weather> PostWeatherType(WeatherType weatherType) { _context.WeatherType.Add(weatherType); _context.SaveChanges(); return(CreatedAtAction("GetWeatherType", new Weather { Id = weatherType.Id }, weatherType)); }
public ActionResult <Weather> PostWeatherItem(Weather weather) { _context.WeatherItems.Add(weather); _context.SaveChanges(); return(CreatedAtAction("GetWeatherItem", new Weather { Id = weather.Id }, weather)); }
public ActionResult <Location> PostLocationItem(Location location) { _context.Location.Add(location); _context.SaveChanges(); return(CreatedAtAction("GetWeatherItem", new Weather { Id = location.Id }, location)); }
//return type WeatherDetail //take a WeatherDetail data as input //save input data to server/database public WeatherDetail CreateWeatherDetail(WeatherDetail weatherDetail) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } _context.WeatherDetails.Add(weatherDetail); _context.SaveChanges(); return(weatherDetail); }
public void AddItems() { _context.Locations.AddRange( new Location(1, "Västerås", "721 30"), new Location(2, "Västerås", "722 28"), new Location(3, "Malmö", "211 11"), new Location(4, "Stockholm", "112 44") ); _context.SaveChanges(); var random = new Random(); _context.WeatherItems.AddRange( new WeatherItem(1, DateTime.Now, random.GetRandomDouble(-20, 40), random.GetRandomDouble(0, 103), random.GetRandomDouble(0, 100), random.GetRandomDouble(-20, 40), 1), new WeatherItem(2, DateTime.Now, random.GetRandomDouble(-20, 40), random.GetRandomDouble(0, 103), random.GetRandomDouble(0, 100), random.GetRandomDouble(-20, 40), 2), new WeatherItem(3, DateTime.Now, random.GetRandomDouble(-20, 40), random.GetRandomDouble(0, 103), random.GetRandomDouble(0, 100), random.GetRandomDouble(-20, 40), 3), new WeatherItem(4, DateTime.Now, random.GetRandomDouble(-20, 40), random.GetRandomDouble(0, 103), random.GetRandomDouble(0, 100), random.GetRandomDouble(-20, 40), 4), new WeatherItem(5, DateTime.Now.AddDays(-2), random.GetRandomDouble(-20, 40), random.GetRandomDouble(0, 103), random.GetRandomDouble(0, 100), random.GetRandomDouble(-20, 40), 4) ); _context.SaveChanges(); }
private void DeleteObsoletedData() { using (WeatherContext db = new WeatherContext()) { DateTime UTCtime = DateTime.Now.ToUniversalTime(); var forecastForDeleting = from f in db.Forecasts where f.date < UTCtime select f; foreach (var f in forecastForDeleting) { db.Forecasts.Remove(f); } var ratingBySource = db.Ratings.GroupBy(x => x.Source); foreach (var gr in ratingBySource) { var ratingGroupForDeleting = from f in gr group f by(f.ForecastDate - f.ForecastFor) into g //farness select g.OrderByDescending(x => x.ForecastDate).Skip(countRatingsForStorage); foreach (var deletingGroup in ratingGroupForDeleting) { db.Ratings.RemoveRange(deletingGroup); } } try { db.SaveChanges(); } catch (Exception ex) { Logger.Log.Error("An error occurred while trying to Delete Obsoleted forecasts and ratings in DeleteObsoletedData in WeatherSourceContainer", ex); } } }
public async Task <ActionResult> RegisterAsync(AuthAccount request) { var result = await _userManager.CreateAsync(new IdentityUser { UserName = request.Email, Email = request.Email, }, request.Password); if (!result.Succeeded) { return(BadRequest(new { result.Errors, })); } else { _context.UserSettings.Add(new UserSettings { User = request.Email, Units = 0, }); _context.SaveChanges(); } return(Ok()); }
public async Task <Root> GetWeatherDataAsync(string url) { WebRequest webRequest = WebRequest.Create(url); WebResponse webResponse = await webRequest.GetResponseAsync(); using (Stream stream = webResponse.GetResponseStream()) { StreamReader reader = new StreamReader(stream); string responceFromServer = await reader.ReadToEndAsync(); Root result = JsonConvert.DeserializeObject <Root>(responceFromServer); try { using (_context) { _context.Roots.Add(result); _context.SaveChanges(); } } catch (Exception exception) { Debug.WriteLine(new string('-', 50)); Debug.WriteLine(exception); } return(result); } }
private void Init() { if (!db.WeatherEntities.Any()) { db.WeatherEntities.AddRange( new WeatherEntity() { CityName = "C1", Temperature = 13 }, new WeatherEntity() { CityName = "C2", Temperature = 23 }, new WeatherEntity() { CityName = "C3", Temperature = 432 }, new WeatherEntity() { CityName = "C4", Temperature = 2 }, new WeatherEntity() { CityName = "C5", Temperature = 4 } ); db.SaveChanges(); } }
public void Commit() { try { _context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entidade do tipo \"{0}\" no estado \"{1}\" tem os seguintes erros de validação:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Erro: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } catch (Exception) { throw; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { var optionBuilder = new DbContextOptionsBuilder <WeatherContext>(); var options = optionBuilder.UseSqlServer(Configuration.GetConnectionString("WeatherDBConnection")).Options; using (WeatherContext db = new WeatherContext(options)) { var allRows = db.WeatherRows; db.WeatherRows.RemoveRange(allRows); db.SaveChanges(); Console.WriteLine("ќбъекты успешно удалены"); } app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
UpdateForecastAsync(WeatherForecast objWeatherForecast) { using (var context = new WeatherContext()) { var ExistingWeatherForecast = context.WeatherForecast .Where(x => x.Id == objWeatherForecast.Id) .FirstOrDefault(); if (ExistingWeatherForecast != null) { ExistingWeatherForecast.Date = objWeatherForecast.Date; ExistingWeatherForecast.Summary = objWeatherForecast.Summary; ExistingWeatherForecast.TemperatureC = objWeatherForecast.TemperatureC; ExistingWeatherForecast.TemperatureF = objWeatherForecast.TemperatureF; context.SaveChanges(); } else { return(Task.FromResult(false)); } } return(Task.FromResult(true)); }
public SimpleStation Save(SimpleStation station) { _db.Stations.Add(station); _db.SaveChanges(); return(station); }
private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) { int interval = Convert.ToInt32(ConfigHelper.Get("Interval:Data")); if (DateTime.Now.Minute % interval != 0) { return; } try { Weather weather = await GetWeatherAsync(); using WeatherContext context = new WeatherContext(); context.Add(weather); context.SaveChanges(); if (DateTime.Now.Minute == 0 || DateTime.Now.Minute == 30) { await PostWeiboAsync(weather); } } catch (Exception ex) { Console.WriteLine(ex); } }
public async Task <IActionResult> Post() { var root = await _stationsDownloader.Download(); var weatherStations = new List <WeatherStation>(); foreach (var station in root.station) { var weatherStation = new WeatherStation { Id = station.id.ToString(), Name = station.name, Altitude = station.height, Latitude = station.latitude, Longitude = station.longitude }; weatherStations.Add(weatherStation); } _db.AddRange(weatherStations); _db.SaveChanges(); return(Ok("Import completed!")); }
public WeatherStation Save(WeatherStation station) { _db.Stations.Add(station); _db.SaveChanges(); return(station); }
public int LogWeatherEvent(DateTime datetime, WeatherType type, bool happy, string name, string quote) { //This controller method demonstrates that DbSet Add behaves the same //as EF6: affecting every item in a [disconnected] graph with the same state //As well as Attach, Remove and the new Update. WeatherEvent wE; if (String.IsNullOrEmpty(name)) { wE = WeatherEvent.Create(datetime, type, happy); } else { wE = WeatherEvent.Create(datetime, type, happy, new List <string[]> { new[] { name, quote } }); } _context.WeatherEvents.Add(wE); var affectedRowCount = _context.SaveChanges(); return(affectedRowCount); }
public void Seedit(string jsonData) { JsonSerializerSettings settings = new JsonSerializerSettings { ContractResolver = new PrivateSetterContractResolver() }; _context.Database.EnsureDeleted(); _context.Database.EnsureCreated(); //json was hard coded with dates //editing the raw json to update dates to current date range //not doing that in weatherevent because date is protected List <JObject> random = JsonConvert.DeserializeObject <List <JObject> >(jsonData, settings); var day = System.DateTime.Today.AddDays(-1); foreach (var weatherEvent in random) { day = day.AddDays(1); weatherEvent["date"] = day; } jsonData = JsonConvert.SerializeObject(random); //dates now updated List <WeatherEvent> events = JsonConvert.DeserializeObject <List <WeatherEvent> >(jsonData, settings); if (!_context.WeatherEvents.Any()) { _context.AddRange(events); _context.SaveChanges(); } }
CreateForecastAsync(WeatherForecast objWeatherForecast) { using (var context = new WeatherContext()) { context.WeatherForecast.Add(objWeatherForecast); context.SaveChanges(); } return(Task.FromResult(objWeatherForecast)); }
public HttpResponseMessage AddSensor(RainfallSensor rainfallSensor) { var rainfallSensorMapped = Mapper.Map <RainfallSensor, DataModels.RainfallSensor>(rainfallSensor); using (var db = new WeatherContext()) { db.RainfallSensors.Add(rainfallSensorMapped); db.SaveChanges(); } return(Request.CreateResponse(HttpStatusCode.Created, "Sensor was added.")); }
public TEntity Insert(TEntity entity) { using (var context = new WeatherContext()) { var dbSet = context.Set <TEntity>(); dbSet.Add(entity); context.SaveChanges(); } return(entity); }
public void Execute(IJobExecutionContext context) // starts once a day (at the beginning) and updates the list of Astro { Logger.Log.Debug("Starting of astro on schedule in " + DateTime.Now.ToString()); List <OneDayAstro> currentAstroData = null; currentAstroData = GetAstroFromApixu(); while (currentAstroData == null || counter == 0) { Thread.Sleep(1000 * 60 * 60 * repeatPeriodInHours); currentAstroData = GetAstroFromApixu(); counter--; } if (currentAstroData != null) { using (WeatherContext db = new WeatherContext()) { var deleteAstroData = from astro in db.AstroByDays where astro.Sunrise.Value < DateTime.Today && db.OneDayAnalyticForecast.Where(x => x.astro == astro).Count() == 0 select astro; foreach (var astro in deleteAstroData) { db.AstroByDays.Remove(astro); } foreach (var astro in currentAstroData) { if (db.AstroByDays.Where(x => x.Sunrise == astro.Sunrise).Count() == 0) { db.AstroByDays.Add(astro); } } try { db.SaveChanges(); } catch (Exception ex) { Logger.Log.Error("An error occurred while trying to save astro", ex); } AllDaysAstro = db.AstroByDays.ToList(); } } else { Logger.Log.Error(String.Format("An error occurred while trying to receive astro data on schedule")); } }
void DbUpdateActual(ForecastGeneralized generalized, string cityId, WeatherContext _context) { var objectFromDatabase = _context.Cities .Include(i => i.ActualTemparture) .First(i => i.Name == cityId); objectFromDatabase.ActualTemparture.Add(new ActualTemperature { ForecastTime = generalized.Forecasts.First().ForecastTime, Temperature = generalized.Forecasts.First().temperature }); _context.SaveChanges(); }
private WeatherContext CreateAndSeedContext() { // All contexts that share the same service provider will share the same InMemory database var serviceProvider = _services.BuildServiceProvider(); var serviceScope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope(); context = serviceScope.ServiceProvider.GetService <WeatherContext>(); context.WeatherEvents.AddRange(BuildWeatherEvents()); context.SaveChanges(); return(context); }
public void Post1() { using var db = new WeatherContext(); var rng = new Random(); var forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast1( DateTime.Now.AddDays(index), rng.Next(-20, 55), Summaries[rng.Next(Summaries.Length)])).ToArray(); db.Weathers1.AddRange(forecasts); db.SaveChanges(); }
private WeatherContext CreateAndSeedContext() { var optionsBuilder = new DbContextOptionsBuilder <WeatherContext>(); optionsBuilder.UseInMemoryDatabase(); var context = new WeatherContext(optionsBuilder.Options); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.WeatherEvents.AddRange(BuildWeatherEvents()); context.SaveChanges(); return(context); }
public void AddWeather(Weather weatherToAdd) { if (weatherToAdd != null) { _context.Weathers.Add(weatherToAdd); _context.SaveChanges(); log.InfoFormat("Inserted 1 row to database."); } else { log.InfoFormat("Row is empty, could not insert empty row to database."); } }