private void SetChosenLocation(WeatherLocation weatherlocation) { //Purpose: Saves new locationid to settings and closes this settings form GlobalConfig.WeatherLocation = weatherlocation; this.Close(); }
public override async Task StartAsync(IDialogContext context) { var message = context.MakeMessage(); WeatherLocation existingLocation = null; try { existingLocation = context.UserData.GetValueOrDefault <WeatherLocation>(WeatherBot.Storage.Location.UserDataLocationKey); } catch (Exception ex) { // Do nothing } if (existingLocation != null) { _message = $"Your current location is {existingLocation.Name}. Would you like to use this location?"; await base.StartAsync(context); } else { context.Done <bool?>(false); } }
// Getting the Name of the Zip code area public async Task <WeatherLocation> GetDescription(string zip) { try { WeatherLocation weather = this.DbService.ZipSearch(zip); Console.WriteLine(weather); if (weather == null) { weather = await WeatherHelper.GetWeatherDescription(zip); this.DbService.AddLocation(weather); } // TODO:: FIX THIS FOR REALS else if (weather.Forecasts[0].Date != DateTime.Today.ToString("MM/dd h:mm tt")) { weather = await WeatherHelper.GetWeatherDescription(zip); await this.DbService.ReplaceWeatherDocument(weather.Zip, weather); } return(weather); } catch (HttpRequestException httpRequestException) { return(null); // ($"Error getting weather from OpenWeather: {httpRequestException.Message}"); } }
public void Remove(WeatherLocation location) { using (var weatherlocationContext = new WeatherLocationContext()) { weatherlocationContext.WeatherLocations.Remove(location); weatherlocationContext.SaveChanges(); } }
private async Task AddLocation(WeatherLocation location) { _weatherLocationRepository.Add(new WeatherLocation { City = location.City, CountryCode = location.CountryCode, }); await _pageService.DisplayAlert(string.Empty, string.Format("Properly added city: {0}", location.City), "Ok"); }
public WeatherPresentationViewModel(WeatherLocation location) { _location = location; Title = string.Format("Weather forecast for {0}", location.City); DailyForecastDtos = new List <DailyForecastDto>(); GetWeatherDataCommand = new Command(async() => await GetWeatherData()); ChangeSelectedDayCommand = new Command <int>(ChangeSelectedDay); }
public async Task <Maybe <WeatherLocation> > GetLastLocation() { var location = await _locationProvider.GetLastLocationAsync(); if (location != null) { var weather = new WeatherLocation(location.Latitude, location.Longitude); return(Maybe <WeatherLocation> .Some(weather)); } return(Maybe <WeatherLocation> .None); }
private void listboxLocations_DoubleClick(object sender, EventArgs e) { if (listboxLocations.SelectedItem == null) { return; } listboxLocations.Visible = false; WeatherLocation location = (WeatherLocation)listboxLocations.SelectedItem; SetChosenLocation(location); }
protected async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { GeoLocation geoLocation = null; var activity = await result; if (string.IsNullOrEmpty(activity.Text) && activity.ChannelId == FacebookChannelId) { var facebookLocation = (FacebookLocation)activity.ChannelData.ToObject <FacebookLocation>(); double?latitude = facebookLocation?.message?.attachments?[0]?.payload?.coordinates?.lat; double?longitude = facebookLocation?.message?.attachments?[0]?.payload?.coordinates?.@long; if (latitude.HasValue && longitude.HasValue) { geoLocation = new GeoLocation() { Latitude = latitude.Value, Longitude = longitude.Value }; } } else { var googleLocationService = new GoogleLocationService(); var geoCodingRequest = new GeocodingRequest { Address = activity.Text ?? string.Empty, ApiKey = _apiKey, Language = _language }; geoLocation = await googleLocationService.GetLocationAsync(geoCodingRequest); } if (geoLocation != null) { WeatherLocation weatherLocation = null; try { weatherLocation = context.UserData.GetValueOrDefault <WeatherLocation>(WeatherBot.Storage.Location.UserDataLocationKey) ?? new WeatherLocation(); } catch (Exception ex) { // Do nothing weatherLocation = new WeatherLocation(); } weatherLocation.GeoLocation = geoLocation; context.UserData.SetValue(WeatherBot.Storage.Location.UserDataLocationKey, weatherLocation); } context.Done <GeoLocation>(geoLocation); }
//return weather for a city public Weather(string city) { iLocation = WeatherLocation.WL_AUS; yw = new YahooWeather(); for (int i = 0; i < yw.WeatherAustralia.Length; i++) { if (city == yw.WeatherAustralia[i].city.ToLower() || city == yw.WeatherAustralia[i].city.ToLower().Substring(0, 3)) { iLocation = (WeatherLocation)yw.WeatherAustralia[i].index; city_name = yw.WeatherAustralia[i].city_chn; break; } } }
// Wraps locking and null-checking. bool TryGetConditions(WeatherLocation location, out WeatherConditions cond) { cond = null; lock (_locker) { if (weather != null) { cond = weather.GetConditions(location); return(true); } } return(false); }
private void btnAdd_Click(object sender, System.EventArgs e) { if (searchResults.SelectedIndex != -1) { WeatherLocation srcLoc = (WeatherLocation)searchResults.Items[searchResults.SelectedIndex]; WeatherRegionForecast dstLoc = new WeatherRegionForecast(); dstLoc.LocationId = srcLoc.LocationId; dstLoc.Description = srcLoc.Description; dstLoc.ForecastDays = Convert.ToInt16(forecastDays.Value); dstLoc.IsMetric = rbUnitMetric.Checked; dstLoc.RadarMap = XoapProvider.Instance.GetRadarUrl(srcLoc.LocationId); forecastRegions.Items.Add(dstLoc); forecastRegions.SelectedIndex = forecastRegions.FindStringExact(dstLoc.Description); } }
public void UpdateForecast(WeatherLocation location, JObject forecast) { var now = clock.UtcNow; var foreDoc = new WeatherForecast { Location = location.Identifier, Year = now.Year, Month = now.Month, Day = now.Day, Forecast = forecast, LastUpdated = now }; Logger.Trace("forecast doc", foreDoc); Upsert(foreDoc); }
// This is the continuation delegate, gets invoked every time a new message comes in async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument) { WeatherLocation weatherLoc = null; string theWeather = string.Empty; // Get the incoming activity var message = await argument; var ws = new WeatherService(); weatherLoc = await ws.FindLocationCoordinatesAsync(message.Text); if (weatherLoc == null) { // Check to see if the location is already in the bot's state if (context.PrivateConversationData.TryGetValue("currentloc", out weatherLoc) == false) { // We don't have the city, need to return a message saying that theWeather = $"I queried Google and still didn't find anyting matching {message.Text}, mind entering a new location?"; await context.PostAsync(theWeather); context.Wait(MessageReceivedAsync); } } // We have a location - save it to the conversation data context.PrivateConversationData.SetValue("currentloc", weatherLoc); // try to parse the input to see if there's a time var timeParser = new Chronic.Parser(); var chronicResult = timeParser.Parse(message.Text); if (chronicResult != null && chronicResult.Start.HasValue) { theWeather = await ws.GetConditionsForLocationAtTimeAsync(weatherLoc, chronicResult.Start.Value); } else { theWeather = await ws.GetCurrentConditionsAsync(weatherLoc); } // Send something back await context.PostAsync(theWeather); // Wait for everything again context.Wait(MessageReceivedAsync); }
public static async Task <WeatherLocation> GetWeatherDescription(string zip) { using (HttpClient client = new HttpClient()) { string url = $"http://api.openweathermap.org/data/2.5/forecast?zip={zip}&appid=23abca4662290892ff42dd59246c00e1"; HttpResponseMessage response = client.GetAsync(url).Result; response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); var weatherData = JsonConvert.DeserializeObject <OpenWeatherResponse>(json); // temp list of 5 day/ 3 hour forecasts var weatherForecasts = new List <Forecast>(); // add all forecasts to the temp list as theyre created foreach (List timeWeather in weatherData.List) { Main main = timeWeather.Main; IEnumerable <WeatherDescription> weatherDesc = timeWeather.Weather; string description = string.Join(",", weatherDesc.Select(x => x.Description)); string icon = string.Join(",", weatherDesc.Select(x => x.Icon)); string date = DateTime.Parse(timeWeather.Date).ToString("MM/dd h:mm tt"); Forecast forecast = new Forecast { Description = description, Temp = main.Temp, Humidity = main.Humidity, Date = date, Icon = icon }; weatherForecasts.Add(forecast); } WeatherLocation weather = new WeatherLocation { Id = zip, Zip = zip, Name = weatherData.City.Name, Forecasts = weatherForecasts.ToArray() }; return(weather); } }
private async Task CreateWeatherDocumentIfNotExists(WeatherLocation weather) { try { await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, weather.Id)); } catch (DocumentClientException de) { if (de.StatusCode == HttpStatusCode.NotFound) { await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), weather); } else { throw; } } }
public async Task <DailyForecast16DaysDto> GetDailyForecastFor16Days(WeatherLocation location) { try { var url = ApiUrl .AppendPathSegments("forecast", "daily") .SetQueryParams(new { key = ApiKey, city = location.City, country = location.CountryCode }); return(await url.GetJsonAsync <DailyForecast16DaysDto>()); } catch (FlurlHttpException) { return(null); } }
public async System.Threading.Tasks.Task <IHttpActionResult> GetAsync(string location) { using (var client = new HttpClient()) { var uri = new Uri(api_uri + location); //Create the full uri with the location of the city var response = await client.GetAsync(uri); if (!response.IsSuccessStatusCode) //Check if the request was good { return(BadRequest()); } //Parse to JSON string textResult = await response.Content.ReadAsStringAsync(); WeatherLocation forecast = JsonConvert.DeserializeObject <WeatherLocation>(textResult); return(Ok(forecast)); } }
public override async Task <CommandResult> Execute() { await Task.CompletedTask; var location = new WeatherLocation { Name = Name, Identifier = Identifier, Latitude = Latitude, Longitude = Longitude }; var doc = documentStore.GetWeatherLocations(); if (doc.Locations.All(l => l.Identifier != Identifier)) { doc.Locations.Add(location); documentStore.UpdateLocations(doc); } return(CommandResult.SuccessfulResult); }
void WeatherSearch(ITriggerMsg e, WeatherLocation location) { if (TryGetConditions(location, out WeatherConditions cond)) { if (cond.Success) { irc.SendMessage(e.ReturnTo, WeatherFormat.IrcFormat(cond)); } else if (cond.HttpErrorIs(HttpStatusCode.NotFound)) { e.Reply("Sorry, couldn't find anything for query '{0}'.", location); } else { e.Reply(cond.Exception.Message); } } else { e.Reply(weatherError); } }
public async Task <Weather> GetWeather(WeatherLocation location) { var client = new HttpClient(); var response = await client.GetAsync( $"https://api.openweathermap.org/data/2.5/weather?lat={location.Latitude}&lon={location.Longitude}&appid={API_KEY}"); var responseString = await response.Content.ReadAsStringAsync(); var json = JsonValue.Parse(responseString); var descriptionJson = json["weather"][0]; var description = new Description( descriptionJson["id"], descriptionJson["main"], descriptionJson["description"], descriptionJson["icon"] ); var mainJson = json["main"]; var main = new Main( mainJson["temp"] + KELVIN_ZERO, mainJson["pressure"], mainJson["humidity"] ); return(new Weather(json["name"], description, main)); }
// --- Weather Search, 'w' trigger --- void WeatherSearch(ITriggerMsg e) { var location = GetLocation(e); if (!string.IsNullOrWhiteSpace(location)) { var weatherLoc = WeatherLocation.Parse(location); if (weatherLoc.IsValidQuery && VerifyCountry(weatherLoc.Country)) { WeatherSearch(e, weatherLoc); } else { e.Reply("Invalid query format. Please use \"city, country\" or \"zip, country\", " + "where country is a 2-letter country code (ISO 3166)."); } } else { e.Reply("Either specify a location or set your default location with the 'W' trigger. " + "(That is an upper case W)"); } }
/// <summary> /// return the weather for all australia /// </summary> public Weather() { yw = new YahooWeather(); iLocation = WeatherLocation.WL_AUS; }
/// <summary>Remove (DELETE) conditions.</summary> protected void RemoveConditions(WeatherLocation location, int maxLength) { // Adjusted maximum length to account the new record. maxLength -= 1; if(location.locationConditions != null && location.locationConditions.Count() > maxLength) { var objConditions = location.locationConditions.OrderByDescending(condition => condition.conditionDateUpdated).Skip(maxLength); _dbContext.GetTable<WeatherCondition>().DeleteAllOnSubmit(objConditions); } }
/// <summary>Create locations with default data.</summary> public IList<WeatherLocation> CreateLocationsDefault() { var objLocations = new WeatherLocation[] { new WeatherLocation() { locationName = "Orlando", locationUrl = "http://www.weather.gov/data/current_obs/KMCO.xml" }, new WeatherLocation() { locationName = "San Diego", locationUrl = "http://www.weather.gov/data/current_obs/KSAN.xml" }, new WeatherLocation() { locationName = "San Antonio", locationUrl = "http://www.weather.gov/data/current_obs/KSAT.xml" }, new WeatherLocation() { locationName = "Tampa", locationUrl = "http://www.weather.gov/data/current_obs/KTPA.xml" }, new WeatherLocation() { locationName = "Williamsburg", locationUrl = "http://www.weather.gov/data/current_obs/KJGG.xml" }, new WeatherLocation() { locationName = "Trenton", locationUrl = "http://www.weather.gov/data/current_obs/KTTN.xml" } }; _dbContext.GetTable<WeatherLocation>().InsertAllOnSubmit(objLocations); _dbContext.SubmitChanges(); return objLocations; }
public async Task <WeatherLocation> GetDescription(string zip) { WeatherLocation weather = await valueService.GetDescription(zip); return(weather); }
public async Task ReplaceWeatherDocument(string zip, WeatherLocation locationUpdate) { await this.client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, zip), locationUpdate); Console.WriteLine("Replaced {0}", zip); }
// add a new location to the db public async void AddLocation(WeatherLocation newWeatherLocation) { await CreateWeatherDocumentIfNotExists(newWeatherLocation); }
/// <summary>Create weather conditions from location.</summary> protected void CreateConditions(WeatherLocation location) { // Validate HTTP implementation. try { // Create a HTTP request for XML document. HttpWebRequest webRequest = WebRequest.Create(location.locationUrl) as HttpWebRequest; // Get HTTP response. using(HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse) { // Validate HTTP response. if(!webResponse.ContentType.Contains("text/xml") || webResponse.ContentLength <= 0) { EventLog.WriteEntry(logName, "HTTP Error: Malformed response. Goto source line: 142.", EventLogEntryType.Error); return; } // Get stream from HTTP response. StreamReader streamResponse = new StreamReader(webResponse.GetResponseStream()); // Retrieve XML document. XDocument xmlDocument = XDocument.Load(streamResponse); // Parse XML document. var objConditions = ( from x in xmlDocument.Descendants("current_observation") select new WeatherCondition { conditionLocation = location, conditionDateUpdated = DateTime.Now, conditionCredit = (string)x.Element("credit"), conditionCreditUrl = (string)x.Element("credit_URL"), conditionImageUrl = (string)x.Element("image").Element("url"), conditionImageTitle = (string)x.Element("image").Element("title"), conditionImageLink = (string)x.Element("image").Element("link"), conditionSuggestedPickup = (string)x.Element("suggested_pickup"), conditionSuggestedPickupPeriod = (float?)x.Element("suggested_pickup_period"), conditionLocationString = (string)x.Element("location"), conditionStationId = (string)x.Element("station_id"), conditionLatitude = (float?)x.Element("latitude"), conditionLongitude = (float?)x.Element("longitude"), conditionObservationTime = (string)x.Element("observation_time"), conditionObservationTimeRfc822 = (string)x.Element("observation_time_rfc822"), conditionWeather = (string)x.Element("weather"), conditionTemperatureString = (string)x.Element("temperature_string"), conditionTempF = (float?)x.Element("temp_f"), conditionTempC = (float?)x.Element("temp_c"), conditionRelativeHumidity = (float?)x.Element("relative_humidity"), conditionWindString = (string)x.Element("wind_string"), conditionWindDir = (string)x.Element("wind_dir"), conditionWindDegrees = (float?)x.Element("wind_degrees"), conditionWindMph = (float?)x.Element("wind_mph"), conditionWindGustMph = (float?)x.Element("wind_gust_mph"), conditionWindKt = (float?)x.Element("wind_kt"), conditionWindGustKt = (float?)x.Element("wind_gust_kt"), conditionPressureString = (String)x.Element("pressure_string"), conditionPressureMb = (float?)x.Element("pressure_mb"), conditionPressureIn = (float?)x.Element("pressure_in"), conditionDewpointString = (string)x.Element("dewpoint_string"), conditionDewpointF = (float?)x.Element("dewpoint_f"), conditionDewpointC = (float?)x.Element("dewpoint_c"), conditionVisibilityMi = (float?)x.Element("visibility_mi"), conditionIconUrlBase = (string)x.Element("icon_url_base"), conditionTwoDayHistory = (string)x.Element("two_day_history_url"), conditionIconUrlName = (string)x.Element("icon_url_name"), conditionObUrl = (string)x.Element("ob_url"), conditionDisclaimerUrl = (string)x.Element("disclaimer_url"), conditionCopyrightUrl = (string)x.Element("copyright_url"), conditionPrivacyPolicyUrl = (string)x.Element("privacy_policy_url") } ).ToList(); // Validate conditions. if(objConditions == null || objConditions.Count() != 1) { EventLog.WriteEntry(logName, "HTTP Error: More than one parent element in XML. Goto source line: 150.", EventLogEntryType.Error); return; } // Create (INSERT) conditions. _dbContext.GetTable<WeatherCondition>().InsertOnSubmit(objConditions[0]); } } catch(UriFormatException ex) { EventLog.WriteEntry(logName, "HTTP Error: Malformed URL from web request. Goto source line: 137. Details: " + ex, EventLogEntryType.Error); return; } catch(WebException ex) { EventLog.WriteEntry(logName, "HTTP Error: Malformed content from web response. Goto source line: 139. Details: " + ex, EventLogEntryType.Error); return; } catch(XmlException ex) { EventLog.WriteEntry(logName, "XML Error: " + ex, EventLogEntryType.Error); return; } }