public IActionResult Index() { string cityID = "3081368"; // Wroclaw string apiKey = "38832353be066e5198365b401c09da9f"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cityID + "&APPID=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); StringBuilder sb = new StringBuilder(); sb.Append("<table style=\"margin-left:auto;margin-right:auto;\">"); sb.Append("<tr><td>Location:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " m/s</td></tr>"); sb.Append("<tr><td>Temperature:</td><td>" + (int)rootObject.main.temp + "°C</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "%</td></tr>"); sb.Append("<tr><td>Pressure:</td><td>" + rootObject.main.pressure + " hPa</td></tr>"); sb.Append("<tr><td>Overcast:</td><td>" + rootObject.weather[0].description + "</td></tr>"); ViewBag.HtmlOutput = sb.ToString(); return(View()); }
public ActionResult Index() { ResponseWeather responseWeather = GetWeatherByCiti("Kyiv"); // Информция о погоде в Киеве отображается по умолчанию. //можно было бы использовать определение города по IP юзера но это коректно работает только с развернутым сайтом а не при использовании локального сервер return(View("~/Views/OpenWeatherMapMvc/Search.cshtml", responseWeather)); //вызов представления и передача модели }
public async Task <ResponseWeather> WeatherForecasts(string city) { //var rng = new Random(); //return Enumerable.Range(1, 5).Select(index => new WeatherForecast //{ // Date = DateTime.Now.AddDays(index), // TemperatureC = rng.Next(-20, 55), // Summary = Summaries[rng.Next(Summaries.Length)] //}); HttpWebRequest apiRequest = WebRequest.Create( $"http://api.openweathermap.org/data/2.5/weather?q={city}&appid=a21ff7bf210de8be6ea2214336b0c7de") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); return(rootObject); //return await _http.GetJsonAsync<ResponseWeather[]>( // $"http://api.openweathermap.org/data/2.5/weather?q={city}&appid=a21ff7bf210de8be6ea2214336b0c7de"); }
public ActionResult GetWeather(string city) { //https://samples.openweathermap.org/data/2.5/weather?q=Minsk&appid=3ddbdbaa8509490ac43f89297c044421 погода string apiKey = "3ddbdbaa8509490ac43f89297c044421"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); ViewBag.responceWeather = rootObject; TempStore.response = rootObject; TimeSpan sunrise = TimeSpan.FromMilliseconds(rootObject.sys.sunrise); TimeSpan sunset = TimeSpan.FromMilliseconds(rootObject.sys.sunset); ViewBag.sunrise = sunrise; ViewBag.sunset = sunset; return(PartialView("GetWeatherPartial")); }
private async Task <ResponseWeather> ConsumeOpenWeatherApi(string[] cities) { const string token = "eb8b1a9405e659b2ffc78f0a520b1a46"; var responseList = new ResponseWeather(); var sbLog = new StringBuilder(); foreach (var city in cities) { _restClient.BaseUrl = new Uri($"http://api.openweathermap.org/data/2.5/forecast?id={city}&APPID={token}"); var request = new RestRequest(Method.GET); var resp = await _restClient.ExecuteGetAsync <IRestResponse>(request); if (resp == null) { sbLog.AppendLine($"response is null; Request idCity: {city}"); continue; } Console.WriteLine(resp.Content); if (string.IsNullOrEmpty(resp.Content)) { sbLog.AppendLine($"Content is empty; Request idCity: {city}"); } var weather = JsonConvert.DeserializeObject <WeatherForecast>(resp.Content); responseList.WeathersList.Add(weather); } responseList.MessageResponse = (string.IsNullOrEmpty(sbLog.ToString()) ? "Success" : sbLog.ToString()); return(responseList); }
public ResponseWeather GetWeather(string cityID) { string apiKey = ConfigurationManager.AppSettings["APIKey"].ToString(); HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cityID + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; try { using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather WeatherDetails = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); return(WeatherDetails); } catch (Exception e) { logger.Error(e.Message); } return(null); }
private void FormatRootObject(ResponseWeather rootObject, ref OpenWeatherMap openWeatherMap) { openWeatherMap.City = rootObject.name; openWeatherMap.Country = rootObject.sys.country; openWeatherMap.WindSpeed = rootObject.wind.speed; openWeatherMap.Temperature = rootObject.main.temp; openWeatherMap.Humidity = rootObject.main.humidity; openWeatherMap.Conditions = rootObject.weather[0].description; }
public void TestWeatherAPIResponeDetails() { String city = "milan"; _Default bn = new _Default(); ResponseWeather rootObject = bn.GetWeatherAPIResponse(city); Assert.IsNotNull(rootObject); Assert.AreEqual(rootObject.name.ToLower(), city); }
public ActionResult Index(string cityName) { WeatherModel wm = new WeatherModel(); string apiKey = "ca862bc98586462259cc6d14ec1037d1"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); wm.cityName = cityName; wm.description = rootObject.weather[0].description; wm.clouds = rootObject.clouds.all.ToString(); wm.humidity = rootObject.main.humidity.ToString(); wm.pressure = rootObject.main.pressure.ToString(); wm.temp = Math.Round(((rootObject.main.temp * (9.00 / 5.00)) + 32), 0).ToString(); wm.wind = rootObject.wind.speed.ToString(); string pants = AppDomain.CurrentDomain.BaseDirectory; if (wm.description.Contains("rain")) { wm.imageURL = "~/Images/rain.png"; } else if (wm.description.Contains("clear")) { wm.imageURL = "~/Images/sky.png"; } else if (wm.description.Contains("clouds")) { wm.imageURL = "~/Images/cloud.png"; } else if (wm.description.Contains("snow")) { wm.imageURL = "~/Images/snow.png"; } else { wm.imageURL = "~/Images/sky.png"; } TempData["weather"] = wm; return(RedirectToAction("ShowWeather")); }
public ActionResult Index(string cities) { ResponseWeather rootObject = null; if (!string.IsNullOrEmpty(cities)) //проверяем есть ли символы в строке { rootObject = GetWeatherByCiti(cities); //ищем погоду по названию города if (rootObject != null) //проверяем получили ли мы данные о погоде в указанном нами городе { return(View("~/Views/OpenWeatherMapMvc/Search.cshtml", rootObject)); //вызов представления и передача модели } } return(Content("You did not specify a city or the specified city was not found!")); //Error }
public ActionResult Index(OpenWeatherMap openWeatherMap, string cities) { openWeatherMap = FillCity(); if (cities != null) { /*Calling API http://openweathermap.org/api */ string apiKey = "61dda8e5b0d2ba353473d60e9d6a7646"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); StringBuilder sb = new StringBuilder(); sb.Append("<table><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>"); sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("</table>"); openWeatherMap.apiResponse = sb.ToString(); } else { if (Request.Form["submit"] != "") { openWeatherMap.apiResponse = "► Select City"; } } return(View(openWeatherMap)); }
private string FormatRootObjectAsString(ResponseWeather rootObject) { StringBuilder sb = new StringBuilder(); sb.Append("<table><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>"); sb.Append("<tr><td>Conditions:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("</table>"); return(sb.ToString()); }
private void GetWeather_Click(object sender, EventArgs e) { string message = "/GetCityCoordinates" + "<EOF>"; Request request = new Request(message, null); var jsonToSend = JsonConvert.SerializeObject(request); string receivedData = client.sendData(jsonToSend); var json = JsonConvert.DeserializeObject <City>(receivedData); ResponseWeather responseWeather = new ResponseWeather(); List <Weather> weathers = responseWeather.getInformations(new Coord(json.Latitude, json.Longitude)); foreach (Weather weather in weathers) { Information.Text = "The weather is " + weather.description + " "; } }
public OpenWeatherMap WeatherApICall(OpenWeatherMap openWeatherMap, string cities) { if (cities != null) { try { /*Calling API http://openweathermap.org/api */ string apiKey = "aa69195559bd4f88d79f9aadeb77a8f6"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); StringBuilder sb = new StringBuilder(); sb.Append("<table class=\"col-md-4\" ><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>"); sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("</table>"); openWeatherMap.apiResponse = sb.ToString(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } return(openWeatherMap); }
public ActionResult Index(WeatherModel weather, string cities) { weather = FillCity(); if (cities != null) { /*Calling API http://openweathermap.org/api */ string apiKey = "fb59ff231e41ec1d3ab5c10bb667052d"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); StringBuilder sb = new StringBuilder(); sb.Append("<table><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>"); sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("</table>"); weather.apiResponse = sb.ToString(); } else { if (Request.Form["submit"] != null) { weather.apiResponse = "► Select City"; } } return(View(weather)); }
/// <summary> /// This method is used to call the weather API and get response /// </summary> /// <param name="city"></param> /// <returns></returns> public ResponseWeather GetWeatherAPIResponse(String city) { String unitType = "metric"; //To fetch the Temperature in celcius unit HttpWebRequest apiRequest = WebRequest.Create(url + city + "&units=" + unitType + "&appid=" + apiKey) as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); return(rootObject); }
private async Task <IActionResult> ProcessRequestWeather(string[] cities) { if (!ContainCitiesReques(cities)) { var responseNotFound = new ResponseWeather { MessageResponse = "não informado cidades válidas no request" }; return(NotFound(JsonConvert.SerializeObject(responseNotFound))); } ; var response = await ConsumeOpenWeatherApi(cities); return(Ok(JsonConvert.SerializeObject(response))); }
public FileResult saveToFile() { string path = @"C:\Univer\for1day.txt"; string file_type = "application/txt"; ResponseWeather rootObject = TempStore.response; //string json = JsonSerializer.Serialize(rootObject); string json = JsonConvert.SerializeObject(rootObject); using (StreamWriter file = new StreamWriter(path)) { file.WriteLine(json); } return(File(path, file_type)); }
public ActionResult Index(string cities) { ClimateModel openWeatherMap = FillCity(); if (cities != null) { string apiKey = "61cb374e7df0bee2ff6d3cc46f278eb1"; HttpWebRequest apiRequest = WebRequest.Create("https://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; //apiRequest.UseDefaultCredentials = true;// added by me to solve the error //apiRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;// added by me to solve the error string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse);// StringBuilder sb = new StringBuilder(); sb.Append("<table><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Country Sun Rise:</td><td>" + rootObject.sys.sunrise + "</td></tr>"); sb.Append("<tr><td>Country Sun Sete:</td><td>" + rootObject.sys.sunset + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>"); sb.Append("<tr><td>Max. Temperature:</td><td>" + rootObject.main.temp_max + " °C</td></tr>"); sb.Append("<tr><td>Min. Temperature:</td><td>" + rootObject.main.temp_min + " °C</td></tr>"); sb.Append("<tr><td>Pressure:</td><td>" + rootObject.main.pressure + "</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>"); sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("</table>"); openWeatherMap.apiResponse = sb.ToString(); } else { if (Request.Form["submit"] != null) { TempData["SelectOption"] = -1; } } return(View(openWeatherMap)); }
/// <summary> /// This method is used to populate the weather details of provided city in table /// </summary> /// <param name="city"></param> /// <returns></returns> public string GetWeatherDetails(string city) { try { #region call API and get response ResponseWeather rootObject = GetWeatherAPIResponse(city); #endregion #region Add dynamic table to show output data StringBuilder sb = new StringBuilder(); sb.Append("<table><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C / " + ConvertCelciusToFahrenheit(rootObject.main.temp) + " F </td></tr>"); sb.Append("<tr><td>Minimum Temperature:</td><td>" + rootObject.main.temp_min + " °C / " + ConvertCelciusToFahrenheit(rootObject.main.temp_min) + " F </td></tr>"); sb.Append("<tr><td>Maximum Temperature:</td><td>" + rootObject.main.temp_max + " °C / " + ConvertCelciusToFahrenheit(rootObject.main.temp_max) + " F </td></tr>"); sb.Append("<tr><td>Pressure:</td><td>" + rootObject.main.pressure + " hPa</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "%</td></tr>"); sb.Append("<tr><td>Sunrise:</td><td>" + UnixTimeStampToDateTime(rootObject.sys.sunrise) + "</td></tr>"); sb.Append("<tr><td>Sunset:</td><td>" + UnixTimeStampToDateTime(rootObject.sys.sunset) + "</td></tr>"); sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("</table>"); #endregion return(sb.ToString()); } catch (Exception e) { //lblError.Visible = true; return(""); } }
public ActionResult Index(string cities) { OpenWeatherMap openWeatherMap = FillCity(); if (cities != null) { /*Calling API http://openweathermap.org/api */ string apiKey = "de6d52c2ebb7b1398526329875a49c57"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&appid=" + apiKey) as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); StringBuilder sb = new StringBuilder(); sb.Append("<table><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>Location:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Visibility:</td><td>" + rootObject.visibility + "</td></tr>"); sb.Append("<tr><td>Sky Conditions:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + "</td></tr>"); sb.Append("<tr><td>Relative Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>"); sb.Append("<tr><td>Dew Point:</td><td>" + rootObject.dt + "</td></tr>"); sb.Append("<tr><td>Pressure:</td><td>" + rootObject.main.pressure + "</td></tr>"); sb.Append("</table>"); openWeatherMap.apiResponse = sb.ToString(); } else { if (Request.Form["submit"] != null) { openWeatherMap.apiResponse = "Select City"; } } return(View(openWeatherMap)); }
public ActionResult Index(string cities) { WeatherModel weatherModel = FillCity(); try { if (cities != null) { string apiKey = "f1adaad561307ef65a1266096fd908b2"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); StringBuilder sb = new StringBuilder(); sb.Append("<table><tr><th>Weather Description</th></tr>"); sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>"); sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>"); sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>"); sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>"); sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>"); sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>"); sb.Append("</table>"); weatherModel.apiResponse = sb.ToString(); } else { if (Request.Form["submit"] != null) { weatherModel.apiResponse = "► Select City"; } } } catch (Exception e) { Console.WriteLine(e.StackTrace); } return(View(weatherModel)); }
public void Post([FromBody] JObject value) { float lat = value["lat"].Value <float>(); float lon = value["lon"].Value <float>(); /*Calling API http://openweathermap.org/api */ string apiKey = "0e24126ab1639fb0301e58fb0f2a7009"; HttpWebRequest apiRequest = WebRequest.Create($"http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={apiKey}") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); }
/** * get responded info * searchText: search string * cor: Current location * type: type of search * rootObject: search response weather object * weekData: search response of incoming week * */ public void getResponseWeather(string searchText, [Optional] Coord cor, int type, ref ResponseWeather rootObject, ref List <Models.Forecastday> weekData) { string curUrl = "", weekUrl = ""; getApiRequestString(searchText, cor, type, ref curUrl, ref weekUrl); System.Net.HttpWebRequest apiRequest = WebRequest.Create(curUrl) as HttpWebRequest; string apiResponse = ""; try { using (System.Net.HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } JsonSerializerSettings serSettings = new JsonSerializerSettings(); serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse, serSettings); } catch (Exception ex) { if (ex.Message.ToLower().Contains("not found")) { rootObject = null; } } //-----get 7 days info------------- Models.WeatherModel model = GetData(weekUrl); if (model != null && model.forecast != null) { weekData = model.forecast.forecastday; } }
public ActionResult Index(DashboardViewModel openWeatherMap, string cities) { if (cities != null) { /*Calling API http://openweathermap.org/api */ string apiKey = "9b102e84793bf9c05da530b6612257ed"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); StringBuilder sb = new StringBuilder(); sb.Append("<div weather-panel=\"forecast\" show-entry=\"forecast.list[0]\" class=\"ng-isolate-scope ng-scope\" id=\"weather\"><div class=\"weather panel panel-primary\">"); sb.Append("<div class=\"panel-heading ng-binding\" id=\"weatherheader\">" + rootObject.name + ", " + rootObject.sys.country + ": " + DateTime.Now + "</div>"); sb.Append("<div class=\"panel-body\">"); sb.Append("<div>"); sb.Append("<p class=\"lead ng-binding\"><img ng-src=http://openweathermap.org/img/w/" + rootObject.weather[0].icon + ".png " + "src=\"http://openweathermap.org/img/w/" + rootObject.weather[0].icon + ".png\"> " + rootObject.main.temp + "°C " + rootObject.weather[0].main + "</p>"); sb.Append("<p class=\"ng-binding\">" + rootObject.weather[0].description + " ~ High: " + rootObject.main.temp_max + "°C ~ Low: " + rootObject.main.temp_min + "°C</p>"); sb.Append("</div>"); sb.Append("</div>"); sb.Append("<div class=\"panel-footer\"><small class=\"ng-binding\">Pressure: " + rootObject.main.pressure + "hPa ~ Humidity: " + rootObject.main.humidity + "%</small></div>"); sb.Append("</div>"); sb.Append("</div>"); openWeatherMap.apiResponse = sb.ToString(); } else { ViewBag.ErrorMessage = "please provide a city name"; } return(View(openWeatherMap)); }
public ActionResult Index(HttpPostedFileBase postedFile) { if (postedFile != null && postedFile.ContentLength > 0) { try { string filePath = string.Empty; string path = Server.MapPath("~/Uploads/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } filePath = path + Path.GetFileName(postedFile.FileName); string extension = Path.GetExtension(postedFile.FileName); postedFile.SaveAs(filePath); //Read the contents of txt file. string txtData = System.IO.File.ReadAllText(filePath); Dictionary <string, string> cities = new Dictionary <string, string>(); //Execute a loop over the lines. foreach (string row in txtData.Split('\n')) { if (!string.IsNullOrEmpty(row)) { cities.Add((row.Split('=')[1]), (row.Split('=')[0])); } } if (cities != null) { foreach (var city in cities) { string apiKey = "aa69195559bd4f88d79f9aadeb77a8f6"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + Convert.ToInt32(city.Value) + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; //Getting API's Response string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } //Converting the response ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); //Dumping the response into String Builder StringBuilder sb = new StringBuilder(); sb.Append("Weather Description" + "\n"); sb.Append("City:" + rootObject.name + "\n"); sb.Append("Country:" + rootObject.sys.country + "\n"); sb.Append("Sun Rise:" + rootObject.sys.sunrise + "\n"); sb.Append("Country Sun Set:" + rootObject.sys.sunset + "\n"); sb.Append("Wind:" + rootObject.wind.speed + " Km/h" + "\n"); sb.Append("Current Temperature:" + rootObject.main.temp + " °C" + "\n"); sb.Append("Max. Temperature:" + rootObject.main.temp_max + " °C" + "\n"); sb.Append("Min. Temperature:" + rootObject.main.temp_min + " °C" + "\n"); sb.Append("Pressure:" + rootObject.main.pressure + "\n"); sb.Append("Humidity:" + rootObject.main.humidity + "\n"); sb.Append("Weather:" + rootObject.weather[0].description + "\n"); //Creating the required files with output string directory = Server.MapPath("~"); string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now, city.Key.ToString().Replace("\r", "")); string filepath = Path.Combine(directory, filename); if (System.IO.File.Exists(filepath)) { System.IO.File.Delete(filepath); } using (StreamWriter swriter = System.IO.File.CreateText(filepath)) { swriter.Write(sb.ToString()); ViewBag.Message = "SUCCESS. Your generated weather reports are at:" + directory.ToString(); } } } } catch (Exception ex) { ViewBag.Message = "Exception Occured:" + ex.Message; } } else { ViewBag.Message = "You have not specified a file."; } return(View()); }
public ActionResult Index(OpenWeatherMap openWeatherMap) { //Check for non-empty input field if (ModelState.IsValid) { /*Calling API http://openweathermap.org/api */ string apiKey = "de6d52c2ebb7b1398526329875a49c57"; //Current weather in city HttpWebRequest apiRequest = WebRequest.Create("https://api.openweathermap.org/data/2.5/weather?q=" + openWeatherMap.cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; //Check for an existing city try { //Receiving a request and translating it into a string using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader readersReader = new StreamReader(response.GetResponseStream()); apiResponse = readersReader.ReadToEnd(); } } catch (Exception) { openWeatherMap.apiResponseCurrent = "<h1 class='text-danger text-center'>This city not exist!</h1>"; return(View(openWeatherMap)); } //Writing json information to classes ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); //Html text StringBuilder sb = new StringBuilder(); sb.Append("<h2 class='text-center'>" + rootObject.name + "</h2>"); sb.Append("<h3 class='text-center'>Weather now</h3>"); sb.Append("<table class='table table-striped table-bordered'>"); sb.Append("<tr ><td>Temp: </td ><td>" + Math.Round(rootObject.main.temp) + "°C</td></tr>"); sb.Append("<tr ><td>Pressure: </td ><td>" + Math.Round(rootObject.main.pressure) + " hPa</td></tr>"); sb.Append("<tr ><td>Humidity: </td ><td>" + Math.Round(rootObject.main.humidity) + "%</td></tr>"); sb.Append("<tr><td>Wind speed:</td><td>" + Math.Round(rootObject.wind.speed) + " meter/sec</td></tr>"); sb.Append("</table>"); openWeatherMap.apiResponseCurrent = sb.ToString(); //Today's weather forecast HttpWebRequest apiRequestForecast = WebRequest.Create("https://api.openweathermap.org/data/2.5/forecast?q=" + openWeatherMap.cities + "&appid=" + apiKey) as HttpWebRequest; string apiResponseForecast = ""; //Receiving a request and translating it into a string using (HttpWebResponse responses = apiRequestForecast.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(responses.GetResponseStream()); apiResponseForecast = reader.ReadToEnd(); } //Writing json information to classes RootObject rootObjectforecast = JsonConvert.DeserializeObject <RootObject>(apiResponseForecast); //Html text StringBuilder sbforecast = new StringBuilder(); //Current day sbforecast.Append(" <h3 class='text-center'> Weather today " + ": <b>" + DateTime.Now.Day + "." + DateTime.Now.Month + "</b></h3>"); sbforecast.Append("<div class='row'>"); //Calculate time forecast int hours = 0; if (DateTime.Now.Hour % 3 == 0) { hours = DateTime.Now.Hour; } else { hours = DateTime.Now.Hour - DateTime.Now.Hour % 3; } //Forecast for 18 hours because the information in the json 5 days / 3 hours //If you want I can do a few days weather forecast sbforecast.Append("<table class='tabs col-lg-offset-2 col-md-offset-2 col-sm-offset-0 text-center table-bordered '>"); sbforecast.Append("<tr ><th>Time:</th>" + "<th>Temp:</th>" + "<th>Pressure:</th>" + "<th>Humidity:</th>" + "<th>Wind speed:</th>" + "<th>Wind direction:</th></tr>"); for (int i = 0; i < 8; i += 1) { if (hours > 24) { hours = hours - 24; } //Calculate temp from kelvin to celsius double TempNow = rootObjectforecast.list[i].main.temp - 272.15; //sbforecast.Append("<tr ><th class='text-center'>" + "Time: " + hours + " :00" +"</th></tr>"); sbforecast.Append("<tr ><th class='text-center'>" + hours + " :00" + "</th> " + "<td>" + Math.Round(TempNow) + " °C </td> " + "<td>" + rootObjectforecast.list[i].main.pressure + " hPa " + "<td>" + rootObjectforecast.list[i].main.humidity + " %</td> " + "<td>" + Math.Round(rootObjectforecast.list[i].wind.speed) + " m/c</td> " + "<td>" + rootObjectforecast.list[i].wind.deg + "°</td></tr>"); //sbforecast.Append("<tr><td>Temp:</td><td>" + Math.Round(TempNow) + " °C </td></tr>"); //sbforecast.Append("<tr><td>Pressure:</td><td>" + rootObjectforecast.list[i].main.pressure + " hPa</td></tr>"); //sbforecast.Append("<tr><td>Humidity:</td><td>" + rootObjectforecast.list[i].main.humidity + " %</td></tr>"); //sbforecast.Append("<tr><td>Wind speed:</td><td>" + Math.Round(rootObjectforecast.list[i].wind.speed) + " m/c</td></tr>"); //sbforecast.Append("<tr><td>Wind direction:</td><td>" + rootObjectforecast.list[i].wind.deg + "°</td></tr>"); hours += 3; } sbforecast.Append("</div>"); sbforecast.Append("</table>"); openWeatherMap.ApiResponseForecast = sbforecast.ToString(); } return(View(openWeatherMap)); }
public IActionResult Weather()//[FromBody]TwitterViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var mails = new Dictionary <string, List <string> >(); var userIds = ( from souscription in _db.Souscriptions where souscription.AppletId == 4 select souscription.UserId ).ToList(); foreach (var id in userIds) { var list = new List <string>(); var userName = ( from users in _db.Users where users.Id == id select users.UserName ).FirstOrDefault(); var city = ( from souscription in _db.Souscriptions where souscription.UserId == id && souscription.AppletId == 4 select souscription.City ).FirstOrDefault(); var token = ( from souscription in _db.Souscriptions where souscription.UserId == id && souscription.AppletId == 4 select souscription.TwitterToken ).FirstOrDefault(); var secret = ( from souscription in _db.Souscriptions where souscription.UserId == id && souscription.AppletId == 4 select souscription.TwitterSecret ).FirstOrDefault(); list.Add(city); list.Add(token); list.Add(secret); mails.Add(userName, list); } foreach (var pair in mails) { /*Calling API http://openweathermap.org/api */ string apiKey = "9b102e84793bf9c05da530b6612257ed"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + pair.Value[0] + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); Auth.SetUserCredentials("GchL7ZiVPOxn4S1ahVqr72tP3", "m4X3R69C5nHdSSKdAyg2TetLpTvypYwPrEYAmMd8pL8ShUYwBr", pair.Value[1], pair.Value[2]); var user = Tweetinvi.User.GetAuthenticatedUser(); Console.WriteLine(user); var icon_url = "http://openweathermap.org/img/w/" + rootObject.weather[0].icon + ".png"; var tweet = Tweet.PublishTweet("The weather of today in " + rootObject.name + " is: " + rootObject.weather[0].main + ", " + rootObject.weather[0].description + "\n" + icon_url); var timelineTweets = Timeline.GetUserTimeline(user, 5); foreach (var timelineTweet in timelineTweets) { Console.WriteLine(timelineTweet); } Console.ReadKey(); return(Ok(new { message = "Tweet sent successfully", status = 200 })); } return(BadRequest(new { message = "Tweet not sent", status = 400 })); }
public IActionResult Current()//[FromBody]WeatherViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var mails = new Dictionary <string, string>(); var userIds = ( from souscription in _db.Souscriptions where souscription.AppletId == 1 select souscription.UserId ).ToList(); foreach (var id in userIds) { var userName = ( from user in _db.Users where user.Id == id select user.UserName ).FirstOrDefault(); var city = ( from souscription in _db.Souscriptions where souscription.UserId == id && souscription.AppletId == 1 select souscription.City ).FirstOrDefault(); mails.Add(userName, city); } foreach (var pair in mails) { /*Calling API http://openweathermap.org/api */ string apiKey = "9b102e84793bf9c05da530b6612257ed"; HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + pair.Value + "&appid=" + apiKey + "&units=metric") as HttpWebRequest; string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ /*http://json2csharp.com*/ ResponseWeather rootObject = JsonConvert.DeserializeObject <ResponseWeather>(apiResponse); try { var icon_url = "http://openweathermap.org/img/w/" + rootObject.weather[0].icon + ".png"; SmtpClient client = new SmtpClient("smtp.gmail.com"); client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential("*****@*****.**", "Starkiller75"); MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress("*****@*****.**"); mailMessage.To.Add(pair.Key); mailMessage.Body = ( $"<h1 style=\"text-align: center;\">Voici la météo pour la ville de {rootObject.name}: </h1><br>" + $"<h2 style=\"text-align: center;\">{rootObject.weather[0].main}, {rootObject.weather[0].description}</h2><br>" + $"<p style=\"text-align: center;\"><img src=\"{icon_url}\"/></p>" ); mailMessage.IsBodyHtml = true; mailMessage.Subject = "Météo du jour"; client.Send(mailMessage); } catch (SmtpFailedRecipientException ex) { return(BadRequest(ex)); } } return(Ok(new { message = "Mail sent successfully", status = 200 })); }
public ActionResult Index(string curlat, string curlon, string requestString) { Coord currentLocation = null; int type = 0; // navigating search criteria if (!String.IsNullOrEmpty(requestString) || (!String.IsNullOrEmpty(curlat) && !String.IsNullOrEmpty(curlon))) { ResponseWeather rootObjectt = new ResponseWeather(); List <Forecastday> weekInfo = new List <Forecastday>(); requestString = requestString.Trim(); if (Regex.Match(requestString, @"^\d{5}$", RegexOptions.IgnoreCase).Success) {//search by zip code type = 2; openWeatherMap.apiResponse = ""; } else if (Regex.Match(requestString, @"^\w+\,\w+$", RegexOptions.IgnoreCase).Success) {//search by city (Lacey,us), (danang,vn) type = 1; openWeatherMap.apiResponse = ""; } else if (String.IsNullOrEmpty(curlat) == false && String.IsNullOrEmpty(curlon) == false) {//current location currentLocation = new Coord() { lat = Double.Parse(curlat), lon = Double.Parse(curlon) }; type = 3; } else { openWeatherMap.apiResponse = "Invalid zipcode or city"; return(View(openWeatherMap)); } if (type == 0) { openWeatherMap.apiResponse = "Nothing to render"; return(View(openWeatherMap)); } myService.getResponseWeather(searchText: requestString, cor: currentLocation, type: type, rootObject: ref rootObjectt, weekData: ref weekInfo ); openWeatherMap.rootObject = rootObjectt; if (rootObjectt != null) { var recent = new HistorySearch() { coord = rootObjectt.coord, nameLocation = rootObjectt.name }; retrieveInfo(recent); saveToCookie(openWeatherMap.historySearchs); weekInfo.ForEach(x => x.date = DateTime.Parse(x.date).Month.ToString() + "/" + DateTime.Parse(x.date).Day.ToString()); openWeatherMap.forecastResponse = weekInfo; } else { openWeatherMap.apiResponse = "Info you are searching is not found"; return(View(openWeatherMap)); } } else if (Request.Form["submit"] != null) { openWeatherMap.apiResponse = "Put in city or zip code"; } return(View(openWeatherMap)); }