Example #1
0
 public void WriteWeatherHistory(WeatherDataModel now, WeatherDataModel daily)
 {
     try
     {
         WriteLock.EnterWriteLock();
         FileStream fs = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WeatherHistory.txt"), FileMode.Create);
         fs.Close();
         StreamWriter sw       = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WeatherHistory.txt"));
         string       nowstr   = JsonConvert.SerializeObject(now);
         string       dailystr = JsonConvert.SerializeObject(daily);
         //开始写入
         sw.Write(nowstr + "##" + dailystr);
         //清空缓冲区
         sw.Flush();
         //关闭流
         sw.Close();
     }
     catch (System.Exception e)
     {
         LogWriter.Instance.Error(e);
     }
     finally
     {
         WriteLock.ExitWriteLock();
     }
 }
        public static async Task SendMessageAsync(DeviceClient deviceClient)
        {
            try
            {
                var response = await _client.GetAsync(_connweather);

                if (response.IsSuccessStatusCode)
                {
                    WeatherDataModel weather = JsonConvert.DeserializeObject <WeatherDataModel>(await response.Content.ReadAsStringAsync());
                    var data = new Current
                    {
                        temperature = weather.current.temperature,
                        humidity    = weather.current.humidity
                    };

                    var json    = JsonConvert.SerializeObject(data);
                    var payload = new MAD.Client.Message(Encoding.UTF8.GetBytes(json));
                    await deviceClient.SendEventAsync(payload);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #3
0
        public async Task <WeatherDataValuesListModel> GetData()
        {
            using (var client = new HttpClient())
            {
                var    url = string.Format("http://twister.utm.edu/?command=DataQuery&uri=twister%3AUTM_1.Table1&format=json&mode=since-record&p1=624768&p2=2017-09-13T22:00:00&headsig=30291&nextpoll=10000&order=collected&_=1505340243729");
                string resp;
                try
                {
                    resp = await client.GetStringAsync(url);

                    resp = resp.Replace("\\n", "");
                }
                catch (Exception e)
                {
                    throw e;
                }
                WeatherDataModel root = new WeatherDataModel();
                try
                {
                    root = JsonConvert.DeserializeObject <WeatherDataModel>(resp);
                }
                catch (Exception e)
                {
                    throw e;
                }

                WeatherDataValuesListModel weatherDataValuesListModel = setJSONObject(root);

                return(weatherDataValuesListModel);
            }
        }
Example #4
0
        /// <summary>
        /// 调用心知天气
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public WeatherDataModel WeatherData(string url)
        {
            WeatherDataModel model = new WeatherDataModel();

            try
            {
                HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
                req.ContentType = "multipart/form-data";
                req.Accept      = "*/*";
                req.UserAgent   = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
                req.Timeout     = 30000; //30秒连接不成功就中断
                req.Method      = "GET";

                HttpWebResponse response = req.GetResponse() as HttpWebResponse;
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string result = sr.ReadToEnd();
                    model = JsonConvert.DeserializeObject <WeatherDataModel>(result);
                }
            }
            catch (WebException ex)
            {
                model = null;
            }
            return(model);
        }
        private void ConvertKelvinToCelcil(WeatherDataModel weatherData)
        {
            if (weatherData.MainWeather == null)
            {
                throw new ApplicationException("MainWeather is null");
            }

            weatherData.MainWeather.MinimalTemperature += ValueCelciusAtZeroKelvin;
            weatherData.MainWeather.MaximalTemperature += ValueCelciusAtZeroKelvin;
            weatherData.MainWeather.Temperature        += ValueCelciusAtZeroKelvin;
        }
        private void SetIconURL(WeatherDataModel weatherData)
        {
            if (weatherData.WeatherElement == null)
            {
                throw new ApplicationException("WeatherElement is null");
            }

            weatherData.WeatherElement.ForEach(x =>
            {
                x.Icon = $"https://openweathermap.org/img/wn/{x.Icon}@2x.png";
            });
        }
Example #7
0
        public JsonResult GetDataPoints(string city, string scaleUnit)
        {
            var apiHelper      = new ApiHelper(city, scaleUnit);
            var rootObjectItem = apiHelper.GetWeatherData();

            var weatherModel      = new WeatherDataModel();
            var weatherModelList  = weatherModel.GetWeaterForecastList(rootObjectItem);
            GraphicDataPoints gdp = new GraphicDataPoints();
            var result            = gdp.GetDataPointObject(weatherModelList);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Example #8
0
        public ActionResult GetGraphic(string city, string scaleUnit)
        {
            var apiHelper      = new ApiHelper(city, scaleUnit);
            var rootObjectItem = apiHelper.GetWeatherData();

            var weatherModel     = new WeatherDataModel();
            var weatherModelList = weatherModel.GetWeaterForecastList(rootObjectItem);

            ViewBag.WeatherList = weatherModelList;

            return(PartialView());
        }
Example #9
0
 /// <summary>
 /// 判定是否第一次启动或修改了城市
 /// 是:调用
 /// 否:直接取属性以减少调用开支
 /// </summary>
 /// <param name="url"></param>
 /// <param name="city"></param>
 /// <returns></returns>
 public WeatherDataModel GetWeatherDataDaily(string url, string city)
 {
     if (WeatherDaily == null)//是否第一次启动
     {
         WeatherDaily = WeatherData(url);
     }
     else if (city != City)//是否修改了城市
     {
         WeatherDaily = WeatherData(url);
     }
     City = city;
     return(WeatherDaily);
 }
        private void ConvertTimeToString(WeatherDataModel weatherData)
        {
            if (weatherData.MainWeather == null)
            {
                throw new ApplicationException("Sys is null");
            }

            weatherData.Sys.Sunrise += weatherData.Timezone;
            weatherData.Sys.Sunset  += weatherData.Timezone;

            weatherData.Sys.SunriseText = ConvertTime(weatherData.Sys.Sunrise);
            weatherData.Sys.SunsetText  = ConvertTime(weatherData.Sys.Sunset);
        }
Example #11
0
        public WeatherDataValuesListModel setJSONObject(WeatherDataModel weatherDataModel)
        {
            WeatherDataValuesListModel weatherDataValuesListModel;

            weatherDataValuesListModel = new WeatherDataValuesListModel();


            foreach (DataListModel model in weatherDataModel.data)
            {
                WeatherDataValuesModel weatherDataValuesModel = new WeatherDataValuesModel();
                weatherDataValuesModel.Time_Stamp    = model.time;
                weatherDataValuesModel.Record        = model.no;
                weatherDataValuesModel.T1_Avg        = model.vals[0];
                weatherDataValuesModel.T2_Avg        = model.vals[1];
                weatherDataValuesModel.T1_Asp_Avg    = model.vals[2];
                weatherDataValuesModel.RH1           = model.vals[3];
                weatherDataValuesModel.RH2           = model.vals[4];
                weatherDataValuesModel.U1_Avg        = model.vals[5];
                weatherDataValuesModel.U2_Avg        = model.vals[6];
                weatherDataValuesModel.UDir1         = model.vals[7];
                weatherDataValuesModel.UDir2         = model.vals[8];
                weatherDataValuesModel.U1_Max        = model.vals[9];
                weatherDataValuesModel.U2_Max        = model.vals[10];
                weatherDataValuesModel.P_mb_Avg      = model.vals[11];
                weatherDataValuesModel.PPN_mm_Tot    = model.vals[12];
                weatherDataValuesModel.TC1_Avg       = model.vals[13];
                weatherDataValuesModel.SoilW1_Avg    = model.vals[14];
                weatherDataValuesModel.SoilW2_Avg    = model.vals[15];
                weatherDataValuesModel.SoilW3_Avg    = model.vals[16];
                weatherDataValuesModel.SW_UP_Avg     = model.vals[17];
                weatherDataValuesModel.SW_Down_Avg   = model.vals[18];
                weatherDataValuesModel.LW_UP_Avg     = model.vals[19];
                weatherDataValuesModel.LW_Down_Avg   = model.vals[20];
                weatherDataValuesModel.CNR1TC_Avg    = model.vals[21];
                weatherDataValuesModel.CNR1TK_Avg    = model.vals[22];
                weatherDataValuesModel.NetSW_Avg     = model.vals[23];
                weatherDataValuesModel.NetLW_Avg     = model.vals[24];
                weatherDataValuesModel.Albedo_Avg    = model.vals[25];
                weatherDataValuesModel.UpTot_Avg     = model.vals[26];
                weatherDataValuesModel.DnTot_Avg     = model.vals[27];
                weatherDataValuesModel.NetTot_Avg    = model.vals[28];
                weatherDataValuesModel.CG3UpCo_Avg   = model.vals[29];
                weatherDataValuesModel.CG3DnCo_Avg   = model.vals[30];
                weatherDataValuesModel.Batt_Volt_Avg = model.vals[31];
                weatherDataValuesModel.T_Panel_Avg   = model.vals[32];

                weatherDataValuesListModel.weatherDataValuesModel.Add(weatherDataValuesModel);
            }
            return(weatherDataValuesListModel);
        }
Example #12
0
 private object BuildModel(WeatherDataModel data)
 {
     return(data == null
                         ? null
                         : new
     {
         when = data.DateTime.ToShortTimeString(),
         t = WeatherUtils.FormatTemperature(data.Temperature),
         p = data.Pressure,
         h = data.Humidity,
         icon = WeatherUtils.GetIconClass(data.Code),
         description = data.Description
     });
 }
Example #13
0
        public void GetWeatherDataByCityAsyncWithValidDataSuccessResult()
        {
            IOptions <MyConf> someOptions = Options.Create(new MyConf()
            {
                Key = "123"
            });

            var weatherDataProvider = new Mock <IWeatherDataProvider>();
            var successResult       = new WeatherDataModel()
            {
                Name = "successResult",
                Wind = new Wind()
                {
                    Speed = 2.5
                },
                MainWeather = new MainWeather()
                {
                    MaximalTemperature = 1.0,
                    MinimalTemperature = 1.0,
                    Temperature        = 1.0,
                    Humidity           = 20,
                    Pressure           = 10.5
                },
                WeatherElement = new List <WeatherElement>()
                {
                    new WeatherElement()
                    {
                        Icon = "12d"
                    }
                },
                Sys = new Sys()
                {
                    Sunrise = 1562212165,
                    Sunset  = 1562271597,
                    Country = "UA"
                },
                Timezone = 3600,
            };

            weatherDataProvider
            .Setup(x => x.GetWeatherDataAsync("Kharkiv", "123"))
            .ReturnsAsync(successResult);

            var service = new WeatherService(weatherDataProvider.Object, someOptions);

            var result = service.GetWeatherDataByCityAsync("Kharkiv").Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(result.Name, "successResult");
        }
Example #14
0
 public WeatherDataModel[] ReadWeatherHistory()
 {
     try
     {
         StreamReader     sw        = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WeatherHistory.txt"));
         string           tempstr   = sw.ReadToEnd();
         string[]         reminders = Regex.Split(tempstr, "##", RegexOptions.IgnoreCase);
         WeatherDataModel now       = JsonConvert.DeserializeObject <WeatherDataModel>(reminders[0]);
         WeatherDataModel daily     = JsonConvert.DeserializeObject <WeatherDataModel>(reminders[1]);
         sw.Close();
         return(new WeatherDataModel[] { now, daily });
     }
     catch (System.Exception e)
     {
         return(null);
     }
 }
        static void Main(string[] args)
        {
            var model = new WeatherDataModel();

            model.Subscribe(new DefaultDisplay());
            model.Subscribe(new StatisticDisplay());

            var data = new WeatherData();

            for (int i = 0; i < 10; i++)
            {
                model.Temperature        = data.GetTemperature();
                model.Humidity           = data.GetHumidity();
                model.BarometricPressure = data.GetBarometricPressure();
            }

            Console.ReadLine();
        }
Example #16
0
        public async Task <ActionResult> GetWeatherReport(string cityName)
        {
            WeatherDataModel weatherData   = new WeatherDataModel();
            bool             dataRetrieved = false;

            weatherData.ErrorMessage = "Please specify city name to get the weather forecast.";
            // check if cityName is not empty
            if (!string.IsNullOrWhiteSpace(cityName))
            {
                try
                {
                    string result;
                    // get json string result from the service
                    result = await _weatherService.GetWeatherByCity(cityName);

                    if (!string.IsNullOrWhiteSpace(result))
                    {
                        // map json data to our model class
                        // this will be returned as json object to front end
                        weatherData = JsonConvert.DeserializeObject <WeatherDataModel>(result);
                        weatherData.ErrorMessage = "Please specify a valid city name to get the weather forecast. Or the service is currently unavailable.";
                        // check if the correct city weather is returned
                        if (weatherData.City != null)
                        {
                            if (weatherData.City.Name.Equals(cityName, OrdinalIgnoreCase))
                            {
                                weatherData.ErrorMessage = "";
                                dataRetrieved            = true;
                            }
                        }
                    }
                    if (!dataRetrieved && string.IsNullOrWhiteSpace(weatherData.ErrorMessage))
                    {
                        weatherData.ErrorMessage = "There was some technical problem getting the weather report. Please try again after sometime.";
                    }
                }
                catch (Exception ex)
                {
                    weatherData.ErrorMessage = $"There was some problem getting the weather report: {ex.Message}";
                }
            }

            return(Json(HelperClasses.Json(Mapper.Map <WeatherDataDTO>(weatherData)), JsonRequestBehavior.AllowGet));
        }
Example #17
0
        public void GetWeatherDataByCityAsyncWithInvalidTempError()
        {
            IOptions <MyConf> someOptions = Options.Create(new MyConf()
            {
                Key = "123"
            });

            var weatherDataProvider = new Mock <IWeatherDataProvider>();
            var successResult       = new WeatherDataModel()
            {
                Name = "successResult",
                Wind = new Wind()
                {
                    Speed = 2.5
                },
                MainWeather    = null,
                WeatherElement = new List <WeatherElement>()
                {
                    new WeatherElement()
                    {
                        Icon = "12d"
                    }
                },
                Sys = new Sys()
                {
                    Sunrise = 1562212165,
                    Sunset  = 1562271597,
                    Country = "UA"
                },
                Timezone = 3600,
            };

            weatherDataProvider
            .Setup(x => x.GetWeatherDataAsync("Kharkiv", "123"))
            .ReturnsAsync(successResult);

            var service = new WeatherService(weatherDataProvider.Object, someOptions);

            var result = service.GetWeatherDataByCityAsync("Kharkiv").Result;

            Assert.IsNull(result);
        }
Example #18
0
 public MainWeatherViewModel(WeatherDataModel nowModel, WeatherDataModel dailyModel, Degree degreeFormat)
 {
     Task.Factory.StartNew(() =>
     {
         DispatcherHelper.CheckBeginInvokeOnUI(
             () =>
         {
             DailyModel   = dailyModel;
             NowModel     = nowModel;
             DegreeFormat = degreeFormat;
             FetchData();
         });
     }).ContinueWith(result =>
     {
         if (result.IsFaulted)
         {
             //result.Exception.GetBaseException()
         }
     });
 }
Example #19
0
        public void CalculateAndAddToList(IQueryable <WeatherData> listToCalc, List <WeatherDataModel> listToAdd, string location, DateTime date)
        {
            double moldRisk, averageTemperature = 0, averageHumidity = 0;

            foreach (var tempreading in listToCalc)
            {
                averageTemperature += tempreading.Temperature;
                averageHumidity    += tempreading.Humidity;
            }
            averageTemperature /= listToCalc.Count();
            averageHumidity    /= listToCalc.Count();

            if ((((averageHumidity - 78) * (averageTemperature / 15)) / 0.22) < 0)
            {
                moldRisk = 0;
            }
            else if ((((averageHumidity - 78) * (averageTemperature / 15)) / 0.22) > 100)
            {
                moldRisk = 100;
            }
            else
            {
                moldRisk = ((averageHumidity - 78) * (averageTemperature / 15)) / 0.22;
            }

            WeatherDataModel wd = new WeatherDataModel()
            {
                AverageHumidity    = (int)averageHumidity,
                AverageTemperature = Math.Round(averageTemperature, 2),
                Date     = date,
                Location = location,
                MoldRisk = (int)moldRisk
            };

            listToAdd.Add(wd);
        }
        public async Task <IEnumerable <WeatherDataModel> > GetWeatherData(DateTime StartDate, DateTime EndDate, double DesiredTemperature, bool OnlyUnitedStates)
        {
            List <String> locationNames = new List <String>();

            locationNames.Add("New York City, NY US");
            locationNames.Add("Albequerque, NM US");
            locationNames.Add("Tucson, AZ US");
            locationNames.Add("Tallahassee, FL US");
            locationNames.Add("Tampa, FL US");
            locationNames.Add("Buffalo, NY US");
            locationNames.Add("Milwaukee, WI US");
            locationNames.Add("Los Angeles, CA US");
            locationNames.Add("Austin, TX US");
            locationNames.Add("Dallas, TX US");
            locationNames.Add("Atlanta, GA US");
            locationNames.Add("Savannah, GA US");
            locationNames.Add("Montgomery, AL US");
            locationNames.Add("Portland, OR US");
            locationNames.Add("Seattle, WA US");
            locationNames.Add("Pittsburgh, PA US");
            locationNames.Add("Asheville, NC US");
            locationNames.Add("Raleigh, NC US");
            locationNames.Add("Knoxville, TN US");
            locationNames.Add("Little Rock, AR US");
            locationNames.Add("Reno, NV US");
            locationNames.Add("Las Vegas, NV US");
            locationNames.Add("Richmond, VA US");

            if (!OnlyUnitedStates)
            {
                locationNames.Add("London, UK");
                locationNames.Add("Brighton, UK");
                locationNames.Add("Hamburg, DE");
                locationNames.Add("Berlin, DE");
                locationNames.Add("Amsterdam, NL");
                locationNames.Add("Prague, CZ");
                locationNames.Add("Cape Town, SA");
                locationNames.Add("Sydney, AU");
                locationNames.Add("Melbourne, AU");
                locationNames.Add("Ontario, CA");
                locationNames.Add("Toronto, CA");
                locationNames.Add("Mexico City, MX");
                locationNames.Add("Madrid, ES");
                locationNames.Add("Paris, FR");
                locationNames.Add("Barcelona, ES");
                locationNames.Add("Beijing, CN");
                locationNames.Add("Seoul, KR");
                locationNames.Add("Moscow, RU");
            }

            List <WeatherDataModel> dataModels = new List <WeatherDataModel>();
            Random r = new Random();

            for (int i = 0; i < 6; i++)
            {
                WeatherDataModel model = new WeatherDataModel();
                model.Location  = locationNames.ElementAt(r.Next(locationNames.Count));
                model.MaxTemp   = 55.0 + (r.NextDouble() * 35.0);
                model.MinTemp   = 0.0 + (r.NextDouble() * 35.0);
                model.AvgTemp   = Math.Abs(model.MaxTemp - model.MinTemp) / 2.0;
                model.Latitude  = 38.9;
                model.Longitude = -77.04;
                dataModels.Add(model);
            }

            return(dataModels);
        }
Example #21
0
        public async Task <IEnumerable <WeatherDataModel> > GetWeatherData(DateTime StartDate, DateTime EndDate, double DesiredTemperature, bool OnlyUnitedStates)
        {
            List <WeatherDataModel> dataModels = new List <WeatherDataModel>();

            string       firstApiCallParameters  = "data?datasetid=GSOM&datatypeid=TMIN&datatypeid=TMAX&startdate=&enddate=2012-09-10&units=standard&locationid=FIPS:US";
            const string secondApiCallParameters = "stations/";
            string       authToken = config["apiAuthKey"];

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(URL);
                client.DefaultRequestHeaders.Add("token", authToken);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                MetaData         metaData;
                StationInfoModel stationInfoModel;

                double closestAverageTemperatureToGoal = 9999.0;
                double currentMaxTemperature           = 0.0;
                double currentAverageTemperature       = 0.0;

                HttpResponseMessage response = await client.GetAsync(firstApiCallParameters);

                if (response.IsSuccessStatusCode)
                {
                    metaData = await response.Content.ReadAsAsync <MetaData>();

                    foreach (TemperatureValueInfoModel info in metaData.Results)
                    {
                        response = await client.GetAsync(secondApiCallParameters + info.Station);

                        if (response.IsSuccessStatusCode)
                        {
                            stationInfoModel = await response.Content.ReadAsAsync <StationInfoModel>();

                            if (stationInfoModel.ID.Equals(info.Station))
                            {
                                if (info.Name.Contains("TMAX"))
                                {
                                    currentMaxTemperature = info.Value;
                                }
                                else
                                {
                                    currentAverageTemperature = (info.Value + currentMaxTemperature) / 2;

                                    if (Math.Abs(DesiredTemperature - currentAverageTemperature) < closestAverageTemperatureToGoal)
                                    {
                                        closestAverageTemperatureToGoal = Math.Abs(DesiredTemperature - currentAverageTemperature);
                                        WeatherDataModel model = new WeatherDataModel();
                                        model.AvgTemp   = currentAverageTemperature;
                                        model.MaxTemp   = currentMaxTemperature;
                                        model.MinTemp   = info.Value;
                                        model.Location  = stationInfoModel.Name;
                                        model.Latitude  = stationInfoModel.Latitude;
                                        model.Longitude = stationInfoModel.Longitude;
                                        dataModels.Add(model);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(dataModels);
        }
Example #22
0
        // GET: Weather
        public async Task <ActionResult> Index(WeatherDataModel model)
        {
            if (model.Cities == null)
            {
                if (Session["cities"] == null)
                {
                    model.Cities = await _dataService.GetCities();

                    Session.Add("cities", model.Cities);
                }
                else
                {
                    model.Cities = (IEnumerable <ICity>)Session["cities"];
                }
            }

            if (Session["unit"] != null)
            {
                var sessionUnit = (Measurements)Session["unit"];
                if (Request.HttpMethod == "POST")
                {
                    Session["unit"] = model.SelectedUnit;
                }
                else
                {
                    model.SelectedUnit = sessionUnit;
                }
            }
            else
            {
                if (model.SelectedUnit != Measurements.Default)
                {
                    Session.Add("unit", model.SelectedUnit);
                }
            }

            Tuple <IEnumerable <IWeatherData>, int> tuple;
            IEnumerable <IWeatherData> weatherData;

            if (model.SelectedCities?.Any() ?? false)
            {
                model.SelectedCities = model.SelectedCities.Where(i => i > 0).ToArray();
            }
            if (model.ShowLatestData)
            {
                tuple =
                    await
                    _dataService.GetLatestWeatherData(model.SelectedCities, model.SunsetFrom, model.SunsetTo,
                                                      model.SunriseFrom, model.SunriseTo, model.From, model.To, model.MinTemperatureInK(),
                                                      model.MaxTemperatureInK());
            }
            else
            {
                tuple =
                    await
                    _dataService.SearchWeatherData(model.SelectedCities, model.SunsetFrom, model.SunsetTo,
                                                   model.SunriseFrom, model.SunriseTo, model.From, model.To, model.MinTemperatureInK(),
                                                   model.MaxTemperatureInK());
            }
            weatherData        = tuple.Item1;
            model.TotalResults = tuple.Item2;

            model.Results = weatherData.ToList();

            if (model.SelectedUnit != Measurements.Default)
            {
                foreach (var data in model.Results)
                {
                    switch (model.SelectedUnit)
                    {
                    case Measurements.Metric:
                        data.Temperature    = data.Temperature.HasValue ? Converter.FromKelvinToCelsius(data.Temperature.Value) : data.Temperature;
                        data.MinTemperature = data.MinTemperature.HasValue ? Converter.FromKelvinToCelsius(data.MinTemperature.Value) : data.MinTemperature;
                        data.MaxTemperature = data.MaxTemperature.HasValue ? Converter.FromKelvinToCelsius(data.MaxTemperature.Value) : data.MaxTemperature;
                        break;

                    case Measurements.Imperial:
                        data.Temperature    = data.Temperature.HasValue ? Converter.FromKelvinToFahrenheit(data.Temperature.Value) : data.Temperature;
                        data.MinTemperature = data.MinTemperature.HasValue ? Converter.FromKelvinToFahrenheit(data.MinTemperature.Value) : data.MinTemperature;
                        data.MaxTemperature = data.MaxTemperature.HasValue ? Converter.FromKelvinToFahrenheit(data.MaxTemperature.Value) : data.MaxTemperature;
                        data.WindSpeed      = data.WindSpeed.HasValue ? Converter.MetersPerSecondToMilesPerHour(data.WindSpeed.Value) : data.WindSpeed;
                        break;
                    }
                }
            }


            return(View(model));
        }
Example #23
0
 public void SetDataModel(IDataModelBase dataModel, int index)
 {
     if (dataModel != null)
     {
         if (dataModel.GetType() == typeof(InformationDataModel))
         {
             InformationDataModel tempDataModel = (InformationDataModel)dataModel;
             _fiefService.InformationList[index] = (InformationDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(ArmyDataModel))
         {
             ArmyDataModel tempDataModel = (ArmyDataModel)dataModel;
             _fiefService.ArmyList[index] = (ArmyDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(EmployeesDataModel))
         {
             EmployeesDataModel tempDataModel = (EmployeesDataModel)dataModel;
             _fiefService.EmployeesList[index] = (EmployeesDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(ManorDataModel))
         {
             ManorDataModel tempDataModel = (ManorDataModel)dataModel;
             _fiefService.ManorList[index] = (ManorDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(BoatbuildingDataModel))
         {
             BoatbuildingDataModel tempDataModel = (BoatbuildingDataModel)dataModel;
             _fiefService.BoatbuildingList[index] = (BoatbuildingDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(ExpensesDataModel))
         {
             ExpensesDataModel tempDataModel = (ExpensesDataModel)dataModel;
             _fiefService.ExpensesList[index] = (ExpensesDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(StewardsDataModel))
         {
             StewardsDataModel tempDataModel = (StewardsDataModel)dataModel;
             for (int x = 0; x < _fiefService.StewardsList.Count; x++)
             {
                 _fiefService.StewardsList[x] = (StewardsDataModel)tempDataModel.Clone();
             }
         }
         else if (dataModel.GetType() == typeof(SubsidiaryDataModel))
         {
             SubsidiaryDataModel tempDataModel = (SubsidiaryDataModel)dataModel;
             _fiefService.SubsidiaryList[index] = (SubsidiaryDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(IncomeDataModel))
         {
             IncomeDataModel tempDataModel = (IncomeDataModel)dataModel;
             _fiefService.IncomeList[index] = (IncomeDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(BuildingsDataModel))
         {
             BuildingsDataModel tempDataModel = (BuildingsDataModel)dataModel;
             _fiefService.BuildingsList[index] = (BuildingsDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(WeatherDataModel))
         {
             WeatherDataModel tempDataModel = (WeatherDataModel)dataModel;
             _fiefService.WeatherList[index] = (WeatherDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(MinesDataModel))
         {
             MinesDataModel tempDataModel = (MinesDataModel)dataModel;
             _fiefService.MinesList[index] = (MinesDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(PortDataModel))
         {
             PortDataModel tempDataModel = (PortDataModel)dataModel;
             _fiefService.PortsList[index] = (PortDataModel)tempDataModel.Clone();
         }
         else if (dataModel.GetType() == typeof(TradeDataModel))
         {
             TradeDataModel tempDataModel = (TradeDataModel)dataModel;
             _fiefService.TradeList[index] = (TradeDataModel)tempDataModel.Clone();
         }
         else
         {
             Console.WriteLine("ERROR!");
         }
     }
 }
Example #24
0
 public void AddWeatherData(WeatherDataModel weatherData)
 {
     weatherData.CreatedAt = DateTime.UtcNow;
     this.db.Insert(weatherData);
 }
Example #25
0
        public static WeatherDataModel GetWeatherData(string locationName, LanguageDataModel currentLang, string unit)
        {
            if (locationName != string.Empty)
            {
                // MessageBox.Show(unit);
                string unitSystem;
                if (unit.Equals("Celsius"))
                {
                    unitSystem = "metric";
                }
                else
                {
                    unitSystem = "imperial";
                }



                string           webAddress = $"http://api.openweathermap.org/data/2.5/forecast/daily?q={locationName}&mode=json&units={unitSystem}&cnt=7&appid=d0f9a1cee42be9d3f4c06858437cd28b";
                string           response;
                WeatherDataModel outputWeatherData;
                dynamic          JsonObjectData;

                try
                {
                    response = webClient.DownloadString(webAddress);

                    if (response.Length < 55)
                    {
                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                    return(null);
                }
                //  outputWeatherData
                JsonObjectData = JObject.Parse(response);
                //string asd = JsonObjectData.list[0].temp.day;
                //MessageBox.Show(asd);
                outputWeatherData = new WeatherDataModel()
                {
                    TodayTemp    = JsonObjectData.list[0].temp.day,
                    MinimumTemp  = JsonObjectData.list[0].temp.min,
                    MaximumTemp  = JsonObjectData.list[0].temp.max,
                    WindSpeed    = JsonObjectData.list[0].speed,
                    ImageName    = JsonObjectData.list[0].weather[0].main,
                    Pressure     = JsonObjectData.list[0].pressure,
                    LocationCity = JsonObjectData.city.name,
                };
                outputWeatherData.Days = new DailyWeather[6];
                for (int i = 0; i <= 5; i++)
                {
                    StringBuilder describtion = new StringBuilder();
                    describtion.Append((string)JsonObjectData.list[i + 1].weather[0].description);
                    describtion.Replace("heavy intensity rain", currentLang.WeatherDescribtions["heavy intensity rain"]);
                    describtion.Replace("scattered clouds", currentLang.WeatherDescribtions["scattered clouds"]);
                    describtion.Replace("light", currentLang.WeatherDescribtions["light"]);
                    describtion.Replace("moderate", currentLang.WeatherDescribtions["moderate"]);
                    describtion.Replace("heavy", currentLang.WeatherDescribtions["heavy"]);
                    describtion.Replace("rain", currentLang.WeatherDescribtions["rain"]);
                    describtion.Replace("snow", currentLang.WeatherDescribtions["snow"]);
                    describtion.Replace("sky is clear", currentLang.WeatherDescribtions["sky is clear"]);


                    outputWeatherData.Days[i] = new DailyWeather(describtion.ToString(), (int)JsonObjectData.list[i + 1].temp.min,
                                                                 (int)JsonObjectData.list[i + 1].temp.max, (string)JsonObjectData.list[i + 1].weather[0].main);
                }



                return(outputWeatherData);
            }

            return(null);
        }