Exemple #1
0
        public string GetInformation(WeatherInformation weatherInformation)
        {
            StringBuilder stringBuilder = new StringBuilder();

            weatherInformation.Weather.ToList().ForEach(w => stringBuilder.Append($"{w.Description}, "));
            return(stringBuilder.Remove(stringBuilder.Length - 2, 2).ToString());
        }
        public void TestExtractInformationDownloadString()
        {
            WeatherInformation lWeatherInformation = new WeatherInformation(lWebAddress);

            lWeatherInformation.ExtractInfomationDownloadString();
            lWebData = lWeatherInformation.WebData;
        }
Exemple #3
0
        static async Task Main(string[] args)
        {
            WeatherGenerator   weatherGenerator   = new WeatherGenerator();
            WeatherInformation weatherInformation = await WeatherGenerator.GetWeatherfaceAsync();


            Console.SetCursorPosition(3, 2);
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.Write("Temperature: " + weatherInformation.Temperature);

            Console.SetCursorPosition(10, 5);
            Console.Write("Humidity: " + weatherInformation.Humidity);

            Console.SetCursorPosition(10, 7);
            Console.Write("Weather: " + weatherInformation.Weather);


            /*var  splitting =weatherString.Split(' ');
             * foreach (var split in splitting)
             * {
             *  var splitting1 = split.Split(':');
             *
             *  foreach (var split1 in splitting1)
             *
             *      Console.WriteLine(split1);
             *     // Console.WriteLine(split);
             * }
             */
        }
Exemple #4
0
        public Message Handle(Message message)
        {
            //TODO use Textinterpreter instead of HelperMethod + use Textinterpreter in SetCommands
            City = TextInterpreterHelper.HelperMethodReadCity(message);
            SetCommands(message);

            try
            {
                WeatherInformation result = cache.WeatherInformationIsCached(City) ? cache.Get(City) : CallWeatherApi();
                return(ResponseMessage.Ok(commands, result));
            }
            catch (CityNotFoundException)
            {
                return(ResponseMessage.CityNotFoundMessage(City));
            }
            catch (APIUnauthorizedException)
            {
                return(ResponseMessage.Unauthorized());
            }
            catch (APIErrorException)
            {
                return(ResponseMessage.APIError());
            }
            catch (UnknownErrorException)
            {
                return(ResponseMessage.UnknownError());
            }
        }
