Beispiel #1
0
        /// <summary>
        /// Create Db context with connection string
        /// </summary>
        /// <param name="settings"></param>
        public DbContextFactory(IOptions <DbContextSettings> settings)
        {
            var options = new DbContextOptionsBuilder <WeatherDbContext>().UseSqlServer
                              (settings.Value.DbConnectionString).Options;

            DbContext = new WeatherDbContext(options);
        }
 public ActionResult <List <CityCode> > list()
 {
     using (WeatherDbContext context = new WeatherDbContext())
     {
         return(context.Set <CityCode>().ToList());
     }
 }
Beispiel #3
0
 public ServiceUser(UserManager <AppUser> userManager, SignInManager <AppUser> signInManager, IConfiguration config, WeatherDbContext context)
 {
     _userManager   = userManager;
     _singInManager = signInManager;
     _config        = config;
     _context       = context;
 }
Beispiel #4
0
        public DailyNormalService_GetDailyNormal()
        {
            WeatherDbContext context = null;             // mock this value
            IAsyncRepository <DailyNormal> repository = new DailyNormalRepository(context);

            this._dailyNormalService = new DailyNormalService(repository);
        }
        public async Task FetchAndSyncWeather_StoresNewDataInCache_WhenNoneExistsInCache()
        {
            // Expire cache data, by making it older than 4 hours
            var weatherDto = FakerT <WeatherDto> .Generate();

            weatherDto.LocaleId = 3;
            var mockWeatherApi = new Mock <IWeatherApi>();

            mockWeatherApi.Setup(api => api.GetWeatherForLocation(3)).Returns(Task.FromResult(TestDataGenerator.LocationWeather(3)));

            var option     = new DbContextOptionsBuilder <WeatherDbContext>().UseInMemoryDatabase("WeatherInMemoryDatabase").Options;
            var dbContext  = new WeatherDbContext(option);
            var repository = new WeatherRepository(dbContext);

            // Act
            var sut = new FetchManager.FetchManager(mockWeatherApi.Object, repository, new OpenWeatherSettings()
            {
                CacheExpiryMinutes = 180
            });
            var result = (await sut.FetchAndSyncWeatherForLocationAsync(3)).FirstOrDefault();

            // Assert
            Assert.Equal(3, result.LocaleId);
            var insertedObject = await repository.GetWeatherById(3);

            Assert.Equal(3, insertedObject.Count);
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                using (var scope = serviceScopeFactory.CreateScope())
                {
                    weatherContext = scope.ServiceProvider.GetService <WeatherDbContext>();

                    ICollection <Task <WeatherData> > cityTasks = new List <Task <WeatherData> >();
                    foreach (var city in cities)
                    {
                        cityTasks.Add(new WeatherClient().GetCity(city));
                    }

                    var taskResult = await Task.WhenAll(cityTasks.AsEnumerable());

                    foreach (var cityWeatherData in taskResult)
                    {
                        weatherContext.WeatherData.Add(cityWeatherData);
                    }

                    await weatherContext.SaveChangesAsync(cancellationToken);

                    _iLogger.LogInformation($"Downloaded weather data for cities ${string.Join(",", cities)} ");
                    await Task.Delay(delayMilliseconds, cancellationToken);
                }
            }
        }
 /// <summary>
 /// Get a  list of all sources of data
 /// </summary>
 /// <returns>A list of tuples with id of source first, and its name second</returns>
 public async Task <IReadOnlyCollection <DataSource> > GetAllAsync()
 {
     using (var db = new WeatherDbContext(_dbOptions))
     {
         return(await db.DataSources.ToListAsync());
     }
 }
