public static Forecast GetForecast()
    {
        try {
            var excludeBlocks = new Exclude[]
            {
            Exclude.alerts,
            Exclude.minutely,
            Exclude.hourly,
            //Exclude.daily,
            Exclude.flags
            };

            var request = new ForecastIORequest(ApiKey, 46.280613f, -119.340984f, DateTime.Now, Unit.us, null, excludeBlocks);
            var forecast = request.Get();
            return new Forecast(forecast.daily.data[0].apparentTemperatureMax,
                forecast.daily.data[0].apparentTemperatureMin,
                forecast.currently.temperature,
                forecast.currently.summary,
                forecast.currently.icon);
        }
        catch (WebException ex)
        {
            return new Forecast(0, 0, 0, "The weather man called in sick.", "broken");
        }
    }
Beispiel #2
0
    public void getWeather()
    {
        var request = new ForecastIORequest(api_key, Lat, Long, Unit.auto);
        ForecastIOResponse response = request.Get();

        Temperature = Math.Round(response.currently.temperature).ToString();
        Condition = response.currently.summary;
        Town = city;
        TFCond = response.daily.data[0].summary;
        TFHigh = Math.Round(response.daily.data[0].temperatureMax).ToString();
        TFLow = Math.Round(response.daily.data[0].temperatureMin).ToString();

        //Should we say Good Morning, Afternoon or Evening?
        TimeSpan morning_end = new TimeSpan(12, 00, 0); //10am
        TimeSpan afternoon_end = new TimeSpan(18, 00, 0); //7pm
        TimeSpan now = DateTime.Now.TimeOfDay;
        string greeting = "Good Morning";
        if (now > afternoon_end)
            greeting = "Good Evening";
        else if (now > morning_end)
            greeting = "Good Afternoon";


        Console.WriteLine(greeting + ". The current weather in " + Town + " is " + Condition + " at " + Temperature + " degrees. Today is expected to be " + TFCond + " with a top of " + TFHigh + ", and a low of " + TFLow);
        return;
    }
        public IHttpActionResult Get(string zipCode, int? years = 10)
        {
            // Now we can make our first API call to map the zip code
            //  to the geo coordinates we need
            //
            var zipCodeResponse = RequestGeoFromZipcode(zipCode);

            // Let's make sure the zip code was mapped properly before proceeding
            //
            if (zipCodeResponse == null)
            {
                return BadRequest("The zip code could not be mapped to a latitude and longitude");
            }

            var zipcodeWeather = new ZipcodeWeather
            {
                City = zipCodeResponse.City,
                State = zipCodeResponse.State,
                Latitude = zipCodeResponse.Latitude,
                Longitude = zipCodeResponse.Longitude
            };

            // Grab the current date so we can create offsets from it
            //
            var startDate = DateTime.Now;

            // Now loop according to 'years' and use the index each time to make a request back
            //  in time
            //
            foreach (var offset in Enumerable.Range(0, (int) years))
            {
                // Calculate the date for this iteration
                //
                var pastDate = startDate.AddYears(-offset);

                // Make the actual forecast.io call
                //
                var request = new ForecastIORequest(ConfigurationManager.AppSettings["forecast-io-key"], zipCodeResponse.Latitude, zipCodeResponse.Longitude, pastDate, Unit.us);
                var response = request.Get();

                // Create the temp object we need to return and add it to the list
                //
                zipcodeWeather.HistoricalTemperatures.Add(new HistoricalTemperature
                {
                    Date = pastDate,
                    High = response.daily.data[0].temperatureMax,
                    Low = response.daily.data[0].temperatureMin
                });
            }

            // Use the WebAPI base method to return a 200-response with the list as
            //  the payload
            //
            return Ok(zipcodeWeather);
        }
        /// <summary>
        /// Gets daily weather conditions given latitude and longitude. Currently synchronous
        /// </summary>
        /// <param name="latitude">lat</param>
        /// <param name="longitude">long</param>
        /// <returns>Weather object with condition and temperature from weather service</returns>
        public static Weather GetWeather(float latitude, float longitude)
        {
            var request = new ForecastIORequest(API_KEY, latitude, longitude, DateTime.Now, Unit.us);
            var response = request.Get();

            DailyForecast forecast = response.daily.data.First();

            Temperature temperature = WeatherServiceHelper.GetDailyTemperature(forecast.apparentTemperatureMin, forecast.apparentTemperatureMax);
            WeatherCondition condition = WeatherServiceHelper.GetDailyCondition(forecast.icon);

            return new Weather(condition, temperature);
        }
        static void Main(string[] args)
        {
            var request = new ForecastIORequest("Your ForecastIO API Key", 45.292f, -75.896f, Unit.si); // Set your location by inputting a longitude/latitude coordinate
            var response = request.Get();

            string temp = Math.Round(response.currently.temperature, 1).ToString();
            string time = response.currently.time.ToDateTime().ToLocalTime().ToShortTimeString().ToString(); //unix timestamp converted to local time

            string AccountSid = "Your Twilio AccountSid Key";
            string AuthToken = "Your Twilio AuthToken Key";
 
            var twilio = new TwilioRestClient(AccountSid, AuthToken);
            var message = twilio.SendMessage("Your Twilio Generated Number", "Your Personal Phone Number","TIME: " + time + " WEATHER: " + temp + " degrees", "");
 
            if (message.RestException != null)
            {
                var error = message.RestException.Message;
                Console.WriteLine(error);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            this.configuration = PackageHost.GetSettingAsConfigurationSection <ForecastIOConfigurationSection>("forecastIOConfigurationSection", true);

            int nbSeconde = 0;

            Task.Factory.StartNew(() =>
            {
                while (PackageHost.IsRunning)
                {
                    if (nbSeconde == 0)
                    {
                        foreach (StationElement station in this.configuration.Stations)
                        {
                            PackageHost.WriteInfo("Getting forecast for {0}", station.Name);
                            try
                            {
                                ForecastIOResponse response = new ForecastIORequest(this.configuration.ApiKey, (float)station.Latitude, (float)station.Longitude, this.configuration.Unit, this.configuration.Language).Get();
                                PackageHost.PushStateObject <ForecastIOResponse>(station.Name, response, lifetime: (int)this.configuration.RefreshInterval.TotalSeconds * 2);
                                PackageHost.WriteInfo("Weather for {0} done. Report date @ {1}", station.Name, response.currently.time.ToDateTime().ToLocalTime().ToLongTimeString());
                            }
                            catch (Exception ex)
                            {
                                PackageHost.WriteError("Unable to get the weather for {0} : {1}", station.Name, ex.Message);
                            }
                        }
                    }
                    Thread.Sleep(1000);
                    nbSeconde++;

                    if (nbSeconde == (int)this.configuration.RefreshInterval.TotalSeconds)
                    {
                        nbSeconde = 0;
                    }
                }
            });
        }
        public object GetWeather(double dLatitude = 47.4886, double dLongitude = -117.5786)
        {
            Debug.WriteLine(GetType().FullName + "." + MethodBase.GetCurrentMethod().Name);

            //NOTE:
            //The first thousand API calls you make every day are free, period.
            //Every API call after that costs $0.0001 each.
            //Credit us with a “Powered by Forecast” badge that links to http://forecast.io/ wherever you display data from the API.
            //https://api.forecast.io/forecast/ec8fab02bc1bf58c04e74c58bc2c3525/47.4886,-117.5786

            //https://github.com/f0xy/forecast.io-csharp  // API Key, Lat, Long, Unit
            var request = new ForecastIORequest("ec8fab02bc1bf58c04e74c58bc2c3525", (float)dLatitude, (float)dLongitude, Unit.us);
            var response = request.Get();

            var strSummary = response.daily.summary;
            var currently = response.currently;

            List<DailyForecast> tempList = new ListStack<DailyForecast>();
            tempList.AddRange(response.daily.data);
            if (!tempList.Any())
                return new HttpResponseException(HttpStatusCode.BadRequest);

            //Ember Data expects a JSon array and an id in all returns
            const int id = 1;
            var currentWeather = new { currently.summary, currently.icon, currently.temperature };
            var dailyWeather =
                tempList.AsQueryable()
                    .Select(
                        x =>
                            new
                            {
                                x.summary,
                                x.icon,
                                x.temperatureMin,
                                x.temperatureMinTime,
                                x.temperatureMax,
                                x.temperatureMaxTime
                            })
                    .ToList();

            var data = new { id, strSummary, currentWeather, dailyWeather };
            var weatherItems = new List<object>() { data }.AsEnumerable();

            return new { weatherItems };
        }
 public IWeatherData GetWeatherData(IToponymData toponym)
 {
     var request = new ForecastIORequest(_apiKey, (float)toponym.Latitude, (float)toponym.Longitude, Unit.si);
     var response = request.Get();
     return new ForecastWeatherData(response);
 }
        // Get Forecast information for a location using "Forecast.io" API
        // We are using Forecast.io.45 wrapper library to contact Forecast.io API
        public WeatherModel GetForecast(float lat, float lon)
        {
            // ForecastIORequest(API key, lat, lon, measurement unit)
            var request = new ForecastIORequest("d1d02d9b39d4125af3216ea665368a5c", lat, lon, Unit.us);
            var response = request.Get();

            WeatherModel weather = new WeatherModel(response);
            return weather;
        }
Beispiel #10
0
        public WeatherModel GetLocalForecast(float lat, float lon)
        {
            var request = new ForecastIORequest("d1d02d9b39d4125af3216ea665368a5c", lat, lon, Unit.us);
            var response = request.Get();

            WeatherModel weather = new WeatherModel(response);
            return weather;
        }
        private async Task GetWeatherInfo(ForecastDevice device, CancellationToken cancellationToken)
        {
            var latitude = (float)device.Latitude;
            var longitude = (float)device.Longitude;
            ForecastIOResponse response;

            try
            {
                var request = new ForecastIORequest(_apiKey, latitude, longitude, Unit.si);
                response = _policy.Execute(() => request.Get());
            }
            catch (WebException)
            {
                return;
            }
            catch (Exception e)
            {
                _log.Error(e.Message, e);
                return;
            }

            UpdateVariables(device.Id, string.Empty, response.currently);

            for (var hour = 0; hour < response.hourly.data.Count; hour++)
            {
                var data = response.hourly.data[hour];
                UpdateVariables(device.Id, $"H+{hour}_", data);
            }

            for (var day = 0; day < response.daily.data.Count; day++)
            {
                var data = response.daily.data[day];
                UpdateVariables(device.Id, $"D+{day}_", data);
            }

            await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).ContinueWith(_ => { });
        }