Exemple #5
0
        static async Task GetCity()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:50148/");
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    WeatherInformation weather = new WeatherInformation();
                    // GET weather/city/{name}
                    HttpResponseMessage response = await client.GetAsync("weather/city/Dublin");

                    if (response.IsSuccessStatusCode)
                    {
                        weather = await response.Content.ReadAsAsync <WeatherInformation>();

                        Console.WriteLine("*** Weather Information for specific city ***");
                        Console.WriteLine(weather.City + "\t" + weather.Temperature + "\n" + weather.Condition + "\t" + weather.Warning + "\t" + weather.WindSpeed);
                    }
                    else
                    {
                        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemple #6
0
        static async Task UpdateCity()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:50148/");
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    // PUT weather/city/Dublin
                    WeatherInformation weather = new WeatherInformation()
                    {
                        City        = "Dublin",
                        Condition   = "Storm",
                        Temperature = 5.1,
                        Warning     = true,
                        WindSpeed   = 35
                    };
                    HttpResponseMessage response = await client.PutAsJsonAsync("weather/city/Dublin", weather);

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("\n*** Updated Weather Information: Dublin ***\n");
                        Console.WriteLine(weather.City + "\t" + weather.Temperature + "\n" + weather.Condition + "\t" + weather.Warning + "\t" + weather.WindSpeed);
                    }
                    else
                    {
                        Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        public async static Task <WeatherInformation> GetWeather()
        {
            HttpClient http        = new HttpClient();
            var        ctWbService = await http.GetStringAsync("http://api.openweathermap.org/data/2.5/weather?q=Cape%20Town&APPID=f27a016865a3eed617a112811e03e4ba");

            WeatherInfo weather = JsonConvert.DeserializeObject <WeatherInfo>(ctWbService);

            /*   List<string> fullReport = new List<string>();
             *
             * for (int index = 0; index < weather.weather.Count; index++)
             * {
             *     fullReport.Add(weather.weather[index].description);
             *     fullReport.Add(weather.weather[index].id.ToString());
             *     fullReport.Add(weather.weather[index].main);
             *     fullReport.Add(weather.name[index].ToString());
             *     fullReport.Add(weather.timezone.ToString());
             *     fullReport.Add(weather.coord.lat.ToString());
             *
             * }
             */
            WeatherInformation info = new WeatherInformation();

            info.Temperature = weather.main.temp;
            info.Humidity    = weather.main.humidity;



            foreach (var n in weather.weather)
            {
                info.Weather = n.description;
            }


            return(info);
        }
        public async Task <ActionResult <string> > UpdateWeatherForAirportMethod(int airport_id)
        {
            Airport FoundAirport;

            try{
                FoundAirport = dbQuery.FindAirportWithForecastById(airport_id);
            }catch {
                JsonResponse r = new JsonResponse("Invalid Airport Id");
                return(StatusCode(400, r));
            }

            if (FoundAirport.WeatherForecast.Count > 0) //verify weather cache

            //check if less than 1 hour since last update
            {
                if (FoundAirport.WeatherForecast[0].UpdatedAt.AddHours(1) > DateTime.Now)
                {
                    //don't update cache
                    return("cache ok");
                }
            }

            WeatherInformation weather_information = new WeatherInformation(client);

            WeatherForecast airport_forecast =
                await weather_information.GetWeatherForLocation(FoundAirport.Latitude, FoundAirport.Longitude);

            airport_forecast.AirportId = FoundAirport.AirportId;
            dbQuery.AddWeatherForecast(airport_forecast);

            return("cache updated");
        }
        //Refresh condition depending on the location.
        public async void RefreshCurrentConditionAsync()
        {
            this.IsBusy       = true;
            this.NeedsRefresh = false;
            WeatherInformation result = null;

            switch (this.LocationType)
            {
            case LocationType.Location:
                if (this.Location == null)
                {
                    this.Location = await Helpers.LocationHelper.GetCurrentLocationAsync();
                }
                result = await Helpers.WeatherHelper.GetCurrentConditionsAsync(this.Location.Latitude, this.Location.Longitude);

                break;

            case LocationType.City:
                result = await Helpers.WeatherHelper.GetCurrentConditionsAsync(this.CityName, this.CountryCode);

                break;
            }

            this.CurrentCondition.Conditions     = result.Conditions;
            this.CurrentCondition.Description    = result.Description;
            this.CurrentCondition.DisplayName    = result.DisplayName;
            this.CurrentCondition.Icon           = result.Icon;
            this.CurrentCondition.Id             = result.Id;
            this.CurrentCondition.MaxTemperature = result.MaxTemperature;
            this.CurrentCondition.MinTemperature = result.MinTemperature;
            this.CurrentCondition.Temperature    = result.Temperature;
            this.CurrentCondition.Humidity       = result.Humidity;
            this.CurrentCondition.TimeStamp      = result.TimeStamp.ToLocalTime();
            this.IsBusy = false;
        }
Exemple #10
0
        private void ProcessResult(List <WeatherInformation> weatherInformation)
        {
            if (weatherInformation.Any())
            {
                StringBuilder result = new StringBuilder();

                foreach (var info in weatherInformation)
                {
                    result.AppendLine($"{info.StartTime.Year}-{info.StartTime.Month}-{info.StartTime.Day}\t{info.AverageDegrees}");
                }

                textBoxResult.Text = result.ToString();
                Clipboard.SetText(result.ToString());

                WeatherInformation latest = weatherInformation.LastOrDefault();

                if (latest != null)
                {
                    Properties.Settings.Default.LastDate = latest.StartTime.Date;
                    InitializeDates();
                }

                MessageBox.Show(
                    this,
                    "Copied results to clipboard and results tab",
                    "Temperature Data",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information,
                    MessageBoxDefaultButton.Button1);
            }
        }
        public void TestFetchFromInputWhenWrongInput()
        {
            WeatherInformation info = new WeatherInformation();

            info = requestHandler.FetchDataFromInput("daka");
            Assert.AreEqual(null, info);
        }
        public void TestFetchFromInput()
        {
            WeatherInformation info = new WeatherInformation();

            info = requestHandler.FetchDataFromInput("dhaka");
            Assert.AreEqual("Dhaka", info.name);
        }
Exemple #13
0
        public IActionResult Index()
        {
            string uri;
            var    ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();

            var ipDetails = GetUserLocationDetailsyByIp(ip);

            if (ipDetails.Longitude == null)
            {
                uri = "http://api.openweathermap.org/data/2.5/weather?q=Surrey,ca&units=metric&appid=6a918a2e7455032b8e29775f764b46df";
            }
            else
            {
                uri = openWeatherUri + "lat=" + ipDetails.Latitude + "&lon=" + ipDetails.Longitude + "&units=metric&appid=6a918a2e7455032b8e29775f764b46df";
            }

            var client = new HttpClient();

            var response = client.GetAsync(uri).Result;

            if (!response.IsSuccessStatusCode)
            {
                return(View(indexPath));
            }

            var data = response.Content.ReadAsStringAsync().Result;

            weatherInformation = JsonConvert.DeserializeObject <WeatherInformation>(data);
            return(View(indexPath, weatherInformation));
        }
Exemple #14
0
        public WeatherInformation GetCurrentWeather(Coordinates coordinates)
        {
            var url = $"http://api.openweathermap.org/data/2.5/weather?q=Pinetown&units=metric&cnt=1&APPID={apiKey}";
            // TODO: Make this dynamic, only using hard coded location for testing for the brief
            //var lat = coordinates.Lat;
            //var lon = coordinates.Lon;
            //var url = $"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&units=metric&exclude=daily&cnt=1&appid={apiKey}";

            var json         = GetRequest(url);
            var weatherStats = (new JavaScriptSerializer()).Deserialize <WeatherStats>(json);

            var weatherInformation = new WeatherInformation
            {
                Country              = weatherStats.Sys.Country,
                City                 = weatherStats.Name,
                Latitude             = Convert.ToString(weatherStats.Coord.Lat),
                Longitude            = Convert.ToString(weatherStats.Coord.Lon),
                Description          = weatherStats.Weather[0].Description,
                Humidity             = Convert.ToString(weatherStats.Main.Humidity),
                Temperature          = Convert.ToString(weatherStats.Main.Temp),
                TemperatureFeelsLike = Convert.ToString(weatherStats.Main.Feels_like),
                MaximumTemperature   = Convert.ToString(weatherStats.Main.Temp_max),
                MinimunTemperature   = Convert.ToString(weatherStats.Main.Temp_min),
                WeatherIcon          = weatherStats.Weather[0].Icon
            };

            return(weatherInformation);
        }
Exemple #15
0
        public ActionResult DeleteConfirmed(long id)
        {
            WeatherInformation weatherInformation = db.WeatherInformations.Find(id);

            db.WeatherInformations.Remove(weatherInformation);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public void ShouldGetNullIfInputIsNotInDatabase()
        {
            string apiUrl1 = requestHandler.GetApiUrl("londo");
            string result1 = requestHandler.GetJsonFromApi(apiUrl1);

            weatherInformation = JsonConvert.DeserializeObject <WeatherInformation>(result1);
            Assert.AreEqual(null, weatherInformation);
        }
Exemple #17
0
        public static Message Ok(List <ICommand> commands, WeatherInformation weatherInformation)
        {
            StringBuilder stringBuilder = new StringBuilder($"Wetter in {weatherInformation.CityName} ({weatherInformation.Date}): ");

            commands.ForEach(rs => stringBuilder.AppendLine($"{rs.GetInformation(weatherInformation)}"));

            return(new Message(stringBuilder.ToString()));
        }
        public string GetInformation(WeatherInformation weatherInformation)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append($"Es ist zu {weatherInformation.Clouds.CloudinessPercentage}% bewölkt. ");
            stringBuilder.Append($"Die Sichtweite beträgt {weatherInformation.Visibilty}m.");
            return(stringBuilder.ToString());
        }
Exemple #19
0
 public MainViewModel()
 {
     IsBusy            = true;
     NeedsRefresh      = true;
     LocationType      = LocationType.City;
     CityName          = "Amsterdam";
     CountryCode       = "HL";
     CurrentConditions = new WeatherInformation();
 }
Exemple #20
0
        public void Run()
        {
            GetInformation();
            _weatherInformation = GetofflineWeatherDatat();
            _trafficInformation = GetOfflinetraccicData();

            GenerateOutput();
            Console.ReadLine();
        }
Exemple #21
0
        public void Run()
        {
            _userInformation    = GetInformation();
            _weatherInformation = GetOfflineWeatherData();
            _trafficInformation = GetOfflineTrafficData();


            GenerateOutput();
            Console.ReadKey();
        }
Exemple #22
0
        private bool WeatherInformationIsOutdated(string city)
        {
            WeatherInformation weatherInformation = storedWeatherInformations[city];
            bool isOutdated = DateTime.Now.AddMinutes(-10) > weatherInformation.CreationDate;

            if (isOutdated)
            {
                storedWeatherInformations.Remove(city);
            }
            return(isOutdated);
        }
Exemple #23
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);
            locationInput      = FindViewById <EditText>(Resource.Id.getLocationEditText);
            locationButton     = FindViewById <Button>(Resource.Id.getLocationButton);
            weatherInformation = new WeatherInformation();

            locationButton.Click += locationButton_Click;
        }
