protected void GetWeatherInfo(object sender, EventArgs e)
    {
        string appId = "159d0d438da2af04cfa485a55f79319b";
        string url   = string.Format("http://api.openweathermap.org/data/2.5/forecast/daily?q={0}&units=metric&cnt=1&APPID={1}", txtCity.Text.Trim(), appId);

        using (WebClient client = new WebClient())
            try
            {
                string json = client.DownloadString(url);

                WeatherInfo weatherInfo = (new JavaScriptSerializer()).Deserialize <WeatherInfo>(json);
                lblCity_Country.Text    = weatherInfo.city.name + ", " + weatherInfo.city.country;
                imgCountryFlag.ImageUrl = string.Format("http://openweathermap.org/images/flags/{0}.png", weatherInfo.city.country.ToLower());
                lblDescription.Text     = weatherInfo.list[0].weather[0].description;
                imgWeatherIcon.ImageUrl = string.Format("http://openweathermap.org/img/w/{0}.png", weatherInfo.list[0].weather[0].icon);
                lblTempMin.Text         = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.min, 1));
                lblTempMax.Text         = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.max, 1));
                lblTempDay.Text         = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.day, 1));
                lblTempNight.Text       = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.night, 1));
                lblHumidity.Text        = weatherInfo.list[0].humidity.ToString();
                tblWeather.Visible      = true;
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
            }
    }
        static void Main(string[] args)
        {
            YandexSeleniumReader reader = new YandexSeleniumReader(WeatherSource.YC);
            //var reader = new YandexFileReaderWriter(WeatherSource.YC);
            var yandex = new YandexWeatherExtractor(reader);

            var w = new WeatherInfo();

            yandex.get_current_weather(w);

            var forecast = new Dictionary <WeatherPeriod, WeatherInfo>();

            yandex.get_forecast(forecast);

            //for (double lat = -80.03; lat < 0; lat += 3.018)
            //{
            //  for (double lon = -180.02; lon < 170; lon += 3.046)
            //  {
            //    reader.SetLocation(lat, lon);

            //    yandex.get_current_weather(new WeatherInfo());
            //    yandex.get_forecast(new Dictionary<WeatherPeriod, WeatherInfo>());
            //  }
            //}


            //yandex.get_nsu_current_temp(w);

            reader.close();
        }
        public WeatherInfo GetWeather(string city)
        {
            int         retries = 0;
            WeatherInfo info    = null;

            do
            {
                try
                {
                    info = _provider.GetWeather(city);
                }
                catch (Exception)
                {
                    if (retries == _maxTries)
                    {
                        throw;
                    }
                    else
                    {
                        Thread.Sleep(_waitingTime);
                    }
                }
            } while (++retries <= _maxTries);

            return(info);
        }
Example #4
0
        public static void UpdateTemp(WeatherInfo wInfo)
        {
            Temperature temp = new Temperature();

            temp.min      = wInfo.list[0].temp.min;
            temp.max      = wInfo.list[0].temp.max;
            temp.day      = wInfo.list[0].temp.day;
            temp.night    = wInfo.list[0].temp.night;
            temp.morn     = wInfo.list[0].temp.morn;
            temp.eve      = wInfo.list[0].temp.eve;
            temp.dateTime = wInfo.list[0].dt;
            temp.cityId   = wInfo.city.id;

            using (DefaultConnection cn = new DefaultConnection())
            {
                /*int dt = wInfo.list[0].dt;
                 * bool dateExist = cn.Temperatures.Any(d => d.dateTime.Equals(dt));
                 * if (dateExist)
                 * {}
                 * else
                 * {*/
                cn.Temperatures.Add(temp);
                cn.SaveChanges();
                // }
            }
        }
Example #5
0
        public WeatherInfo GetWeatherInfo()
        {
            City2 city = new City2();

            city.name = "zaria";
            string appId = "53a1ac331bbef7a7bb2799ab4f25f091";
            string url   = string.Format("http://api.openweathermap.org/data/2.5/forecast/daily?q={0}&units=metric&cnt=1&APPID={1}", city.name, appId);

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                try
                {
                    string json = client.DownloadString(url);

                    weatherInfo = (new JavaScriptSerializer()).Deserialize <WeatherInfo>(json);

                    UpdateTemp(weatherInfo);
                    UpdateHumid(weatherInfo);
                    UpdateWeather(weatherInfo);
                    UpdateLWD(weatherInfo);
                }
                catch (Exception)
                {}
                return(weatherInfo);
            }
        }