Beispiel #8
0
        public async Task Test_GetWeatherForecastsAsync_Returns_Weather()
        {
            Db.Recreate();

            var now = DateTime.UtcNow;

            using (WeatherDbContext ctx = Db.GetAdminContext())
            {
                ctx.Set <WeatherForecastEntity>()
                .AddRange(new WeatherForecastEntity
                {
                    Id           = Guid.NewGuid(),
                    Date         = now,
                    Summary      = "sum-1",
                    TemperatureC = 1
                }, new WeatherForecastEntity
                {
                    Id           = Guid.NewGuid(),
                    Date         = now.AddDays(-1),
                    Summary      = "sum-2",
                    TemperatureC = 1
                });
                await ctx.SaveChangesAsync();
            }

            IWeatherForecastClient client = Integration.CreateClient();

            WeatherForecastGetModel[] models = await client.GetWeatherForecasts(CancellationToken.None);

            Assert.AreEqual(2, models.Length);
            Assert.AreEqual("sum-1", models[0].Summary);
            Assert.AreEqual("sum-2", models[1].Summary);
        }
 public ActionResult <CityCode> queryByAdcode(string adcode)
 {
     using (WeatherDbContext context = new WeatherDbContext())
     {
         CityCode city =
             (from c in context.CityCode
              where c.ad_code == adcode
              select c).FirstOrDefault();
         return(city);
     }
 }
 public ActionResult <CityCode> queryByName(string cityname)
 {
     using (WeatherDbContext context = new WeatherDbContext())
     {
         CityCode city =
             (from c in context.CityCode
              where c.city_CN == cityname
              select c).FirstOrDefault();
         return(city);
     }
 }
Beispiel #11
0
 public async Task <IReadOnlyCollection <AggregatedMeasurement> > GetAggregationsAsync(DateTime start, DateTime?end = null)
 {
     using (var db = new WeatherDbContext(_dbOptions))
     {
         return(await db.AggregatedMeasurements
                .Where(x =>
                       x.Day.Date >= start.Date &&
                       (end != null ? x.Day.Date < end.Value.Date : true)
                       )
                .ToListAsync());
     }
 }
Beispiel #12
0
        private void GivenADatabase(string context)
        {
            _contextOptions = MockDatabaseHelper.CreateNewContextOptions(context);
            _appContext     = new WeatherDbContext(_contextOptions);
            _settings       = Substitute.For <IOptions <DbContextSettings> >();

            _settings.Value.Returns(new DbContextSettings {
                DbConnectionString = "test"
            });
            _dbContextFactory = Substitute.For <IDbContextFactory>();
            _dbContextFactory.DbContext.Returns(_appContext);
            _subject = new CityRepository(_dbContextFactory, Substitute.For <ILogger>());
        }
        public async Task Test_GetForecastsAsync_Returns_Correct_Results()
        {
            Db.Recreate();

            var now = DateTime.UtcNow;

            using (WeatherDbContext ctx = Db.GetAdminContext())
            {
                ctx.Set <WeatherForecastEntity>()
                .AddRange(new WeatherForecastEntity
                {
                    Id           = Guid.NewGuid(),
                    Date         = now,
                    Summary      = "sum-1",
                    TemperatureC = 1
                }, new WeatherForecastEntity
                {
                    Id           = Guid.NewGuid(),
                    Date         = now.AddDays(-1),
                    Summary      = "sum-2",
                    TemperatureC = 1
                }, new WeatherForecastEntity
                {
                    Id           = Guid.NewGuid(),
                    Date         = now.AddDays(-30),
                    Summary      = "sum-3",
                    TemperatureC = 1
                }, new WeatherForecastEntity
                {
                    Id           = Guid.NewGuid(),
                    Date         = now.AddDays(-31),
                    Summary      = "sum-4",
                    TemperatureC = 1
                });
                await ctx.SaveChangesAsync();
            }

            using var mock = Mock.Auto();
            mock.Mock <IDateTimeService>().Setup(p => p.Now()).Returns(now);

            var service = mock.Create <WeatherForecastServiceImpl>();

            WeatherForecastEntity[] entities = await service.GetWeatherForecastsAsync(CancellationToken.None);

            Assert.AreEqual(3, entities.Length);
        }
