static void Main(string[] args) { // Create client MetOfficeDataPointClient client = new MetOfficeDataPointClient("<API_KEY>"); // Get all sites SiteListResponse siteListResponse = client.GetAllSites().Result; // Get available forcasts AvailableTimeStampsResponse availableTimeStampsResponse = client.GetAvailableTimestamps().Result; // Get all 3 hourly forecasts ForecastResponse3Hourly forecastResponse3Hourly = client.GetForecasts3Hourly().Result; // Get daily forecasts for site 14 ForecastResponseDaily forecastResponseDaily = client.GetForecastsDaily(14).Result; // Get historical observations ForecastResponse3Hourly historicalResponse = client.GetHistoricalObservations().Result; // Get closest site GeoCoordinate coordinate = new GeoCoordinate(51.508363, -0.163006); Location location = client.GetClosestSite(coordinate).Result; }
public IActionResult Index(double longitude, double latitude) { IpStackClient ipClient = new IpStackClient(_config["Keys:IPStack"]); string ipAddress = AppCode.Projects.Weather.GetRequestIP(_httpContextAccessor); IpStack.Models.IpAddressDetails location = ipClient.GetIpAddressDetails(ipAddress); GeoCoordinate coordinate = new GeoCoordinate(); // If location is provided then use over IP address if (longitude == 0 && latitude == 0) { coordinate.Longitude = location.Longitude; coordinate.Latitude = location.Latitude; } else { coordinate.Longitude = longitude; coordinate.Latitude = latitude; } MetOfficeDataPointClient metClient = new MetOfficeDataPointClient(_config["Keys:MetOfficeDataPoint"]); MetOfficeDataPoint.Models.Location site = metClient.GetClosestSite(coordinate).Result; ForecastResponse3Hourly forecastResponse = metClient.GetForecasts3Hourly(null, site.ID).Result; // Create list containing 5 days of forecasts for midday List <WeatherSummary> weatherSummaries = new List <WeatherSummary>(); // Get current minutes after midnight int minutes = (int)(DateTime.Now.TimeOfDay.TotalSeconds / 60); foreach (ForecastLocation3Hourly forecastLocation in forecastResponse.SiteRep.DV.Location) { foreach (Period3Hourly period in forecastLocation.Period) { if (DateTime.Parse(period.Value).Date == DateTime.Today.Date) { WeatherSummary weatherSummary = new WeatherSummary(); weatherSummary.ForecastDay = DateTime.Parse(period.Value); // Find closest forecast to now Rep3Hourly forecast = period.Rep.Aggregate((x, y) => Math.Abs(x.MinutesAfterMidnight - minutes) < Math.Abs(y.MinutesAfterMidnight - minutes) ? x : y); weatherSummary.Icon = AppCode.Projects.Weather.GetWeatherIcon(forecast.WeatherType); // Find min temperature weatherSummary.MinTemperature = (int)period.Rep.Where(x => x.MinutesAfterMidnight >= forecast.MinutesAfterMidnight).Min(x => x.Temperature); // Find current temperature weatherSummary.MaxTemperature = (int)period.Rep.Where(x => x.MinutesAfterMidnight >= forecast.MinutesAfterMidnight).Max(x => x.Temperature); // Get remaing forecasts weatherSummary.Forecasts = period.Rep.Where(x => x.MinutesAfterMidnight >= forecast.MinutesAfterMidnight).ToList(); weatherSummaries.Add(weatherSummary); } else { WeatherSummary weatherSummary = new WeatherSummary(); weatherSummary.ForecastDay = DateTime.Parse(period.Value); // Get icon for midday weatherSummary.Icon = AppCode.Projects.Weather.GetWeatherIcon(period.Rep.First(x => x.MinutesAfterMidnight == 720).WeatherType); // Find min temperature weatherSummary.MinTemperature = (int)period.Rep.Min(x => x.Temperature); // Find max temperature weatherSummary.MaxTemperature = (int)period.Rep.Max(x => x.Temperature); // Get forecasts weatherSummary.Forecasts = period.Rep; weatherSummaries.Add(weatherSummary); } } } ViewData["WeatherSummaries"] = weatherSummaries; ViewData["Location"] = location; ViewData["Site"] = site; return(View("~/Views/Projects/Weather/Index.cshtml")); }
/// <summary> /// The main function that actually gets the weather JSON from DataPoint, and passes it to the parser. /// </summary> /// <param name="choice"> /// Identifies whether the user wants a daily forecast or a 3-hourly forecast /// </param> private void GetWeather(int choice) { //Run Dictionary setup function GetDict(); //Make a new DataPoint Client, with the API key in the Settings file. MetOfficeDataPointClient client = new MetOfficeDataPointClient(Settings1.Default.mo_api_key); //Defines floats for try statement #region floats float lat; float lon; string postcode; #endregion //Attempt to get longitude and latitude values, along with the postcode. If successful, display in box. #region LongLatPost try { lat = LongLat().lat; lon = LongLat().lon; postcode = LongLat().postcode; } catch (Exception) //This still runs, even after a weberror in the GET function, so catch it here aswell and exit. { outputBox.Text = "Malformed or Incorrect Postcode!"; return; //Should exit this function and return to ready state } outputBox.Text = "Postcode: " + postcode; //Shows Postcode in text box outputBox.AppendText("\r\nLatitude: " + lat.ToString()); //Shows Latitude in text box outputBox.AppendText("\r\nLongitude: " + lon.ToString()); //Shows Longitude in text box #endregion //Get nearest weather site from coordinates from previous step. #region Find closest site GeoCoordinate coords = new GeoCoordinate(lat, lon); Location location = null; try { //Find closest weather site to postcode var locationone = client.GetClosestSite(coords); location = locationone.Result; } catch (AggregateException) { outputBox.Text = "Your API Key is incorrect! Please change it, or reset it to default in the Settings dialog."; return; } #endregion //Obtain Data from the Met Office, and pass to the appropriate parser. #region Data Aquisition, and Passing to Parser //Defines forecastResponse variable as dynamic, so it can be used regardless of which type the user requests dynamic forecastResponse = null; //Is choice Three Hourly? if (choice.Equals(1)) { try { var weatheresponse = client.GetForecasts3Hourly(null, location.ID); forecastResponse = new ForecastResponse3Hourly(); forecastResponse = weatheresponse.Result; HourlyParse(forecastResponse); //Run parsing for 3-hourly data } catch (WebException) //Catch incorrect API Key { outputBox.Text = "Your API Key is incorrect! Please change it, or reset it to default in the Settings dialog."; } } //Is choice Daily? else if (choice.Equals(2)) { try { var weatheresponse = client.GetForecastsDaily(location.ID); forecastResponse = new ForecastResponseDaily(); forecastResponse = weatheresponse.Result; DailyParse(forecastResponse); //Run parsing for Daily data } catch (WebException) //Catch incorrect API Key { outputBox.Text = "Your API Key is incorrect! Please change it, or reset it to default in the Settings dialog."; } } #endregion }