Reloj en Jquery con Clima en ASP.NET MVC 3

Buscando algunos plugins de relojes hechos en Jquery, me topé con este http://www.htmldrive.net/items/show/298/Digital-Clock-SlideshowjQuery , inspirado en la interfaz de HTC, que se puede ver en algunos smartphones con Android y Windows Mobile. Posee un reloj digital y además muestra el clima de una ciudad junto con la predicción de este, los próximos 4 días junto con las temperaturas probables para cada día.

Después de descargarnos el comprimido y descomprimirlo, veremos la siguiente estructura:

En el archivo WeatherLocationDatabase, se encuentran las localizaciones de una vasta cantidad de ciudades que soporta en WebService, del gestor de clima, en la carpeta lib, se encuentra el script del plugin, este junto a los css y las imágenes las deberemos de agregar a nuestro proyecto:

Ahora en la carpeta lib/proxy se encuentra el proxy del web service tanto para ASP.NET como para PHP, ahora existen 2 opciones, hacer que el proxy que viene por defecto funcione con MVC o modificarlo para adaptarlo a MVC, para el post usaremos la opción 2.

Para lo cual crearemos un controlador con el nombre Weather, ahí crearemos un método llamado “GetWeather” y pegaremos el siguiente código, que no es nada más que el código que viene en el proxy del plugin con algunas modificaciones:
[HttpGet]
        public JsonResult GetWeather(string _location = "EUR|BG|BU002|BOURGAS", string _metric = "C")
        {
            //string _url = string.Format("http://rainmeter.accu-weather.com/widget/rainmeter/weather-data.asp?location={0}&metric={1}", _location, _metric);
            string _url = string.Format("http://wwwa.accuweather.com/adcbin/forecastfox/weather_data.asp?location={0}&metric={1}", _location, _metric);

            string _xml = DownloadWebPage(_url);

            XmlDocument _xmlDocument = new XmlDocument();
            _xmlDocument.LoadXml(_xml);

            XmlNamespaceManager _mgr = new XmlNamespaceManager(_xmlDocument.NameTable);
            _mgr.AddNamespace("pf", _xmlDocument.DocumentElement.NamespaceURI);

            Weather _weather = new Weather();

            _weather.city =
                _xmlDocument.SelectSingleNode("/pf:adc_database/pf:local/pf:city", _mgr).InnerText;
            _weather.curr_temp = Convert.ToInt32(
                _xmlDocument.SelectSingleNode("/pf:adc_database/pf:currentconditions/pf:temperature", _mgr).InnerText);
            _weather.curr_text =
                _xmlDocument.SelectSingleNode("/pf:adc_database/pf:currentconditions/pf:weathertext", _mgr).InnerText;
            _weather.curr_icon = Convert.ToInt32(
                _xmlDocument.SelectSingleNode("/pf:adc_database/pf:currentconditions/pf:weathericon", _mgr).InnerText);

            XmlNodeList _xmlNodeList = _xmlDocument.SelectNodes("/pf:adc_database/pf:forecast/pf:day", _mgr);
            int _day = _xmlNodeList.Count;
            int i = 0;
            foreach (XmlNode _dayItem in _xmlNodeList)
            {
                Forecast _forecast = new Forecast();

                _forecast.day_date = _dayItem["obsdate"].InnerXml;
                _forecast.day_text = _dayItem.SelectSingleNode("pf:daytime", _mgr)["txtshort"].InnerXml;
                _forecast.day_icon =
                    Convert.ToInt32(_dayItem.SelectSingleNode("pf:daytime", _mgr)["weathericon"].InnerXml);
                _forecast.day_htemp =
                    Convert.ToInt32(_dayItem.SelectSingleNode("pf:daytime", _mgr)["hightemperature"].InnerXml);
                _forecast.day_ltemp =
                    Convert.ToInt32(_dayItem.SelectSingleNode("pf:daytime", _mgr)["lowtemperature"].InnerXml);

                _weather.forecast.Add(_forecast);

                i++;
                // 5 day forecast
                if (i == 5) break;
            }
            return Json(_weather, JsonRequestBehavior.AllowGet);
        }
Luego agregaremos un par de clases y un método al controlador para cumplir con el proxy:

        public string DownloadWebPage(string Url)
        {
            // Open a connection
            HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(Url);

            // You can also specify additional header values like
            // the user agent or the referer:
            WebRequestObject.UserAgent = ".NET Framework/2.0";
            WebRequestObject.Referer = "http://www.example.com/";

            // Request response:
            WebResponse Response = WebRequestObject.GetResponse();

            // Open data stream:
            Stream WebStream = Response.GetResponseStream();

            // Create reader object:
            StreamReader Reader = new StreamReader(WebStream);

            // Read the entire stream content:
            string PageContent = Reader.ReadToEnd();

            // Cleanup
            Reader.Close();
            WebStream.Close();
            Response.Close();

            return PageContent;
        }

        public class Weather
        {
            public string city;
            public int curr_temp;
            public string curr_text;
            public int curr_icon;

            public List forecast = new List();
        }

        public class Forecast
        {
            public string day_date;
            public string day_text;
            public int day_icon;
            public int day_htemp;
            public int day_ltemp;
        }


Por ultimo nos dirigiremos al script “jquery.jdigiclock.js” y buscaremos la línea:

       $.getJSON('lib/proxy/' + proxy + '?location=' + el.weatherLocationCode + '&metric=' + el.weatherMetric, function(data) {

Y la reemplazaremos por:

 $.getJSON('/home/GetWeather/?_location=' + el.weatherLocationCode + '&_metric=' + el.weatherMetric, function (data) {

Después crearemos el método “Index” en el controlador, y en su vista pondremos el siguiente código:


@{
     ViewBag.Title = "Weather Page";
}
<div id="digiclock"></div>

<script type="text/javascript">
$(document).ready(function () {
$('#digiclock').jdigiclock({
weatherLocationCode: 'SAM|BO|BL002|COCHABAMBA'
} );
} );


</script>
<link href="@Url.Content("~/Content/clock/jquery.jdigiclock.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery.jdigiclock.js")" type="text/javascript"></script>
    


   
Con eso nuestro plugin estará funcionando perfectamente:


Comentarios

Publicar un comentario

Entradas populares de este blog

Ejecutar comandos en el CMD de Windows desde C#

Crear una aplicacion Android en Netbeans

Modern UI Style para WPF