Beispiel #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.Locations))
            {

                if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
                {
                    HttpContext.Current.Cache.Remove("ForecastCache");
                }
                else
                {
                    var responses = new List<Utility.ForecastMyProperty>();

                    if (HttpContext.Current.Cache["ForecastCache"] != null)
                    {
                        responses = (List<Utility.ForecastMyProperty>)HttpContext.Current.Cache["ForecastCache"];
                    }
                    else
                    {
                        var settings = this.GetLocationsLatitude(this.Locations);

                        foreach (var setting in settings.Keys)
                        {
                            var value = settings[setting];
                            var request = new ForecastIORequest(APIKey, value.Lat, value.Long, value.DisplayName, Unit.si);
                            var response = request.Get();
                            responses.Add(new Utility.ForecastMyProperty()
                            {
                                timezone = value.DisplayName,
                                temperature = Convert.ToInt32(response.currently.temperature),
                                icon = response.currently.icon
                            });
                        }

                       HttpContext.Current.Cache.Add("ForecastCache", responses, null, DateTime.Now.AddSeconds(Convert.ToDouble(this.CacheLifetime)), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                    }

                    rptForecast.DataSource = responses;
                    rptForecast.DataBind();
                }
            }
        }
Beispiel #13
0
        private ForecastIOResponse GetWeatherInfo(string address, DateTime dateTime)
        {
            // Get Latitude and Longitude for given address
            Address addressInfo = GetGeoInfo(address);
            ForecastIOResponse response = null;

            // If the address was found (had Latitude and Longitude)
            if (addressInfo != null)
            {
                // Get weather info from forecast API
                ForecastIORequest request = new ForecastIORequest(_weatherApiKey, Convert.ToSingle(addressInfo.Coordinates.Latitude), Convert.ToSingle(addressInfo.Coordinates.Longitude), dateTime, Unit.us);
                response = request.Get();
            }

            return response;
        }
