コード例 #1
0
        public string GetWeatherInfo(OpenWeatherModel openWeatherObj)
        {
            try
            {
                if (openWeatherObj != null && openWeatherObj.cities != null)
                {
                    string downloadPath = HttpContext.Current.Server.MapPath(Resource.OutputFolder);
                    foreach (var row in openWeatherObj.cities)
                    {
                        /*Calling API http://openweathermap.org/api */
                        string apiKey           = Resource.ApiKey;
                        string apiResponse      = string.Empty;
                        string downloadFilePath = string.Concat(downloadPath, @"\", row.Key);

                        HttpWebRequest apiRequest =
                            WebRequest.Create(string.Format(Resource.ApiUrl, row.Value, apiKey)) as HttpWebRequest;

                        using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
                        {
                            StreamReader reader = new StreamReader(response.GetResponseStream());
                            apiResponse = reader.ReadToEnd();
                        }
                        /*End*/


                        if (!string.IsNullOrEmpty(apiResponse))
                        {
                            Directory.CreateDirectory(downloadFilePath);
                            string fileName = string.Concat(downloadFilePath, @"\", DateTime.Now.ToString("MM-dd-yyyy"), ".json");
                            if (!File.Exists(fileName))
                            {
                                File.Create(fileName).Dispose();;
                                using (var tw = new StreamWriter(fileName, true))
                                {
                                    tw.WriteLine(apiResponse);
                                }
                            }
                            else if (File.Exists(fileName))
                            {
                                using (var tw = new StreamWriter(fileName, true))
                                {
                                    tw.WriteLine(apiResponse);
                                }
                            }
                        }
                    }
                    return("Files processed successfully, weather information is downloaded to 'Output' folder!");
                }
                else
                {
                    return("Unable to read city details from input file!");
                }
            }
            catch (Exception ex)
            {
                Logger.Publish(EventType.Exception, this.GetType().Name, MethodBase.GetCurrentMethod().Name.ToString(), ex.Message, ex.InnerException == null ? string.Empty : ex.InnerException.Message, ex.StackTrace);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
                throw new HttpResponseException(response);
            }
        }
コード例 #2
0
        public void TestMethod1()
        {
            OpenWeatherModel  openWeatherObj = new OpenWeatherModel();
            WeatherController controller     = new WeatherController();

            openWeatherObj.cities.Add("City of London", "2643741");
            var result = controller.GetWeatherInfo(openWeatherObj);
        }
コード例 #3
0
        public async Task <string> PostAsync()
        {
            try
            {
                if (Request.Content.IsMimeMultipartContent())
                {
                    string           uploadPath     = HttpContext.Current.Server.MapPath(Resource.UploadFolder);
                    MyStreamProvider streamProvider = new MyStreamProvider(uploadPath);
                    string           message        = string.Empty;
                    OpenWeatherModel openWeatherMdl = new OpenWeatherModel();
                    openWeatherMdl.cities = new Dictionary <string, string>();

                    await Request.Content.ReadAsMultipartAsync(streamProvider);

                    string uploadFilePath = streamProvider.GetLocalFileName(streamProvider.FileData[0].Headers);


                    //Read the contents of CSV file.
                    string csvData = File.ReadAllText(uploadFilePath);

                    //Execute a loop over the file rows and populate cities in the object.
                    foreach (string row in csvData.Split('\n'))
                    {
                        if (!string.IsNullOrEmpty(row))
                        {
                            openWeatherMdl.cities.Add(row.Split(',')[0], row.Split(',')[1].Replace("\r", ""));
                        }
                    }

                    message = GetWeatherInfo(openWeatherMdl);


                    return(message);
                }
                else
                {
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
                    throw new HttpResponseException(response);
                }
            }

            catch (Exception ex)
            {
                Logger.Publish(EventType.Exception, this.GetType().Name, MethodBase.GetCurrentMethod().Name.ToString(), ex.Message, ex.InnerException == null ? string.Empty : ex.InnerException.Message, ex.StackTrace);

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
                throw new HttpResponseException(response);
            }
        }
コード例 #4
0
        public OpenWeatherModel Get(int airportId)
        {
            AirportModel airport = new AirportModel();

            using (var connection = GetOpenConnection())
            {
                airport = connection.Query <AirportModel>(
                    @"select AirportId, AirportName, CityName, CountryName, AirportCode, Latitude, Longitude
                        from Airports where AirportId = " + airportId).FirstOrDefault();//<= TODO: use parameters
            }
            //TODO: add link to config
            string urlBase = "http://api.openweathermap.org/data/2.5/onecall?lat={0}&lon={1}&exclude=minutely,hourly,daily&APPID=6ce31626181846df8fb15eed32a345b0&units=metric";
            string url     = String.Format(urlBase, airport.Latitude, airport.Longitude);
            OpenWeatherViewModel weatherForecastViewModel = new OpenWeatherViewModel();
            string         answer;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        answer = reader.ReadToEnd();
                    }

            weatherForecastViewModel = JsonConvert.DeserializeObject <OpenWeatherViewModel>(answer);

            OpenWeatherModel model = new OpenWeatherModel();

            model = new OpenWeatherModel
            {
                CountryName            = airport.AirportName,//TODO: change property to airpirtName
                Sunrise                = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(weatherForecastViewModel.Current.Sunrise).ToLocalTime(),
                Sunset                 = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(weatherForecastViewModel.Current.Sunset).ToLocalTime(),
                Temperature            = weatherForecastViewModel.Current.Temp,
                WeatherMainDescription = weatherForecastViewModel.Current.Weather.Select(w => w.Main).Aggregate((i, j) => i + " " + j),
                Updated                = DateTime.Now,
                Icon = "http://openweathermap.org/img/wn/" + weatherForecastViewModel.Current.Weather.First()?.Icon + "@2x.png"
            };

            return(model);
        }
コード例 #5
0
        //Change to UoW method in future
        private async Task DoWork(CancellationToken stoppingToken)
        {
            _logger.LogInformation($"[{ServiceName}] Started Work");
            _watch = new Stopwatch();
            _watch.Start();
            _logger.LogInformation($"[{ServiceName}] Start Fetch Weather");
            OpenWeatherModel currentWeather = null;

            try
            {
                currentWeather = await _openWeatherApi.GetWeather(stoppingToken : stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                throw;
            }
            _logger.LogInformation($"[{ServiceName}] Finish Fetch Weather");
            _logger.LogInformation($"[{ServiceName}] Start Insert");
            var weatherEntity = new WeatherEntity
            {
                CityId     = currentWeather.id,
                CityName   = currentWeather.name,
                Conditions = currentWeather.weather.Select(s => new WeatherConditionEntity
                {
                    Description = s.description,
                    Icon        = s.icon,
                    Id          = s.id,
                    Main        = s.main
                }),
                Clouds             = currentWeather.clouds.all,
                DateTimeUtc        = DateTimeOffset.FromUnixTimeSeconds(currentWeather.dt).UtcDateTime,
                Humidity           = currentWeather.main.humidity,
                Temp               = currentWeather.main.temp,
                SunriseDateTImeUtc = DateTimeOffset.FromUnixTimeSeconds(currentWeather.sys.sunrise).UtcDateTime,
                SunsetDateTImeUtc  = DateTimeOffset.FromUnixTimeSeconds(currentWeather.sys.sunset).UtcDateTime,
            };
            await _weather.InsertOneAsync(weatherEntity, cancellationToken : stoppingToken);

            _watch.Stop();

            _logger.LogInformation($"[{ServiceName}] Finish Insert Elapsed: {_watch.ElapsedMilliseconds} ms");
        }
コード例 #6
0
        public async Task <OpenWeatherModel> GetWeather(int airportId)
        {
            OpenWeatherModel weatherForecast = new OpenWeatherModel();
            string           url             = "https://localhost:44393/openweather/" + airportId;//TODO: Move this link to config

            try
            {
                using (var httpClient = new HttpClient())
                {
                    using (var response = await httpClient.GetAsync(url))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        weatherForecast = JsonConvert.DeserializeObject <OpenWeatherModel>(apiResponse);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError("ERROR Getting WeatherForecast data from Reservation Service: " + e.Message);
            }

            return(weatherForecast);
        }