Example #6
0
        public List <WeatherForecast> GetTodayWeather()
        {
            List <WeatherForecast> model = new List <WeatherForecast>();

            weatherInfo = GetWeatherInfo();
            if (weatherInfo != null)
            {
                model.Add(new WeatherForecast()
                {
                    Temp        = (weatherInfo.list[0].temp.max + weatherInfo.list[0].temp.max) / 2.00,
                    Humid       = weatherInfo.list[0].humidity,
                    WeatherIcon = weatherInfo.list[0].weather[0].icon.ToString(),
                    WeatherMain = weatherInfo.list[0].weather[0].main.ToString(),
                    City        = weatherInfo.city.name.ToString(),
                    Date        = ConvertDate(weatherInfo.list[0].dt)
                });
            }
            else
            {
                var dbTemp = db.Temperatures.OrderByDescending(t => t.dateTime).FirstOrDefault();

                model.Add(new WeatherForecast()
                {
                    Temp        = (dbTemp.max + dbTemp.max) / 2.00,
                    Humid       = db.Humidities.OrderByDescending(h => h.dateTime).FirstOrDefault().value,
                    WeatherIcon = db.Weathers.OrderByDescending(w => w.dateTime).FirstOrDefault().icon,
                    WeatherMain = db.Weathers.OrderByDescending(w => w.dateTime).FirstOrDefault().main,
                    City        = db.Cities.OrderByDescending(c => c.cityId).FirstOrDefault().name,
                    Date        = ConvertDate(db.Weathers.OrderByDescending(
                                                  w => w.dateTime).FirstOrDefault().dateTime)
                });
            }
            return(model);
            //return PartialView(model);
        }
        static void Main(string[] args)
        {
            var weatherData             = new WeatherData();
            var currentConditionsReport = new CurrentConditionsReport();
            var statisticsReport        = new StatisticReport();

            weatherData.Register(currentConditionsReport);
            weatherData.Register(statisticsReport);

            var weatherInfo = new WeatherInfo()
            {
                Temperature = 10, Humidity = 15, Pressure = 30
            };

            weatherData.UpdateWeatherInfo(weatherInfo);

            Console.WriteLine(currentConditionsReport.MakeReport() + "\n\n");
            Console.WriteLine(statisticsReport.MakeReport() + "\n\n");

            weatherInfo.Temperature = -10;
            weatherInfo.Humidity    = 3;
            weatherInfo.Pressure    = 87;
            weatherData.UpdateWeatherInfo(weatherInfo);

            Console.WriteLine(currentConditionsReport.MakeReport() + "\n\n");
            Console.WriteLine(statisticsReport.MakeReport() + "\n\n");
        }
Example #8
0
        private void UpdateWeatherInfoView(WeatherInfo weatherInfo = null)
        {
            try
            {
                if (!Looper.MainLooper.IsCurrentThread)
                {
                    RunOnUiThread(delegate { UpdateWeatherInfoView(weatherInfo); });
                    return;
                }

                TextView cloudsText = FindViewById <TextView>(Resource.Id.clouds_text);
                TextView tempText   = FindViewById <TextView>(Resource.Id.temp_text);

                if (weatherInfo == null)
                {
                    cloudsText.Text = "...";
                    tempText.Text   = "...";
                }
                else
                {
                    cloudsText.Text = weatherInfo.Clouds.HasValue
                        ? weatherInfo.Clouds.Value.ToString() + "%"
                        : "N/A";
                    tempText.Text = weatherInfo.Temperature.HasValue
                        ? (weatherInfo.Temperature.Value - 273.15).ToString() + "°C"
                        : "N/A";
                }
            }
            catch (Exception e)
            {
                Log.Error(ToString(), e.ToString());
            }
        }
Example #9
0
        /// <summary>
        /// This method will insert sample data in the Database
        /// </summary>
        /// <param name="context"></param>
        private static void SeedData(DataContext context)
        {
            bool doesDatabaseExist = context.Database.EnsureCreated();

            if (context.WeatherInfos.Any())
            {
                return;
            }

            var weatherInfos = new WeatherInfo[]
            {
                new WeatherInfo {
                    InfoDate = DateTime.Parse("2018-06-24"), TemperatureC = 32, Summary = "Scorching"
                },
                new WeatherInfo {
                    InfoDate = DateTime.Parse("2018-06-25"), TemperatureC = 45, Summary = "Mild"
                },
                new WeatherInfo {
                    InfoDate = DateTime.Parse("2018-06-26"), TemperatureC = -4, Summary = "Mild"
                },
                new WeatherInfo {
                    InfoDate = DateTime.Parse("2018-06-27"), TemperatureC = 16, Summary = "Balmy"
                },
                new WeatherInfo {
                    InfoDate = DateTime.Parse("2018-06-28"), TemperatureC = 53, Summary = "Hot"
                }
            };

            foreach (WeatherInfo wi in weatherInfos)
            {
                context.WeatherInfos.Add(wi);
            }
            context.SaveChanges();
        }