Beispiel #14
0
        protected override void Seed(WeatherWidget.Models.WeatherDbContext context)
        {
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            // Create admin role if not already in database
            if (!roleManager.RoleExists("Administrator"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Administrator";
                roleManager.Create(role);


                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";

                string userPassword = "******";

                var chkUser = UserManager.Create(user, userPassword);

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Administrator");
                }
            }

            context.SaveChanges();

            // Seed database with current weather information
            // Get current data for each zip code from weather API and
            // save it to the DB
            List <string> zips = new List <string>()
            {
                "30909", "30907", "30809"
            };
            WeatherDbContext db = new WeatherDbContext();

            foreach (string zip in zips)
            {
                Weather weather = Weather.GetWeatherForZip(zip);
                db.Weather.Add(weather);
                db.SaveChanges();
            }
        }
Beispiel #15
0
        public async Task <ActionResult> Index(string zipCode)
        {
            Weather weather = null;

            if (ModelState.IsValid)
            {
                if (Weather.ValidateZip(zipCode))
                {
                    try
                    {
                        zipCode = zipCode.ToLower().Trim();
                        int zip;
                        Weather.GetWeatherForZip(zipCode);
                        // We know zip will parse because of ValidateZip()
                        int.TryParse(zipCode, out zip);

                        // Get weather data for the given zip code
                        using (WeatherDbContext db = new WeatherDbContext())
                        {
                            // Find weather with zip code using parameters
                            string       query        = "SELECT * FROM Weathers WHERE ZipCode = @zipCode";
                            SqlParameter zipParameter = new SqlParameter("@zipCode", zip);
                            weather = await db.Database.SqlQuery <Weather>(query, zipParameter).FirstOrDefaultAsync();
                        }
                        if (weather == null)
                        {
                            ViewBag.ZipNotFound = "Sorry, we do not have weather information for that zip code.";
                        }
                    }
                    catch (Exception ex)
                    {
                        // log exception
                    }
                }
                else
                {
                    ViewBag.ZipNotFound = "Sorry, we do not have weather information for that zip code.";
                }
            }
            else
            {
                ModelState.AddModelError("zipCode", "Invalid zip code.");
            }
            return(View(weather));
        }
		public async Task<bool> FetchTemperaturesAsync()
		{
			using (var db = new WeatherDbContext(_dbOptions))
			{
				try
				{
					var temperatures = new List<Measurement>();
                    temperatures.AddRange(await FetchWeatherForecastAsync());
                    var hueTemps = await FetchPhilipsHueSensorsAsync();

                    // Only update newer readings
					if (hueTemps != null)
					{
                        foreach(var hueTemp in hueTemps)
                        {
                            var lastMeasurement = db.Measurements.Where(y => hueTemp.SourceId == y.SourceId).OrderByDescending(y => y.Timestamp).Take(1).FirstOrDefault();
                            if(lastMeasurement == null || hueTemp.Timestamp > lastMeasurement.Timestamp)
                            {
                                temperatures.Add(hueTemp);
                            }
                        }
					}

					var piTemps = FetchRaspberryPi(); // Seems not working in Async mode
					if (piTemps != null)
					{
						temperatures.AddRange(piTemps);
					}

					_logger.LogInformation($"Amount of temperatures: {temperatures.Count()}");
					if (temperatures.Count > 0)
					{
						db.Measurements.AddRange(temperatures);
						return db.SaveChanges() > 0;
					}
				} 
				catch (Exception e)
				{
					_logger.LogError(e, $"Exception occured {e.Message}");
				}
				return false;
			}
        }
        public async Task <WeatherForecastEntity[]> GetWeatherForecastsAsync(CancellationToken ct)
        {
            _logger.LogDebug("Retrieving weather forecast items from the database");

            using var scope = new TransactionScope(TransactionScopeOption.Required,
                                                   new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },
                                                   TransactionScopeAsyncFlowOption.Enabled);

            using WeatherDbContext ctx = _dbContextFactory.GetWeatherDbContext();

            WeatherForecastEntity[] entities = await ctx.Set <WeatherForecastEntity>()
                                               .Where(p => p.Date >= _dateTimeService.Now().AddDays(-30))
                                               .OrderByDescending(p => p.Date)
                                               .ToArrayAsync(ct);

            scope.Complete();

            _logger.LogDebug("Retrieved the items: {0}", entities.Length);

            return(entities);
        }
        public void Test_Mapping_Functional()
        {
            Db.Recreate();

            using WeatherDbContext ctx1 = Db.GetAppContext();
            var entity = new WeatherForecastEntity
            {
                Id           = Guid.NewGuid(),
                Date         = DateTime.UtcNow,
                Summary      = "some summary",
                TemperatureC = 10
            };

            ctx1.Set <WeatherForecastEntity>().Add(entity);
            ctx1.SaveChanges();

            using WeatherDbContext ctx2 = Db.GetAppContext();
            WeatherForecastEntity saved = ctx2.Set <WeatherForecastEntity>().Find(entity.Id);

            Assert.NotNull(saved);
            Assert.AreEqual(entity.Date, saved.Date);
            Assert.AreEqual(entity.Summary, saved.Summary);
            Assert.AreEqual(entity.TemperatureC, saved.TemperatureC);
        }