Exemple #24
0
 public ActionResult Edit([Bind(Include = "WeatherInformationId,WebAddress,WebData,RequestData,ResponseData,WeatherDataId")] WeatherInformation weatherInformation)
 {
     if (ModelState.IsValid)
     {
         db.Entry(weatherInformation).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.WeatherDataId = new SelectList(db.WeatherDatas, "WeatherDataId", "WeatherDataId", weatherInformation.WeatherDataId);
     return(View(weatherInformation));
 }
Exemple #25
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            _plist = NSUserDefaults.StandardUserDefaults;
            var startDateEpoch = _plist.DoubleForKey("startDate");
            var endDateEpoch   = _plist.DoubleForKey("endDate");

            if (startDateEpoch > 0.0 && endDateEpoch > 0.0)
            {
                _startTime = startDateEpoch.FromUnixTime();
                _endTime   = endDateEpoch.FromUnixTime();
            }
            else
            {
                _startTime = DateTime.Now.AddDays(-7);
                _endTime   = DateTime.Now.AddDays(2);
            }
            timeLabel.Text = $"{_startTime.ToShortDateString()}-{_endTime.ToShortDateString()}";



            InitializeActivityIndicator();
            TableSource.ViewController = this;
            menuButton.Clicked        += (sender, e) => this.RevealViewController().RevealToggleAnimated(true);
            View.AddGestureRecognizer(this.RevealViewController().PanGestureRecognizer);
            var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

            ActiveStation    = appDelegate.ActiveStation;
            tableView.Source = TableSource;

            locationManager.AuthorizationChanged += (sender, args) =>
            {
                Console.WriteLine("Authorization changed to: {0}", args.Status);
            };
            locationManager.RequestWhenInUseAuthorization();
            GetAnnotationOfStation();
            if (ActiveStation != null)
            {
                WeatherInformation.GetWeatherData(double.Parse(ActiveStation.Latitude), double.Parse(ActiveStation.Longitude),
                                                  (WeatherData data) =>
                {
                    data.IconName = data.GetWeatherIcon(data.Condition);
                    InvokeOnMainThread(() =>
                    {
                        UpdateUIWeatherInformation(data);
                    });
                });
                // GetWeatherData(double.Parse(ActiveStation.Latitude), double.Parse(ActiveStation.Longitude));
            }

            InitializeDatabase();
        }
