)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Home » Code Library » WeatherController (Ia.Api.Wa.Controllers)

Public general use code classes and xml files that we've compiled and used over the years:

OpenWeatherMap API Controller class.

    1: using Microsoft.AspNetCore.Mvc;
    2: using System.Xml.Linq;
    3: using System.Configuration;
    4:  
    5: namespace Ia.Api.Wa.Controllers
    6: {
    7:     ////////////////////////////////////////////////////////////////////////////
    8:  
    9:     /// <summary publish="true">
   10:     /// OpenWeatherMap API Controller class.
   11:     /// </summary>
   12:     /// 
   13:     /// <remarks> 
   14:     /// Copyright © 2001-2024 Jasem Y. Al-Shamlan (info@ia.com.kw), Integrated Applications - Kuwait. All Rights Reserved.
   15:     ///
   16:     /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
   17:     /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
   18:     ///
   19:     /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   20:     /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
   21:     /// 
   22:     /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
   23:     /// 
   24:     /// Copyright notice: This notice may not be removed or altered from any source distribution.
   25:     /// </remarks> 
   26:     [ApiController]
   27:     [Route("api/weather")]
   28:     public class WeatherController : ControllerBase
   29:     {
   30:         private static string weatherTick;
   31:         private static List<Ia.Cl.Models.Weather.Forecast> weather;
   32:  
   33:         ////////////////////////////////////////////////////////////////////////////
   34:  
   35:         /// <summary>
   36:         /// Reads OpenWeatherMap.org API Service for weather information in Kuwait.
   37:         /// </summary>
   38:         [HttpGet]
   39:         [Route("kuwait")]
   40:         public List<Ia.Cl.Models.Weather.Forecast> ReadKuwait()
   41:         {
   42:             long ticks;
   43:             DateTime lastTime, now;
   44:             List<Ia.Cl.Models.Weather.Forecast> forecastList, savedForcastList;
   45:  
   46:             now = DateTime.UtcNow.AddHours(3);
   47:  
   48:             if (weather != null && weatherTick != null)
   49:             {
   50:                 savedForcastList = weather;
   51:                 ticks = long.Parse(weatherTick);
   52:                 lastTime = new DateTime(ticks);
   53:  
   54:                 // check that 60 minutes had passed:
   55:                 if (now.Ticks > lastTime.AddMinutes(60).Ticks)
   56:                 {
   57:                     forecastList = Retrieve(387990); // Kuwait city id: 387990
   58:  
   59:                     weather = forecastList;
   60:                     weatherTick = now.Ticks.ToString();
   61:                 }
   62:                 else
   63:                 {
   64:                     // if an hour did not pass, return the saved value;
   65:                     forecastList = savedForcastList;
   66:                 }
   67:             }
   68:             else
   69:             {
   70:                 forecastList = Retrieve(387990); // Kuwait city id: 387990
   71:                 weather = forecastList;
   72:                 weatherTick = now.Ticks.ToString();
   73:             }
   74:  
   75:             return forecastList;
   76:         }
   77:  
   78:         ////////////////////////////////////////////////////////////////////////////
   79:  
   80:         /// <summary>
   81:         ///
   82:         /// </summary>
   83:         private List<Ia.Cl.Models.Weather.Forecast> Retrieve(int cityId)
   84:         {
   85:             /*
   86:   "AppSettings": {
   87:     "OpenWeatherMapApiKey": "844215dd82dde09fa569c002125f7569",
   88:   },
   89:             */
   90:  
   91:             string apiKey, url, content;
   92:             XDocument xDocument;
   93:  
   94:             var forecast = new Ia.Cl.Models.Weather.Forecast();
   95:             var forecastList = new List<Ia.Cl.Models.Weather.Forecast>();
   96:  
   97:             apiKey = Ia.Cl.Models.ApplicationConfiguration.GetSetting("AppSettings:OpenWeatherMapApiKey");
   98:  
   99:             url = "https://api.openweathermap.org/data/2.5/forecast?id=" + cityId + "&mode=xml&units=metric&APPID=" + apiKey;
  100:  
  101:             using (var httpClient = new HttpClient())
  102:             {
  103:                 httpClient.DefaultRequestHeaders.Clear();
  104:                 httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
  105:  
  106:                 content = httpClient.GetStringAsync(url).Result;
  107:             }
  108:  
  109:             xDocument = XDocument.Parse(content);
  110:  
  111:             if (xDocument != null)
  112:             {
  113:                 foreach (XElement xe in xDocument.Element("weatherdata").Element("forecast").Elements("time"))
  114:                 {
  115:                     forecast = new Ia.Cl.Models.Weather.Forecast();
  116:  
  117:                     // <time from="2016-06-13T03:00:00" to="2016-06-13T06:00:00">
  118:                     forecast.TimeFrom = DateTime.Parse(xe.Attribute("from").Value);
  119:                     forecast.TimeTo = DateTime.Parse(xe.Attribute("to").Value);
  120:  
  121:                     // <symbol number="800" name="clear sky" var="01d"/>
  122:                     forecast.SymbolNumber = int.Parse(xe.Element("symbol").Attribute("number").Value);
  123:                     forecast.SymbolName = xe.Element("symbol").Attribute("name").Value;
  124:                     forecast.SymbolVariable = xe.Element("symbol").Attribute("var").Value;
  125:  
  126:                     // <precipitation/>
  127:                     forecast.Precipitation = (xe.Element("precipitation").Attribute("variable") != null) ? xe.Element("precipitation").Attribute("variable").Value : null;
  128:  
  129:                     // <windDirection deg="322.501" code="NW" name="Northwest"/>
  130:                     forecast.WindDirectionDegree = float.Parse(xe.Element("windDirection").Attribute("deg").Value);
  131:                     forecast.WindDirectionCode = xe.Element("windDirection").Attribute("code").Value;
  132:                     forecast.WindDirectionName = xe.Element("windDirection").Attribute("name").Value;
  133:  
  134:                     // <windSpeed mps="6.05" name="Moderate breeze"/>
  135:                     forecast.WindSpeedMps = float.Parse(xe.Element("windSpeed").Attribute("mps").Value);
  136:                     forecast.WindSpeedName = xe.Element("windSpeed").Attribute("name").Value;
  137:  
  138:                     // <temperature unit="celsius" value="37.14" min="33.12" max="37.14"/>
  139:                     forecast.TemperatureUnit = xe.Element("temperature").Attribute("unit").Value;
  140:                     forecast.TemperatureValue = float.Parse(xe.Element("temperature").Attribute("value").Value);
  141:                     forecast.TemperatureMin = float.Parse(xe.Element("temperature").Attribute("min").Value);
  142:                     forecast.TemperatureMax = float.Parse(xe.Element("temperature").Attribute("max").Value);
  143:  
  144:                     // <pressure unit="hPa" value="1017.48"/>
  145:                     forecast.PressureUnit = xe.Element("pressure").Attribute("unit").Value;
  146:                     forecast.PressureValue = float.Parse(xe.Element("pressure").Attribute("value").Value);
  147:  
  148:                     // <humidity value="46" unit="%"/>
  149:                     forecast.HumidityValue = int.Parse(xe.Element("humidity").Attribute("value").Value);
  150:                     forecast.HumidityUnit = xe.Element("humidity").Attribute("unit").Value;
  151:  
  152:                     // <clouds value="clear sky" all="0" unit="%"/>                        
  153:                     forecast.CloudsValue = xe.Element("clouds").Attribute("value").Value;
  154:                     forecast.CloudsAll = int.Parse(xe.Element("clouds").Attribute("all").Value);
  155:                     forecast.CloudsUnit = xe.Element("clouds").Attribute("unit").Value;
  156:  
  157:                     forecastList.Add(forecast);
  158:                 }
  159:             }
  160:  
  161:             return forecastList;
  162:         }
  163:  
  164:         ////////////////////////////////////////////////////////////////////////////
  165:         ////////////////////////////////////////////////////////////////////////////
  166:     }
  167:  
  168:     ////////////////////////////////////////////////////////////////////////////
  169:     ////////////////////////////////////////////////////////////////////////////
  170: }