Beispiel #19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptionsMonitor <RabbitConfiguration> rabbitConfigurationOptions, WeatherDbContext dbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            dbContext.Database.Migrate();

            app.UseSwagger();
            app.UseSwaggerUi3();

            app.UseMvc();
        }
 public TemperatureController(WeatherDbContext weatherDbContext, ILogger <TemperatureController> logger, SignInManager <IdentityUser> signInManager)
 {
     _weatherDbContext = weatherDbContext;
     _logger           = logger;
 }
 public void Run()
 {
     using WeatherDbContext ctx = _dbContextFactory.GetWeatherDbContext();
     ctx.Database.Migrate();
 }
Beispiel #22
0
        public async Task <ReadoutResponse> GetReadoutsAsync(DateTime?customSince = null)
        {
            var since = ChartConfiguration.RealTime.Labels.First().Start;

            if (customSince != null)
            {
                since = customSince.Value;
            }
            using (var db = new WeatherDbContext(_dbOptions))
            {
                var sources = await db.DataSources.ToListAsync();

                var measurements = await db.Measurements.Where(x => x.Timestamp > since).ToListAsync();

                var readouts = new List <IReadOut>();
                var labels   = ChartConfiguration.RealTime.Labels.ToList();
                if (customSince != null)
                {
                    //  we will only fetch the data for the last "frame", other data already exists in the frontend
                    labels = labels.Where(x => customSince.Value > x.Start).TakeLast(1).ToList();
                }

                // Have some fallback values, so we can draw continuous chart lines
                var lastNonNullTemperatures = new Dictionary <int, int?>();
                foreach (var source in sources)
                {
                    var lastMeasuredTemperature = await db.Measurements
                                                  .Where(x => x.SourceId == source.Id)
                                                  .OrderByDescending(x => x.Timestamp)
                                                  .Take(1)
                                                  .FirstOrDefaultAsync();

                    lastNonNullTemperatures.Add(source.Id, lastMeasuredTemperature?.Temperature);
                }

                foreach (var chartLabel in labels)
                {
                    var medianTemperatures = new Dictionary <int, IEnumerable <double> >();
                    foreach (var source in sources)
                    {
                        var medianTemperature = measurements
                                                .Where(x =>
                                                       x.SourceId == source.Id &&
                                                       x.Timestamp >= chartLabel.Start &&
                                                       x.Timestamp < chartLabel.Start.AddMilliseconds(chartLabel.Span.TotalMilliseconds)
                                                       )
                                                .Select(x => (double)x.Temperature);

                        medianTemperatures.Add(source.Id, medianTemperature);
                    }

                    if (medianTemperatures.Where(x => x.Value.Count() == 0).Count() == sources.Count())
                    {
                        // If all measureents for all sensors were empty, skip this frame.
                        continue;
                    }

                    foreach (var medianTemperature in medianTemperatures)
                    {
                        bool stale = true;
                        if (medianTemperature.Value != null && medianTemperature.Value.Count() > 0)
                        {
                            lastNonNullTemperatures[medianTemperature.Key] = (int?)Math.Round(medianTemperature.Value.Median() * 100) / 100;
                            stale = false;
                        }

                        readouts.Add(new ReadOut
                        {
                            SourceId    = medianTemperature.Key,
                            Temperature = lastNonNullTemperatures[medianTemperature.Key],
                            Stale       = stale
                        });
                    }
                }

                return(new ReadoutResponse {
                    Readouts = readouts,
                    Timestamp = DateTime.Now
                });
            }
        }
 public WeatherService(WeatherDbContext weatherDb, ILogger <WeatherService> logger)
 {
     this.logger    = logger;
     this.weatherDb = weatherDb;
 }
 public AccountController(WeatherDbContext dbContext)
 {
     this.dbContext = dbContext;
 }
 public LabelRepository(WeatherDbContext dbContext)
 {
     _dbContext = dbContext;
 }
