public DailyWeather CreadBaseDailyWeather(string indicator = "C", string lat = "", string lon = "") { var is_ParametrsNull = this.CheckToNull(indicator, lat, lon); var is_Internet = this.CheckInternetConnection(); if (is_Internet) { if (!is_ParametrsNull) { _coordinate.FindCooordinates(lat, lon); var currentLatitude = _coordinate.Latidude; var currentLontitude = _coordinate.Longtitude; var currentDailyWeatherInformation = _repository. GetAllDailyWeatherInformation (currentLatitude, currentLontitude, indicator); _mainDailyObject = currentDailyWeatherInformation; return(_mainDailyObject); } else { throw new Exception("Some parametrs are null"); } } else { throw new Exception("No internet exeption"); } }
public IList <DailyWeather> GetWeather(string code) { IList <DailyWeather> weatherForecast = new List <DailyWeather>(); try { using (SqlConnection conn = new SqlConnection(this.connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("select * from weather where parkCode = @parkCode order by fiveDayForecastValue", conn); cmd.Parameters.AddWithValue("@parkCode", code); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { DailyWeather dailyWeather = this.ConvertSqlToWeather(reader); weatherForecast.Add(dailyWeather); } } } catch (SqlException ex) { Console.WriteLine(ex.Message); throw; } return(weatherForecast); }
public DailyWeather GetAllDailyWeatherInformation(string lat, string lon, string choise = "C") { if (choise == "C") { var json = CurrentJsonForDailyWeatherC(_dailyLink, lat, lon); var deserilizedDailyWeather = _deserializingDailyWeather .DeserializeJson(json.Result); _wholeDailyWeather = deserilizedDailyWeather; return(_wholeDailyWeather); } else { var json = CurrentJsonForDailyWeatherF(_dailyLink, lat, lon); var deserilizedDailyWeather = _deserializingDailyWeather .DeserializeJson(json.Result); _wholeDailyWeather = deserilizedDailyWeather; return(_wholeDailyWeather); } }
/// <summary> extract climate data from json object and write it into an output file /// </summary> /// <param name="outpath"> out path</param> /// <param name="agMipJson"> agMipJson object </param> public static void ExtractWeatherData(string outpath, JObject agMipJson, ref string errorOut) { IList <JToken> results = agMipJson["weathers"].First["dailyWeather"].Children().ToList(); List <DailyWeather> dailyWeathers = new List <DailyWeather>(); List <string> parameters = new List <string> { "w_date", "rain", "tavd", "tmin", "tmax", "rhavd", "srad", "wind" }; foreach (JToken token in results) { if (!Util.HasMissingParameter(parameters, "climate", token, ref errorOut)) { String date = token["w_date"].ToString(); double rain = (double)token["rain"].ToObject(typeof(double)); double tavg = (double)token["tavd"].ToObject(typeof(double)); double tmin = (double)token["tmin"].ToObject(typeof(double)); double tmax = (double)token["tmax"].ToObject(typeof(double)); double humidity = (double)token["rhavd"].ToObject(typeof(double)); double radiation = (double)token["srad"].ToObject(typeof(double)); double wind = (double)token["wind"].ToObject(typeof(double)); DailyWeather dailyWeather = ClimateData.FromAgMIP(date, tavg, tmin, tmax, radiation, rain, humidity, wind); dailyWeathers.Add(dailyWeather); } } SaveClimateData(outpath, dailyWeathers); }
public DailyWeatherData(DailyWeather data) { iconName = data.Weather.Length > 0 ? data.Weather[0].Icon : ""; dayOfWeek = data.Timestamp.DayOfWeek.ToString(); dailyTemperature = DetailsViewModel.convertTemperature(data.Temperatures.Max); nightTemperature = DetailsViewModel.convertTemperature(data.Temperatures.Min); }
public List <DailyWeather> GetWeatherForecast(string id) { List <DailyWeather> result = new List <DailyWeather>(); using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(SQL_GETWEATHERFORECAST, conn); cmd.Parameters.AddWithValue("@parkCode", id); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { DailyWeather dailyWeather = new DailyWeather() { Day = Convert.ToInt32(reader["fiveDayForecastValue"]), Forecast = Convert.ToString(reader["forecast"]), High = Convert.ToInt32(reader["high"]), Low = Convert.ToInt32(reader["low"]), ParkCode = Convert.ToString(reader["parkCode"]) }; result.Add(dailyWeather); } } return(result); }
/// <summary> /// Returns a list of DailyWeather objects for a given park code. /// </summary> /// <param name="parkCode">Park code</param> /// <returns>IList of DailyWeather objects</returns> public IList <DailyWeather> GetForecast(string parkCode) { IList <DailyWeather> forecast = new List <DailyWeather>(); try { using (SqlConnection conn = new SqlConnection(this.connectionString)) { conn.Open(); string sql = "SELECT * FROM weather WHERE parkCode = @parkCode;"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@parkCode", parkCode); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { DailyWeather weather = this.ConvertReaderToDailyWeather(reader); forecast.Add(weather); } } } catch (SqlException x) { // LOG%#$$%^$%^&%^&*&^@#$%R? throw; } return(forecast); }
public void DailyWeatherInitializedToInputParams() { var sut = new DailyWeather(1, 2, 3); Assert.Equal(1, sut.DayOfMonth); Assert.Equal(2, sut.MinTemp); Assert.Equal(3, sut.MaxTemp); }
public async Task FindsMinimumTempSpreadSingleDay() { var weather1 = new DailyWeather(1, 2, 10); _weatherData.Add(weather1); var sut = new DailyWeatherService(_mockFileParser.Object, _mockLoggingService.Object); var result = await sut.GetWeatherWithSmallestTempSpread(); Assert.Equal(weather1.DayOfMonth, result.DayOfMonth); }
private DailyWeather ConvertSqlToWeather(SqlDataReader reader) { DailyWeather dailyWeather = new DailyWeather { ForecastDay = Convert.ToInt32(reader["fiveDayForecastValue"]), LowTemp = Convert.ToInt32(reader["low"]), HiTemp = Convert.ToInt32(reader["high"]), Forecast = Convert.ToString(reader["forecast"]) }; return(dailyWeather); }
public List <DailyWeather> DaysOfRain(List <Forecast> forecasts) { List <string> RainWords = new List <string>() { "rain", "shower", "precipitation" }; List <DailyWeather> RainyDays = new List <DailyWeather>(); int rainPercent; foreach (Forecast Event in forecasts) { string[] EventWeatherList = Event.detailedForecast.ToLower().Split('.'); for (int i = 0; i < RainWords.Count(); i++) { List <string> wetDay = EventWeatherList.Where(x => x.Contains(RainWords[i]) && x.Contains("percent")).ToList(); if (wetDay != null) { foreach (string wetEvent in wetDay) { DailyWeather dw = new DailyWeather(); char[] rainChance = wetEvent.Where(Char.IsDigit).ToArray(); string percentage = String.Join("", rainChance); rainPercent = int.Parse(percentage); dw.eventNumber = Event.EventNumber; dw.name = Event.name; dw.temperature = GetTemperature(EventWeatherList); dw.weather = "Chance of precipitation"; if (rainPercent >= 50) { dw.waterPlants = "No"; } else if (rainPercent < 50 && rainPercent > 30) { dw.waterPlants = "Check the hygrometer"; } else { dw.waterPlants = "Yes"; } RainyDays.Add(dw); } } } } for (int i = 0; i < RainyDays.Count(); i++) { forecasts.RemoveAll(e => e.EventNumber == RainyDays[i].eventNumber); } Session["forecasts"] = forecasts; return(RainyDays); }
private void CollectionDetailListView_ItemClick(object sender, ItemClickEventArgs e) { try { DailyWeather a = e.ClickedItem as DailyWeather; Pages.Parameters.cityName = a.date; Pages.Parameters.previous = a.date; Frame.Navigate(typeof(HomePage), "fromCollection"); } catch { } }
public async Task FindsMinimumTempSpreadAmongManyDays() { var weather1 = new DailyWeather(1, 2, 10); var weather2 = new DailyWeather(2, 4, 6); var weather3 = new DailyWeather(3, 11, 14); _weatherData.AddRange(new DailyWeather[] { weather1, weather2, weather3 }); var sut = new DailyWeatherService(_mockFileParser.Object, _mockLoggingService.Object); var result = await sut.GetWeatherWithSmallestTempSpread(); Assert.Equal(weather2.DayOfMonth, result.DayOfMonth); }
/// <summary> /// Creates a DailyWeather object. /// </summary> /// <returns>True if object successfully created with input params. False if not and out param is set to empty object.</returns> public bool TryCreate(int dayOfMonth, int minTemp, int maxTemp, out IDailyWeather dailyWeather) { try { dailyWeather = new DailyWeather(dayOfMonth, minTemp, maxTemp); } catch (Exception ex) { _loggingService.Log("Unable to create DailyWeather object from numeric values.", ex); dailyWeather = DailyWeather.EmptyDailyWeather; } return((DailyWeather)dailyWeather != DailyWeather.EmptyDailyWeather); }
/// <summary> write DailyWeather object as text line for csv format /// </summary> /// <param name="dailyWeather"></param> /// <returns></returns> private static string AsCSVLine(DailyWeather dailyWeather) { string result = dailyWeather.Isodate.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; result += dailyWeather.DailyTemperatureAverage.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; result += dailyWeather.DailyTemperatureMin.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; result += dailyWeather.DailyTemperatureMax.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; result += dailyWeather.Wind.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; result += dailyWeather.SunRadiation.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; result += dailyWeather.Precip.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; result += dailyWeather.Relativehumidity.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + ClimateData.CsvSeperator; return(result); }
/// <summary> /// Converts a reader object to a DailyWeather object. /// </summary> /// <param name="reader">Reader Object</param> /// <returns>DailyWeather Object</returns> private DailyWeather ConvertReaderToDailyWeather(SqlDataReader reader) { DailyWeather weather = new DailyWeather(); weather.ParkCode = Convert.ToString(reader["parkCode"]); weather.Day = Convert.ToInt32(reader["fiveDayForecastValue"]); weather.Low = Convert.ToInt32(reader["low"]); weather.High = Convert.ToInt32(reader["high"]); weather.LowDisplay = Convert.ToInt32(reader["low"]); weather.HighDisplay = Convert.ToInt32(reader["high"]); weather.Forecast = Convert.ToString(reader["forecast"]); return(weather); }
private void DisplayShort(WeatherForecast weather) { AnsiConsoleHelper.TitleRule(":satellite_antenna: Satellite scans complete. Today's weather is..."); int maxDesc = weather.Hourly.Select(h => h.Description).Max(d => d.Length); string desc = (weather.Current.Description).PadRight(maxDesc); AnsiConsole.MarkupLine($"[white]Current:[/][silver] {weather.Current.Icon} {desc} {weather.Current.Temperature,3}°C FeelsLike {weather.Current.FeelsLike,3}°C[/]"); DailyWeather today = weather.Daily.FirstOrDefault(); desc = (today.Description).PadRight(maxDesc); AnsiConsole.MarkupLine($"[white]Today:[/][silver] {today.Icon} {desc} {today.Temperature.Max,3}°C/{today.Temperature.Min,3}°C[/][silver] High/Low[/]"); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { if (Pages.Parameters.collections != null && Convert.ToString(e.Parameter) == "1") { var myWeather = await MainAPI.MainAPI.getWeather(Pages.Parameters.cityName); //实例化主要天气API var weatherCode = "/Assets/Icons/white/" + Convert.ToString(myWeather.results[0].now.code) + "@2x.png"; string cORf = Pages.Parameters.isCelcius == true ? "°C" : "°F"; collectionDailyWeathers.Add(new DailyWeather() { date = Pages.Parameters.cityName, iconSource = new BitmapImage(new Uri(myImg.BaseUri, weatherCode)), tempreture = myWeather.results[0].now.temperature + cORf, descrip = myWeather.results[0].now.text }); var dialog = new ContentDialog() //消息框 { Title = "消息提示", Content = "已收藏", PrimaryButtonText = "确定", FullSizeDesired = false, }; dialog.PrimaryButtonClick += (_s, _e) => { }; await dialog.ShowAsync(); } if (Convert.ToString(e.Parameter) == "0") { int index = collectionDailyWeathers.Count(); if (index == 0) { } else { DailyWeather daily = collectionDailyWeathers.First(r => r.date == Pages.Parameters.cityName); collectionDailyWeathers.Remove(daily); } var dialog = new ContentDialog() //消息框 { Title = "消息提示", Content = "已取消收藏!", PrimaryButtonText = "确定", FullSizeDesired = false, }; dialog.PrimaryButtonClick += (_s, _e) => { }; await dialog.ShowAsync(); } base.OnNavigatedTo(e); }
public DailyWeatherCtrl(Context context, DailyWeather weather) : base(context) { LayoutInflater inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService); weatherDetailView = inflater.Inflate(Resource.Layout.WeatherDetail, null); var ivWeather = weatherDetailView.FindViewById <ImageView>(Resource.Id.ivWeather); var imageBitmap = GetImageBitmapFromUrl($"https://www.metaweather.com/static/img/weather/png/{weather.WeatherAbbr}.png"); ivWeather.SetImageBitmap(imageBitmap); SetTextViewText(Resource.Id.tvDate, weather.Date.ToString("ddd")); SetTextViewText(Resource.Id.tvWeather, weather.Weather); SetTextViewText(Resource.Id.tvMax, $"{String.Format("{0:0.0}", weather.MaxTemp)}°"); SetTextViewText(Resource.Id.tvMin, $"{String.Format("{0:0.0}", weather.MinTemp)}°"); AddView(weatherDetailView); }
/// <summary> convert paramenters to monica measurement units /// </summary> /// <param name="date"> date as string in yyyyMMdd</param> /// <param name="tempAvgDegC"> avarage temperature in degree celsius </param> /// <param name="tempMinDegC">minimal temperature in degree celsius </param> /// <param name="tempMaxDegC">maximal temperature in degree celsius </param> /// <param name="radiation">sun radiation in MJ m-2 d-1</param> /// <param name="precipitation">percipation in mm</param> /// <param name="relativehumidity">relative humidity in %</param> /// <param name="windKmD">wind speed in km/day </param> /// <returns> DailyWeather with monica values</returns> private static DailyWeather FromAgMIP(string date, double tempAvgDegC, double tempMinDegC, double tempMaxDegC, double radiation, double precipitation, double relativehumidity, double windKmD) { DailyWeather dayWeather = new DailyWeather(); try { dayWeather.Isodate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); dayWeather.DailyTemperatureAverage = tempAvgDegC; dayWeather.DailyTemperatureMin = tempMinDegC; dayWeather.DailyTemperatureMax = tempMaxDegC; dayWeather.SunRadiation = radiation; dayWeather.Precip = precipitation; dayWeather.Relativehumidity = relativehumidity; dayWeather.Wind = windKmD / 86.4; // km/day to m/s } catch (FormatException f) { Console.WriteLine("An error occured:"); Console.WriteLine(f.Message); } return(dayWeather); }
//Function that returns array of objects that are used for "Tjedni pregled", future daily weather forecast public static DailyWeather[] getFutureDailyWeatherList(IList <ListW> weathers, int count) { DailyWeather[] weather = new DailyWeather[5]; //Only have one weather per day - gives a 5 total DateTime today = DateTime.Now; //Get current date so we can compare the long list of weathers and take only days DateTime dayCounterDate = today; //This is used as compare value if date was already repeated int dayCounter = 0; //Counter for array for (int i = 0; i < count; i++) { DateTime date = UnixTimeStampToDateTime(weathers[i].dt); //Convert timestamp to date using helper function if (DateTime.Compare(date, dayCounterDate) > 0) //Check if date from input is later than previous { //if true, then insert the daily weather object to array which is one of the 5 days DailyWeather weatherDay = new DailyWeather(); //Map data weatherDay.date = UnixTimeStampToDateTime(weathers[i].dt); weatherDay.tempMin = weathers[i].main.temp_min; weatherDay.tempMax = weathers[i].main.temp_max; weatherDay.humidity = weathers[i].main.humidity; weatherDay.title = weathers[i].weather[0].main; weatherDay.visibility = weathers[i].visibility; weatherDay.windSpeed = weathers[i].wind.speed; weatherDay.windDegree = weathers[i].wind.deg; //Insert object weather[dayCounter] = weatherDay; //Add the logic counters dayCounterDate = dayCounterDate.AddDays(1); dayCounter++; } } return(weather); }
public override async Task Execute(Message message, TelegramBotClient botClient) { var loggerFactory = LoggerFactory.Create(builder => { builder.AddProvider(new SerilogLoggerProvider()); }); ILogger <GetWeatherCommand> logger = loggerFactory.CreateLogger <GetWeatherCommand>();//создаём типизированный логгер var chatId = message.Chat.Id; HttpClient client = new HttpClient(); if (callbackdata == "")//если в нашем коллбеке ничего нет, то мы выполняем запрос текущей погоды { logger.LogInformation("Делаю запрос к OpenWeatherAPI " + String.Format(AppSettings.UrlForOpenWeatherApiCurrentWeather, $"q={queryparams["city"]}&units={queryparams["units"]}&lang={queryparams["lang"]}", AppSettings.keyForOpenWeather)); string response = null; try { response = await client.GetStringAsync(String.Format(AppSettings.UrlForOpenWeatherApiCurrentWeather, $"q={queryparams["city"]}&units={queryparams["units"]}&lang={queryparams["lang"]}", AppSettings.keyForOpenWeather)); CurrentWeather deserializeResponse = JsonSerializer.Deserialize <CurrentWeather>(response); await botClient.SendTextMessageAsync( chatId : chatId, text : $"Город: {deserializeResponse.name} {EmojiList.Emoji.City_Sunrise}\n" + $"Погода: {deserializeResponse.weather[0].main}, ({deserializeResponse.weather[0].description})\n" + $"Температура: {deserializeResponse.main.temp}℃, \nмин({deserializeResponse.main.temp_min}℃) макс({deserializeResponse.main.temp_max}℃)\nпо ощущениям: {deserializeResponse.main.feels_like}℃\n" + $"Давление: {deserializeResponse.main.pressure} гПа\n" + $"Влажность: {deserializeResponse.main.humidity} %\n" + $"Ветер: скорость ветра - {deserializeResponse.wind.speed}м/с, направление {deserializeResponse.wind.deg}°\n" + $"Облачность: {deserializeResponse.clouds.all} %", replyMarkup : new InlineKeyboardMarkup(new InlineKeyboardButton() { Text = "Прогноз на 7 дней", CallbackData = $"lat={deserializeResponse.coord.lat.ToString().Replace(",",".")}&lon={deserializeResponse.coord.lon.ToString().Replace(",", ".")}" }), parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); } catch (Exception ex) { logger.LogError("При запросе к OpenWeatherAPI произошло исключение " + ex.Message); await botClient.SendTextMessageAsync( chatId : chatId, text : $"Город, который вы ввели не существует, либо не удаётся получить данные о погоде в этом городе", replyMarkup : new ReplyKeyboardMarkup(KeyBoards.keyboardButtons, resizeKeyboard: true), parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); } if (response != null) { logger.LogInformation("Получил ответ: " + response); } } else //иначе выполняем запрос погоды на 7 дней { logger.LogInformation("Делаю запрос к OpenWeatherAPI " + String.Format(AppSettings.UrlForOpenWeatherApi7days, callbackdata + $"&units={queryparams["units"]}&exclude={queryparams["exclude"]}&lang={queryparams["lang"]}" , AppSettings.keyForOpenWeather)); string responseFrom7days = null; try { responseFrom7days = await client.GetStringAsync(String.Format(AppSettings.UrlForOpenWeatherApi7days, callbackdata + $"&units={queryparams["units"]}&exclude={queryparams["exclude"]}&lang={queryparams["lang"]}", AppSettings.keyForOpenWeather)); DailyWeather deserializeResponse = JsonSerializer.Deserialize <DailyWeather>(responseFrom7days); foreach (var dayRes in deserializeResponse.daily) { await botClient.SendTextMessageAsync( chatId : chatId, text : $"Дата: {dayRes.date.Date.ToString("d")}\n" + $"День: {CultureInfo.GetCultureInfo("ru-RU").DateTimeFormat.GetDayName(dayRes.date.DayOfWeek)}\n" + $"Погода: {dayRes.weather[0].main}, ({dayRes.weather[0].description})\n" + $"Температура:\n {EmojiList.Emoji.Sunrise} утром {dayRes.temp.morn}℃\n {EmojiList.Emoji.Sunny} днём {dayRes.temp.day}℃\n {EmojiList.Emoji.Sunrise_Over_Mountains} вечером {dayRes.temp.eve}℃\n {EmojiList.Emoji.Full_Moon} ночью {dayRes.temp.night}℃\n мин({dayRes.temp.min}℃) макс({dayRes.temp.max}℃)\n" + $"Температура по ощущениям:\n {EmojiList.Emoji.Sunrise} утром {dayRes.feels_like.morn}℃\n {EmojiList.Emoji.Sunny} днём {dayRes.feels_like.day}℃\n {EmojiList.Emoji.Sunrise_Over_Mountains} вечером {dayRes.feels_like.eve}℃\n {EmojiList.Emoji.Full_Moon} ночью {dayRes.feels_like.night}℃\n" + $"Давление: {dayRes.pressure} гПа\n" + $"Влажность: {dayRes.humidity} %\n" + $"Ветер: скорость ветра - {dayRes.wind_speed}м/с, направление {dayRes.wind_deg}°\n" + $"Облачность: {dayRes.clouds} %", replyMarkup : new ReplyKeyboardMarkup(KeyBoards.keyboardButtons, resizeKeyboard: true), parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); Thread.Sleep(500); } } catch (Exception ex) { logger.LogError("При запросе к OpenWeatherAPI произошло исключение " + ex.Message); } if (responseFrom7days != null) { logger.LogInformation("Получил ответ: " + responseFrom7days); } callbackdata = ""; } client.Dispose(); }
//Returns the formated string for visibility data public static string getFutureDailyWeatherVisiblity(DailyWeather weather) { return(getVisibilityDisplayValuesFromString(weather.visibility)); }
//Returns the formated string from values for listbox items of humidty public static string getFutureDailyWeatherHumidty(DailyWeather weather) { return(getHumidtyDisplayValueFromString(weather.humidity)); }
public DailyWeatherViewModel(DailyWeather dailyWeather, WeatherForecastOptions options) { DailyWeather = dailyWeather; _options = options; Init(); }