Exemple #26
0
        public static WeatherInformation GetCurrentWeatherInformation(JToken jObject)
        {
            WeatherInformation weather = new WeatherInformation();

            weather.Time        = jObject.Value <DateTime>("LocalObservationDateTime");
            weather.Icon        = jObject.Value <string>("WeatherIcon");
            weather.Title       = jObject.Value <string>("WeatherText");
            weather.Temperature = jObject.Value <JToken>("Temperature").Value <JToken>("Metric").Value <float>("Value");
            weather.IsRainy     = jObject.Value <bool>("HasPrecipitation");
            weather.CloudCover  = jObject.Value <int>("CloudCover");
            return(weather);
        }
Exemple #27
0
        private WeatherInformation ReadNextElement(SqlDataReader reader)
        {
            WeatherInformation item = new WeatherInformation();

            item.Id          = reader.GetInt16(0);
            item.RaspberryId = reader.GetString(1);
            item.Temperature = reader.GetString(2);
            item.Humidity    = reader.GetString(3);
            item.TimeStamp   = reader.GetString(4);

            return(item);
        }
        public IHttpActionResult GetCity(string name)
        {
            WeatherInformation weather = weatherList.SingleOrDefault(w => w.City.ToUpper() == name.ToUpper());

            if (weather == null)
            {
                return(NotFound());
            }
            else
            {
                return(Ok(weather));
            }
        }