Beispiel #26
0
        public async Task Execute(IJobExecutionContext context)
        {
            if (Convert.ToBoolean(WebConfigurationManager.AppSettings["ESPScheduler"]))
            {
                try
                {
                    using (var weatherDbcontext = new WeatherDbContext())
                    {
                        Logging logging = new Logging();

                        logging.WriteLog(new string[] { "start insert job" });

                        ESPData espdata = new ESPData();
                        string  URL     = WebConfigurationManager.AppSettings["ESP8266url"];
                        espdata = await espdata.GetAsync(new Uri(URL));

                        weatherDbcontext.Weather.Add(new Weather
                        {
                            DATETIME = DateTime.Now,
                            VAL1     = espdata.variables.T_OUT,
                            VAL2     = espdata.variables.T_IN,
                            HUMIDITY = espdata.variables.Humidity
                        });

                        try
                        {
                            await weatherDbcontext.SaveChangesAsync();

                            logging.WriteLog(new string[]
                            {
                                "Successfull insert!",
                                "insert at " + DateTime.Now.ToString(),
                                "T_OUT = " + espdata.variables.T_OUT,
                                "T_IN = " + espdata.variables.T_IN,
                                "HUMIDITY = " + espdata.variables.Humidity
                            });
                        }
                        catch (Exception ex)
                        {
                            logging.WriteLog(new string[]
                            {
                                "error while SaveChangesAsync()",
                                "ESPDataSender.cs " + ex.Message + " ### " + ex.InnerException
                            });
                            await Execute(context);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging logging = new Logging();

                    logging.WriteLog(new string[]
                    {
                        "error while inserting!",
                        "ESPDataSender.cs " + ex.Message + " ### " + ex.InnerException
                    });

                    await Execute(context);
                }
            }
        }
Beispiel #27
0
 public CitiesController(WeatherDbContext weatherDbContext, ILogger <CitiesController> logger)
 {
     _weatherDbContext = weatherDbContext;
     _logger           = logger;
 }
Beispiel #28
0
 public RecordRepository(WeatherDbContext context)
 {
     _context = context;
 }
 public WeatherController(WeatherDbContext weatherDbContext)
 {
     _weatherDbContext = weatherDbContext;
 }
Beispiel #30
0
 public EnviornmentsController(WeatherDbContext context)
 {
     _context = context;
 }