Example #10
0
        public async Task FetchCurrentWeather()
        {
            try
            {
                var location = await Geolocation.GetLastKnownLocationAsync();

                var weatherInfo = await _weatherApiManager.GetWeatherInfo(location?.Latitude.ToString(), location?.Longitude.ToString());

                CurrentDayWeatherReport = new WeatherInfo
                {
                    Date        = weatherInfo.Date,
                    FeelsLike   = weatherInfo.FeelsLike,
                    Description = weatherInfo.Description,
                    Humidity    = weatherInfo.Humidity,
                    Location    = weatherInfo.Location,
                    SkyStatus   = weatherInfo.SkyStatus,
                    Temp        = weatherInfo.Temp,
                    WindInfo    = weatherInfo.WindInfo
                };
                UserLocation = new Place
                {
                    Description = CurrentDayWeatherReport.Location,
                    Latitude    = location.Latitude,
                    Longitude   = location.Longitude
                };
            }
            catch (Exception ex)
            {
                await HandleError(ex);
            }
        }
Example #11
0
 public void OnUpdate(WeatherInfo weather)
 {
     if (updates != null)
     {
         updates(weather);
     }
 }
Example #12
0
        public ActionResult WeatherDataCompleted(WeatherInfo weatherInfo, bool isCache)
        {
            JsonResult result = null;

            if (HasError())
            {
                return(ProcessError());
            }

            if (!isCache)
            {
                lock (WeatherCacheName)
                {
                    if (HttpContext.Cache[WeatherCacheName] == null)
                    {
                        DateTime now       = DateTime.Now;
                        int      hour      = 1;
                        DateTime timePoint = DateTime.Parse(now.ToString("yyyy-MM-dd HH:00:00")).AddHours(hour);
                        HttpContext.Cache.Insert(WeatherCacheName, weatherInfo, null, timePoint, Cache.NoSlidingExpiration);
                    }
                }
            }
            if (weatherInfo == null)
            {
                result = new JsonResult();
            }
            else
            {
                result = Json(weatherInfo);
            }
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return(result);
        }
        public string GetWeatherIcon(WeatherInfo weatherInfo)
        {
            string weatherIcon = "";

            weatherInfo.Weather.ForEach(w => { weatherIcon = w.Icon; });
            return(ImgBaseurl + $"{weatherIcon}.png");
        }
Example #14
0
        public WeatherInfo GetWeatherInfo(double lat, double lon)
        {
            WeatherReport weatherReport = new WeatherReport();

            var client = new RestClient(uriString);

            var request = new RestRequest("/weather", Method.GET);

            request.RequestFormat = DataFormat.Json;

            request.AddParameter("lat", lat);
            request.AddParameter("lon", lon);

            IRestResponse <WeatherReport> response = client.Execute <WeatherReport>(request);

            weatherReport = response.Data;

            WeatherInfo weatherInfo = new WeatherInfo();

            if (weatherReport != null)
            {
                weatherInfo.TemperatureDegF = weatherReport.KelvinToDegF(weatherReport.main.temp);
                weatherInfo.LastUpdate      = weatherReport.LongToDateTime(weatherReport.dt);
                if (weatherReport.weather.Count > 0)
                {
                    weatherInfo.Conditions   = weatherReport.weather[0].description;
                    weatherInfo.IconName     = weatherReport.IconToIconName(weatherReport.weather [0].icon);
                    weatherInfo.IconURL      = weatherReport.IconToUrl(weatherReport.weather[0].icon);
                    weatherInfo.LocationName = weatherReport.name;
                }
            }

            return(weatherInfo);
        }