Beispiel #14
0
        private ForecastIOResponse GetWeatherInfo(string address, bool extendHourly)
        {
            // Get Latitude and Longitude for given address
            Address addressInfo = GetGeoInfo(address);
            ForecastIOResponse response = null;

            // If the address was found (had Latitude and Longitude)
            if (addressInfo != null)
            {
                ForecastIORequest request;
                if (extendHourly)
                {
                    Extend[] extendBlocks = new Extend[]
                    { Extend.hourly };
                    request = new ForecastIORequest(_weatherApiKey, Convert.ToSingle(addressInfo.Coordinates.Latitude), Convert.ToSingle(addressInfo.Coordinates.Longitude), Unit.us, extendBlocks);
                    response = request.Get();
                }
                else
                {
                    // Get weather info from forecast API
                    request = new ForecastIORequest(_weatherApiKey, Convert.ToSingle(addressInfo.Coordinates.Latitude), Convert.ToSingle(addressInfo.Coordinates.Longitude), Unit.us);
                    response = request.Get();
                }
            }

            return response;
        }
Beispiel #15
0
 /// <summary>
 /// Gets the weather from the ForecastIO Api
 /// </summary>
 /// <returns>api object: ForecastIOResponse</returns>
 public ForecastIOResponse GetWeather()
 {
     try
     {
         //My API Key    5e0d94d071dee1b6acb0ad259cc54b1b
         // 55.395833f, 10.388611f these are the coordinates
         // for Odense
         var req = new ForecastIORequest("5e0d94d071dee1b6acb0ad259cc54b1b", 55.395833f, 10.388611f, DateTime.Now, Unit.si);
         var response = req.Get();
         var currentTemp = response.currently.apparentTemperature;
         // retrieve houes between 0 - 23
         return response;
     }
     catch (Exception)
     {
         ForecastIOResponse io = new ForecastIOResponse();
         return io;
     }
 }
        // Retrieves weather from forecast.io and populates the model
        private WeatherModel GetForecastIO(float lat, float lon, string formattedAddress)
        {
            var request = new ForecastIORequest("d1d02d9b39d4125af3216ea665368a5c", lat, lon, Unit.us);
            var response = request.Get();

            WeatherModel weather = new WeatherModel(response, formattedAddress);
            return weather;
        }