Exemple #29
0
        private static string GetWeather(WeatherInformation weatherInformation)
        {
            var weatherStringBuilder = new System.Text.StringBuilder();

            weatherStringBuilder.AppendLine($"Following is weather forcast for {weatherInformation.name}\r\n");
            weatherStringBuilder.AppendLine($"Current temperature is:  {weatherInformation.main.temp} Fahrenheit\r\n");
            weatherStringBuilder.AppendLine($"Minimum Tempearature will be:  {weatherInformation.main.temp_min} Fahrenheit\r\n");
            weatherStringBuilder.AppendLine($"Maximum Tempearature will be:  {weatherInformation.main.temp_max} Fahrenheit\r\n");
            weatherStringBuilder.AppendLine($"Wind Speed will be:  {weatherInformation.wind.speed} Miles/hr\r\n");
            weatherStringBuilder.AppendLine($"Humidity will be:  {weatherInformation.main.humidity} percent\r\n");

            return(weatherStringBuilder.ToString());
        }
        public void Should_return_expected_weather_information()
        {
            // given
            RestClientStub restClientStub = new RestClientStub();
            WeatherClient weatherClient = new WeatherClient(restClientStub);
            var expectedResult = new WeatherInformation();
            restClientStub.Execute_Value = expectedResult;

            // when
            var result = weatherClient.GetWeather();

            // then
            Assert.That(result, Is.EqualTo(expectedResult));
        }
        public void ShouldGetCorrectJsonFromApi()
        {
            string apiUrl1 = requestHandler.GetApiUrl("london");
            string result1 = requestHandler.GetJsonFromApi(apiUrl1);

            weatherInformation = JsonConvert.DeserializeObject <WeatherInformation>(result1);
            Assert.AreEqual("London", weatherInformation.name);

            string apiUrl2 = requestHandler.GetApiUrl("stockholm");
            string result2 = requestHandler.GetJsonFromApi(apiUrl2);

            weatherInformation = JsonConvert.DeserializeObject <WeatherInformation>(result2);
            Assert.AreEqual("Stockholm", weatherInformation.name);
        }