Example #15
0
        private async Task WriteToFile(WeatherInfo info)
        {
            var infoText = $"{info.ServiceName}," +
                           $"{info.City}," +
                           $"{info.Date}," +
                           $"{info.Humidity}," +
                           $"{info.Pressure}," +
                           $"{info.Temp}," +
                           $"{info.WindSpeed}" +
                           Environment.NewLine;

            if (!File.Exists("result.csv"))
            {
                infoText = $"ServiceName," +
                           $"City," +
                           $"Date," +
                           $"Humidity," +
                           $"Pressure," +
                           $"Temp," +
                           $"WindSpeed" +
                           Environment.NewLine +
                           infoText;
            }

            await File.AppendAllTextAsync("result.csv", infoText);
        }
 public TelemetrySnapshot(DriverInfo playerInfo, WeatherInfo weatherInfo, InputInfo inputInfo, SimulatorSourceInfo simulatorSourceInfo)
 {
     PlayerData          = playerInfo;
     WeatherInfo         = weatherInfo;
     InputInfo           = inputInfo;
     SimulatorSourceInfo = simulatorSourceInfo;
 }
Example #17
0
        private static void AddCurrentWeather(WeatherInfo model, AdaptiveCard card)
        {
            var current = new AdaptiveColumnSet();

            card.Body.Add(current);

            var currentColumn = new AdaptiveColumn();

            current.Columns.Add(currentColumn);
            currentColumn.Width = "35";

            var currentImage = new AdaptiveImage();

            currentColumn.Items.Add(currentImage);
            currentImage.Url = new Uri(GetIconUrl(model.current.condition.icon));

            var currentColumn2 = new AdaptiveColumn();

            current.Columns.Add(currentColumn2);
            currentColumn2.Width = "65";

            string date = DateTime.Parse(model.current.last_updated).DayOfWeek.ToString();

            AddTextBlock(currentColumn2, $"{model.location.name} ({date})", AdaptiveTextSize.Large, false);
            AddTextBlock(currentColumn2, $"{model.current.temp_f.ToString().Split('.')[0]}° F", AdaptiveTextSize.Large);
            AddTextBlock(currentColumn2, $"{model.current.condition.text}", AdaptiveTextSize.Medium);
            AddTextBlock(currentColumn2, $"Winds {model.current.wind_mph} mph {model.current.wind_dir}", AdaptiveTextSize.Medium);
        }
Example #18
0
        public WeatherInfo updateWeatherInfo(string town)
        {
            loader.town = town;
            weather     = parser.parse(loader.load());

            return(weather);
        }
Example #19
0
        private static async Task <Attachment> GetWeatherCard(Activity activity)
        {
            var         desLocationInfo = JsonConvert.DeserializeObject <WeatherActionDetails>(activity.Value.ToString());
            WeatherInfo weatherinfo     = WeatherHelper.GetWeatherInfo(desLocationInfo.City);

            return(await CardHelper.GetWeatherCard(weatherinfo, desLocationInfo.Date));
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            ConditionCityTextBlock.Text = null;
            ConditionImage.Source       = null;
            ConditionTextBlock.Text     = null;
            TemperatureTextBlock.Text   = null;

            logger.LogDebug("Getting weather condition for {ZipCode}, {Country}...", ZipCodeTextBox.Text, CountryTextBox.Text);

            var httpClient = httpClientFactory.CreateClient("openweathermap");

            using var weatherResponse = await httpClient.GetAsync($"weather?zip={ZipCodeTextBox.Text},{CountryTextBox.Text}&units=metric&APPID={settings.OpenWeatherMapApiKey}");

            if (weatherResponse.IsSuccessStatusCode)
            {
                logger.LogInformation("Weather condition for {ZipCode}, {Country} retrieved", ZipCodeTextBox.Text, CountryTextBox.Text);

                var responseContent = await weatherResponse.Content.ReadAsStringAsync();

                var weather = new WeatherInfo(responseContent);

                ConditionCityTextBlock.Text = weather.CityName;
                ConditionImage.Source       = new BitmapImage(new Uri(weather.ConditionIconUrl));
                ConditionTextBlock.Text     = weather.Condition;
                TemperatureTextBlock.Text   = $"{weather.Temperature}°C";
            }
            else
            {
                logger.LogError("Unable to retrieve weather condition for {ZipCode}, {Country}. Error code: {ErrorCode}", ZipCodeTextBox.Text, CountryTextBox.Text, (int)weatherResponse.StatusCode);
                MessageBox.Show($"Unable to retrieve weather codition ({(int)weatherResponse.StatusCode}).", "Weather Client", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private string FormatWeatherInfo(WeatherInfo weatherInfo)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"--City-- \n\n");
            sb.AppendLine($"CityID: {weatherInfo.Id} \n\n");
            sb.AppendLine($"City: {weatherInfo.Name} \n\n");

            sb.AppendLine($"--Weather-- \n\n");
            weatherInfo?.Weather.ForEach(w =>
            {
                sb.AppendLine($"WeatherID: {w.Id} \n\n");
                sb.AppendLine($"Weather: {w.Main} \n\n");
                sb.AppendLine($"Description: {w.Description} \n\n");
                sb.AppendLine($"WeatherIcon: {w.Icon} \n\n");
            });

            sb.AppendLine($"--Sys-- \n\n");
            sb.AppendLine($"Country: {weatherInfo.sys.Country} \n\n");

            sb.AppendLine($"--Main-- \n\n");
            sb.AppendLine($"Temperature: {weatherInfo.Main.Temperature} \n\n");
            sb.AppendLine($"MaxTemperature: {weatherInfo.Main.MaxTemperature} \n\n");
            sb.AppendLine($"MinTemperature: {weatherInfo.Main.MinTemperature} \n\n");

            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            epoch = epoch.AddSeconds(weatherInfo.dt).ToLocalTime();
            sb.AppendLine($"--Timestamp-- \n\n");
            sb.AppendLine($"Timestamp: {epoch.ToLongTimeString()} \n\n");

            return(sb.ToString());
        }
Example #22
0
        /// <summary>
        /// Creates new weather view model
        /// </summary>
        /// <param name="weatherInfo">Weather information for the model</param>
        public WeatherModel(WeatherInfo weatherInfo)
        {
            Status = weatherInfo.Status;
            Icons  = weatherInfo.Icons;

            _temperatureCelsius = weatherInfo.Temperature;
        }
 // Start is called before the first frame update
 void Start()
 {
     currentWeather = GetWeather();
     WriteName();
     CheckSnowStatus();
     checkDayTimeStatus();
 }
    static void Main(string[] args)
    {
        var    result = new Dictionary <string, WeatherInfo>();
        string input  = null;
        Regex  regex  = new Regex(@"([A-Z]{2})([\d.]+)([A-Za-z]+)\|");

        while ((input = Console.ReadLine()) != "end")
        {
            Match matcher = regex.Match(input);

            while (matcher.Success)
            {
                string city        = matcher.Groups[1].Value;
                double temperature = double.Parse(matcher.Groups[2].Value);
                string weatherType = matcher.Groups[3].Value;

                WeatherInfo weatherInfo = new WeatherInfo();
                weatherInfo.Temperature = temperature;
                weatherInfo.WeatherType = weatherType;

                result[city] = weatherInfo;

                matcher = matcher.NextMatch();
            }
        }
        result = result.OrderBy(a => a.Value.Temperature).ToDictionary(a => a.Key, a => a.Value);

        foreach (var item in result)
        {
            Console.WriteLine($"{item.Key} => {item.Value.Temperature:f2} => {item.Value.WeatherType}");
        }
    }
Example #25
0
        /// <summary>
        /// 获取城市天气信息
        /// </summary>
        /// <param name="cityId">天气城市代号</param>
        /// <returns>返回城市天气信息,参数无法解析会返回null</returns>
        public WeatherInfo GetWeatherInfo(string cityId)
        {
            string  getUrl        = string.Format("http://www.weather.com.cn/data/cityinfo/{0}.html", cityId);
            JObject weatherResult = SimulateRequest.HttpGet <JObject>(getUrl);
            string  weatherStr    = weatherResult["weatherinfo"]?.ToString();

            if (!string.IsNullOrWhiteSpace(weatherStr))
            {
                ClimateInfo climate = JsonConvert.DeserializeObject <ClimateInfo>(weatherStr);
                if (climate != null)
                {
                    WeatherInfo weatherSky = new WeatherInfo()
                    {
                        CityId      = climate.cityid,
                        CityName    = climate.city,
                        TempMin     = climate.temp1,
                        TempMax     = climate.temp2,
                        WeatherDesc = climate.weather,
                        WindImg1    = climate.img1,
                        WindImg2    = climate.img2,
                        Time        = climate.ptime
                    };
                }
            }
            return(null);
        }
Example #26
0
        static void Main(string[] args)
        {
            var regex  = new Regex(@"(?<city>[A-Z]{2})(?<temp>\d+\.\d+)(?<weather>[a-zA-z]+)\|");
            var cities = new Dictionary <string, WeatherInfo>();
            var input  = Console.ReadLine();

            while (input != "end")
            {
                var weatherMatch = regex.Match(input);
                if (!weatherMatch.Success)
                {
                    input = Console.ReadLine();
                    continue;
                }

                var city    = weatherMatch.Groups["city"].Value;
                var temp    = double.Parse(weatherMatch.Groups["temp"].Value);
                var weather = weatherMatch.Groups["weather"].Value;

                var weatherInfo = new WeatherInfo
                {
                    AverageTemp = temp,
                    Weather     = weather
                };

                cities[city] = weatherInfo;

                input = Console.ReadLine();
            }
            foreach (var city in cities.OrderBy(a => a.Value.AverageTemp))
            {
                Console.WriteLine($"{city.Key} => {city.Value.AverageTemp:f2} => {city.Value.Weather}");
            }
        }
Example #27
0
    private void Start()
    {
        Debug.Log("hey");
        WeatherInfo x = GetWeather();

        Debug.Log(x.name);
    }
Example #28
0
        private static long ActualizeWeather(CityInfo city, DateTime date, WeatherInfo weather, MySqlConnection cn)
        {
            var wthrid = cn.QueryFirstOrDefault <long?>("select id from weather where cityname = @name and day = @day",
                                                        new { name = city.Name, day = date.Date });

            if (wthrid.HasValue)
            {
                cn.Execute("update weather set data = @data, day = @day, importdate = @impdt, cityouterid = @oid, cityname = @cname where id = @id",
                           new
                {
                    data  = JsonConvert.SerializeObject(weather),
                    id    = wthrid.Value,
                    day   = date.Date,
                    impdt = DateTime.UtcNow,
                    oid   = city.OuterId,
                    cname = city.Name,
                });
            }
            else
            {
                wthrid = cn.QueryFirst <long>("insert into weather (data, day, importdate, cityouterid, cityname) " +
                                              " values (@data, @day, @impdt, @oid, @cname); " +
                                              " SELECT LAST_INSERT_ID();",
                                              new
                {
                    data  = JsonConvert.SerializeObject(weather),
                    day   = date.Date,
                    impdt = DateTime.UtcNow,
                    oid   = city.OuterId,
                    cname = city.Name,
                });
            }
            return(wthrid.Value);
        }
Example #29
0
        public static WeatherInfo getWeatherInfo(string ZipCode)
        {
            string html = WebZap.ObtainWebPage("http://www.weather.com/weather/local/" + ZipCode);

            WeatherInfo info = new WeatherInfo(ZipCode);

            info.Temp = int.Parse(WebZap.getHTML(html, "<TD VALIGN=\"MIDDLE\" ALIGN=\"CENTER\" CLASS=\"obsTempTextBlue\"><B>", "&deg;F"));
            info.Text = WebZap.getHTML(html, "<TD VALIGN=\"TOP\" ALIGN=\"CENTER\" CLASS=\"obsTextBlue\"><B>", "</B></TD>").Trim();
            info.ImgSrc = WebZap.getHTML(html, "<!-- insert wx icon --><img src=\"", "\" ");
            info.FeelsLike = int.Parse(WebZap.getHTML(html, "<!-- insert feels like temp -->", "&deg;F"));
            info.UVIndex = WebZap.getHTML(html, "<!-- insert UV number -->", "</td>");
            info.Wind = WebZap.getHTML(html, "<!-- insert wind information -->", "</td>");
            info.DewPoint = int.Parse(WebZap.getHTML(html, "<!-- insert dew point -->", "&deg;F"));
            info.Humidity = int.Parse(WebZap.getHTML(html, "<!-- insert humidity -->", " %</td>"));
            info.Visibility = WebZap.getHTML(html, "<!-- insert visibility -->", "</td>");
            info.City = WebZap.getHTML(html, "Local Weather - ", " (" + ZipCode);
            info.ReportedBy = WebZap.getHTML(html, "<!-- insert reported by and last updated info -->as reported at ", ".&nbsp;&nbsp;");
            info.LastUpdated = WebZap.getHTML(html, ".&nbsp;&nbsp;Last Updated ", " (", ")");
            info.Barometer = WebZap.getHTML(html, "<!-- insert barometer information -->", "</td>");

            int after = 0;
            for (int r = 0; r < 10; r++)
            {
                if (r < 2) info.Forcast[r].Date = WebZap.getHTML(html, ref after, "<!-- insert load change day/date here -->", "   ", "</A>") + " " + WebZap.getHTML(html, ref after, "<BR>", "   ");
                else info.Forcast[r].Date = WebZap.getHTML(html, ref after, "<!-- insert no link day name here -->\n               ", "<B").Trim() + " " + WebZap.getHTML(html, ref after, "R>", "\n");
                info.Forcast[r].ImgSrc = WebZap.getHTML(html, ref after, "  <IMG SRC=\"", "\" ");
                info.Forcast[r].Text = WebZap.getHTML(html, ref after, "ALT=\"", "\">");
                info.Forcast[r].High = int.Parse(WebZap.getHTML(html, ref after, "      &nbsp;\n      \n      ", "&deg;F").Trim());
                info.Forcast[r].Low = int.Parse(WebZap.getHTML(html, ref after, "      &nbsp;\n      ", "&deg;F").Trim());
                info.Forcast[r].UVIndex = WebZap.getHTML(html, ref after, "UV Index:&nbsp;", "\n");
            }

            return info;
        }
Example #30
0
        public Form1()
        {
            InitializeComponent();
            jsondata = getJson(" https://opendata.cwb.gov.tw/api/v1/rest/datastore/O-A0003-001?Authorization=rdec-key-123-45678-011121314");
            foreach (JObject data in jsondata)
            {
                WeatherInfo wInfo = new WeatherInfo();
                wInfo.city     = (string)data["parameter"][0]["parameterValue"];
                wInfo.town     = (string)data["parameter"][2]["parameterValue"];
                wInfo.dateTime = (string)data["time"]["obsTime"];
                wInfo.temp     = (string)data["weatherElement"][3]["elementValue"];
                wInfo.tempH    = (string)data["weatherElement"][14]["elementValue"];
                wInfo.tempL    = (string)data["weatherElement"][16]["elementValue"];
                wInfo.uvi      = (string)data["weatherElement"][13]["elementValue"];
                wInfo.wdsd     = (string)data["weatherElement"][2]["elementValue"];
                wInfo.humd     = (string)data["weatherElement"][4]["elementValue"];
                addWeatherInfo(wInfo);

                city.Add((string)data["parameter"][0]["parameterValue"]);
                town.Add((string)data["parameter"][2]["parameterValue"]);
                dateTime.Add((string)data["time"]["obsTime"]);
                temp.Add((string)data["weatherElement"][3]["elementValue"]);
                tempH.Add((string)data["weatherElement"][14]["elementValue"]);
                tempL.Add((string)data["weatherElement"][16]["elementValue"]);
                uvi.Add((string)data["weatherElement"][13]["elementValue"]);
                wdsd.Add((string)data["weatherElement"][2]["elementValue"]);
                humd.Add((string)data["weatherElement"][4]["elementValue"]);
            }
        }
Example #31
0
        public WeatherInfo GetForecasts(string woeid = "721943", string tempUnit = "c")
        {
            //if (String.IsNullOrWhiteSpace(woeid))
            //    woeid = "721943";

            var url    = string.Format(YahooUrlBase, woeid, tempUnit);
            var client = new HttpClient();
            var data   = client.GetStringAsync(url).Result;
            var wfc    = JsonConvert.DeserializeObject <WeatherQuery>(data);
            var info   = new WeatherInfo();

            info.Temp = wfc.query.results.channel.item.condition.temp;
            var index = 0;

            foreach (var f in wfc.query.results.channel.item.forecast)
            {
                if (index == 0)
                {
                    index++;
                    continue;
                }
                var t = f.high;
                info.ForecastMax.Add(t);
            }
            return(info);
        }
Example #32
0
        public static WeatherInfo GetWeatherByName(string name)
        {
            WeacherService.WeatherWebServiceSoapClient client=new WeatherWebServiceSoapClient();
            var w=  client.getWeatherbyCityName(name);

            WeatherInfo result=new WeatherInfo();

            return result;
        }
Example #33
0
 public WeatherInfo GetWeather(WeatherType dummyType = WeatherType.SUNNY)
 {
     if (this.isOnline)
     {
         return Oniyamma.OniyammaService.Current.GetWeather(dummyType);
     }
     var weatherInfo = new WeatherInfo();
     weatherInfo.Type = dummyType;
     return weatherInfo;
 }
Example #34
0
 public WeatherInfo GetWeatherInfo(DateTime dateValue) {
     WeatherInfo info = weatherInfoCache[dateValue] as WeatherInfo;
     if(info == null) {
         Month month = (Month)(dateValue.Month - 1);
         TemperatureRange temperature = GetRandomDayTemperature(averageMonthTemperatures[month]);
         Cloudiness cloudiness = GetRandomCloudiness();
         Rain rain = GetRandomRain(month, cloudiness);
         info = new WeatherInfo(dateValue, TemperatureUnit.Celsius, temperature.Min.Value, temperature.Max.Value,
             cloudiness, rain, GetRandomSnow(month), GetRandomFog(month), GetRandomHail(rain));
         weatherInfoCache[dateValue] = info;
     }
     return info;
 }
        public void Initialize()
        {
            // arrange
            this.serviceMock = new WeatherServiceMock();
            this.target = new OldMainViewModel(serviceMock);

            this.dummyCurrentWeather = CreateDummyCurrentWeather();
            this.dummyWeatherInfo = CreateWeatherInfo();

            this.serviceMock
                .AddHandlers()
                    .GetCurrentWeatherAsync(() => Task.FromResult(dummyCurrentWeather))
                    .GetWeatherAsync(() => Task.FromResult(dummyWeatherInfo));
        }
        public async Task StubTest()
        {
            // arange
            var service = new WeatherServiceStub();
            var dummy = new WeatherInfo();
            service
                .AddHandlers()
                    .GetCityWeatherAsync(cityName => Task.FromResult(dummy));

            // act
            var actual = await service.GetCityWeatherAsync(CityName);

            // assert
            Assert.AreEqual(dummy, actual);
        }
        public List<WeatherInfo> GetWeatherInfo(Location location)
        {
            //Create the list in which we will put all our weatherInfo objects.
            List<WeatherInfo> weatherList = new List<WeatherInfo>();

            //Create a new XML document, create the string from user input, and load the XML.
            XmlDocument xml = new XmlDocument();
            String xmlString = String.Format("http://api.openweathermap.org/data/2.5/forecast/daily?lat={0}&lon={1}&units=metric&cnt=5&lang=en&mode=xml&app_id=850cd19d2459a0c93e80bb44d19a05b2", location.Lat, location.Lng);
            xml.Load(xmlString);

            //Create a nodelist from the certain point in the XML doc we want.
            XmlNodeList xmlNodeList = xml.SelectNodes("/weatherdata/forecast/time");

            //Create weatherinfo objects.
            foreach(XmlNode item in xmlNodeList)
            {
                WeatherInfo weatherItem = new WeatherInfo();

                //Set all weatherinformation
                weatherItem.LocationID = location.LocationID;
                weatherItem.Location = location.Location1;
                weatherItem.Time = item.Attributes["day"].Value;
                weatherItem.Description = item["symbol"].Attributes["name"].Value;
                weatherItem.Icon = String.Format("http://openweathermap.org/img/w/{0}.png", item["symbol"].Attributes["var"].Value);

                //Check to see if the temperature for mid-day period exists. If not, take next one, and so on
                if (item["temperature"].Attributes["day"].Value != null)
                {
                    weatherItem.Temp = item["temperature"].Attributes["day"].Value;
                }
                else if (item["temperature"].Attributes["eve"].Value != null)
                {
                    weatherItem.Temp = item["temperature"].Attributes["eve"].Value;
                }
                else
                {
                    weatherItem.Temp = item["temperature"].Attributes["morn"].Value;
                }

                weatherList.Add(weatherItem);
            }

            return weatherList;
        }
Example #38
0
 public WeatherInfoControl(WeatherInfo info, TemperatureUnit temperatureUnit) {
     this.info = info;
     this.temperatureUnit = temperatureUnit;
 }
 private void Parse(WeatherInfo model)
 {
     this.PreviousImageResource.Value = this.resources.GetImageResource(model.Results[0].Weather[0].Icon);
     this.CurrentImageResource.Value = this.resources.GetImageResource(model.Results[1].Weather[0].Icon);
     this.NextImageResource.Value = this.resources.GetImageResource(model.Results[2].Weather[0].Icon);
     this.PreviousName.Value = this.resources.Today;
     this.CurrentName.Value = this.resources.Tomorrow;
     this.NextName.Value = this.resources.NextDay;
 }
 private void Parse(WeatherInfo model)
 {
     this.PreviousImageResource.Value = "Img" + model.Results[0].Weather[0].Icon.Replace(".png", "");
     this.CurrentImageResource.Value = "Img" + model.Results[1].Weather[0].Icon.Replace(".png", "");
     this.NextImageResource.Value = "Img" + model.Results[2].Weather[0].Icon.Replace(".png", "");
     this.PreviousName.Value = "today";
     this.CurrentName.Value = "tomorrow";
     this.NextName.Value = "next day";
 }