This is a migrated thread and some comments may be shown as answers.

Code for Yahoo Weather User Control/WebPart

3 Answers 129 Views
ListView
This is a migrated thread and some comments may be shown as answers.
Phil
Top achievements
Rank 2
Phil asked on 10 Jan 2012, 02:19 AM
Hi:
No question.  Just sharing some code.  This code is from a web-part that returns a 5 day weather forcast from Yahoo.  So depending on what type of web project you are using 'Web-Site or WAP.  I just suggest you use the MS create user control and then drop the following UI stuff in below the <@Control :
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
  <style type="text/css">
    .wthrTitle     { font-family: Tahoma; font-size: 14px; width: 370px; color: White; background: blue; border-top: 1px solid navy; text-align: center; }
    .wthrContainer { width: 74px; text-align: center; border: 1px; float: left; }
    .wthrDayTitle  { font-family: Tahoma; font-size: 14px; width: 100%; color: White; background: blue; border-bottom: 1px solid navy; border-top: 1px solid navy; }
    .wthrForcast   { font-family: Tahoma; font-size: 12px; color: blue; }
    .wthrTemp      { font-family: Tahoma; font-size: 10px; color: blue; }
    .wthrClear     { clear: left; }
  </style>
<div class="wthrTitle"><asp:Label ID="descriptionLabel" runat="server" Text='' /></div>
<telerik:RadListView ID="weatherRadListView" runat="server">
    <ItemTemplate>
        <div class="wthrContainer">
            <div class="wthrDayTitle"><asp:Label ID="dayLabel" runat="server" Text='<%# Eval("DayName") %>' /></div><br />
            <asp:Image ID="forcastImage" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' /><br />
            <asp:Label ID="forcastLabel" runat="server" Text='<%# Eval("Forcast") %>' CssClass="wthrForcast" /><br />
            <div class="wthrForcast"><asp:Label ID="highLabel" runat="server" Text='<%# Eval("High") %>' />° -
                <asp:Label ID="lowLabel" runat="server" Text='<%# Eval("Low") %>' />°</div><br />
        </div>
    </ItemTemplate>
</telerik:RadListView>
<br class="wthrClear" />
<asp:HiddenField ID="zipcodeHidden" runat="server" Value="49333" />

I have supplied both C# and VB.  Piece in the following code not trying to damage the code behind class name:
// By Phil Huhn 2012-01-08
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//
using System.Xml;
using System.Xml.Linq;
using System.Net;
//
 
namespace Telerik.UserControls
{
    public partial class YahooWeather : System.Web.UI.UserControl
    {
        //
        // ------------------------------------------------------------------------
        //   Properties
        //       ZipCode
        //
        #region "Properties"
        //
        /// <summary>
        /// External way to pass values to user control
        /// </summary>
        /// <value></value>
        /// <returns></returns>
        /// <remarks></remarks>
        public string ZipCode
        {
            get { return zipcodeHidden.Value; }
            set { zipcodeHidden.Value = value; }
        }
        //  
        #endregion
        //
        /// <summary>
        /// call during each postback
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks></remarks>
        protected void Page_Load(object sender, EventArgs e)
        {
            GetWeather(ZipCode);
        }
        //
        /// <summary>
        /// Get weather from yahoo
        /// </summary>
        /// <param name="zipCode"></param>
        /// <remarks></remarks>
        protected void GetWeather(string zipCode)
        {
            try
            {
                XDocument xmlData = XDocument.Load("http://xml.weather.yahoo.com/forecastrss/" + zipCode + "_f.xml");
                //
                List<WeatherItem> _list = new List<WeatherItem>();
                string _description = null;
                System.DateTime _date;
                //...<channel>
                foreach (XElement _row in xmlData.Root.Elements("channel"))
                {
                    foreach (XElement _field in _row.Elements())
                    {
                        //<title>Yahoo! Weather - Any Town</title>
                        //<link></link>
                        //<description>Yahoo! Weather for Any Town</description>
                        if ((_field.Name.ToString() == "description"))
                        {
                            // cherry pick the desired data at this level.
                            _description = _field.Value;
                            descriptionLabel.Text = _description;
                        }
                        //<language>en-us</language>
                        //<lastBuildDate>Sat, 07 Jan 2012 10:51 am EST</lastBuildDate>
                        if ((_field.Name.ToString() == "lastBuildDate"))
                        {
                            string _dateString = _field.Value.Substring(5);
                            _date = DateTime.Parse(_dateString.Substring(0, _dateString.Length - 4));
                            descriptionLabel.Text = _description + " at " + _date.ToShortTimeString();
                        }
                        //<ttl>60</ttl>
                        //<yweather:location city="Any Town" region="MI" country="US"/>
                        //<yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
                        //<yweather:wind chill="35" direction="310" speed="14"/>
                        //<yweather:atmosphere humidity="65" visibility="10" pressure="29.89" rising="1"/>
                        //<yweather:astronomy sunrise="8:02 am" sunset="5:17 pm"/>
                        //<image>
                        //<item>
                        if (_field.Name.ToString() == "item")
                        {
                            foreach (XElement _itm in _field.Elements())
                            {
                                if (_itm.Name.LocalName == "forecast")
                                {
                                    WeatherItem _wi = new WeatherItem();
                                    _wi.YahooForcast(_itm);
                                    _list.Add(_wi);
                                }
                            }
                        }
                    }
                }
                if (_list.Count > 0)
                {
                    _list[0].DayName = "Today";
                }
                weatherRadListView.DataSource = _list;
                weatherRadListView.DataBind();
            }
            catch (Exception e)
            {
                int _i = 1;
            }
        }
 
        //
    }
}
public class WeatherItem
{
    public string DayName { get; set; }
    public System.DateTime Day { get; set; }
    public int Low { get; set; }
    public int High { get; set; }
    public string Forcast { get; set; }
    public string Code { get; set; }
    public string ImageUrl { get; set; }
    public string LocalImageUrl { get; set; }
    protected string LocalImagePath = "../Images/Weather/";
    //
    public WeatherItem()
    {
    }
    //
    public WeatherItem(string localImagePath)
    {
        LocalImagePath = localImagePath;
    }
    //
    //   <yweather:forecast day="Sun" date="8 Jan 2012"
    //       low="28" high="37" text="Partly Cloudy" code="30"/>
    //
    public void YahooForcast(XElement forcastItem)
    {
        DayName = forcastItem.Attribute("day").Value;
        Day = Convert.ToDateTime(forcastItem.Attribute("date").Value);
        Low = Convert.ToInt32(forcastItem.Attribute("low").Value);
        High = Convert.ToInt32(forcastItem.Attribute("high").Value);
        Forcast = forcastItem.Attribute("text").Value;
        Code = forcastItem.Attribute("code").Value;
        ImageUrl = "http://l.yimg.com/a/i/us/we/52/" + Code + ".gif";
        LocalImageUrl = LocalImagePath + Code + ".gif";
    }
}

And here is the same code in vb.net:
' By Phil Huhn 2012-01-08
Option Strict On
Option Explicit On
'
Imports System.Xml
Imports System.Net
'
Public Class YahooWeather
    Inherits System.Web.UI.UserControl
    '
    ' ------------------------------------------------------------------------
    '   Properties
    '       ZipCode
    '
#Region "Properties"
    '
    ''' <summary>
    ''' External way to pass values to user control
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property ZipCode() As String
        Get
            Return zipcodeHidden.Value
        End Get
        Set(ByVal value As String)
            zipcodeHidden.Value = value
        End Set
    End Property
    '  
#End Region
    '
    ''' <summary>
    ''' call during each postback
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        GetWeather(ZipCode)
    End Sub
    '
    ''' <summary>
    ''' Get weather from yahoo
    ''' </summary>
    ''' <param name="zipCode"></param>
    ''' <remarks></remarks>
    Protected Sub GetWeather(zipCode As String)
        Try
            Dim xmlData As Linq.XDocument = _
                XDocument.Load("http://xml.weather.yahoo.com/forecastrss/" & zipCode & "_f.xml")
            '
            Dim _list As New List(Of WeatherItem)
            Dim _description As String = Nothing
            Dim _date As Date = Nothing
            For Each _row As XElement In xmlData.Root.Elements("channel") '...<channel>
                For Each _field As XElement In _row.Elements
                    '<title>Yahoo! Weather - Any Town</title>
                    '<link></link>
                    '<description>Yahoo! Weather for Any Town</description>
                    If (_field.Name.ToString() = "description") Then
                        ' cherry pick the desired data at this level.
                        _description = _field.Value
                        descriptionLabel.Text = _description
                    End If
                    '<language>en-us</language>
                    '<lastBuildDate>Sat, 07 Jan 2012 10:51 am EST</lastBuildDate>
                    If (_field.Name.ToString() = "lastBuildDate") Then
                        Dim _dateString As String = _field.Value.Substring(5)
                        _date = DateTime.Parse(_dateString.Substring(0, _dateString.Length - 4))
                        descriptionLabel.Text = _description & " at " & _date.ToShortTimeString
                    End If
                    '<ttl>60</ttl>
                    '<yweather:location city="Any Town" region="MI" country="US"/>
                    '<yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
                    '<yweather:wind chill="35" direction="310" speed="14"/>
                    '<yweather:atmosphere humidity="65" visibility="10" pressure="29.89" rising="1"/>
                    '<yweather:astronomy sunrise="8:02 am" sunset="5:17 pm"/>
                    '<image>
                    '<item>
                    If _field.Name.ToString() = "item" Then
                        For Each _itm As XElement In _field.Elements
                            If _itm.Name.LocalName = "forecast" Then
                                Dim _wi As New WeatherItem()
                                _wi.YahooForcast(_itm)
                                _list.Add(_wi)
                            End If
                        Next
                    End If
                Next
            Next
            If _list.Count > 0 Then
                _list(0).DayName = "Today"
            End If
            weatherRadListView.DataSource = _list
            weatherRadListView.DataBind()
        Catch e As Exception
            Dim _i As Integer = 1
        End Try
    End Sub
    '
End Class
Public Class WeatherItem
    Public Property DayName() As String
    Public Property Day() As Date
    Public Property Low() As Integer
    Public Property High() As Integer
    Public Property Forcast() As String
    Public Property Code() As String
    Public Property ImageUrl() As String
    Public Property LocalImageUrl() As String
    Protected LocalImagePath As String = "../Images/Weather/"
    '
    Public Sub New()
    End Sub
    '
    Public Sub New(localImagePath As String)
        localImagePath = localImagePath
    End Sub
    '
    '   <yweather:forecast day="Sun" date="8 Jan 2012"
    '       low="28" high="37" text="Partly Cloudy" code="30"/>
    '
    Public Sub YahooForcast(forcastItem As XElement)
        DayName = forcastItem.Attribute("day").Value
        Day = CDate(forcastItem.Attribute("date").Value)
        Low = CInt(forcastItem.Attribute("low").Value)
        High = CInt(forcastItem.Attribute("high").Value)
        Forcast = forcastItem.Attribute("text").Value
        Code = forcastItem.Attribute("code").Value
        ImageUrl = "http://l.yimg.com/a/i/us/we/52/" & Code & ".gif"
        LocalImageUrl = LocalImagePath & Code & ".gif"
    End Sub
End Class

You can drag the control onto your regular form:

<%@ Register src="UserControls/YahooWeather.ascx" tagname="YahooWeather" tagprefix="uc1" %>
...
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<uc1:YahooWeather ID="YahooWeather1" runat="server" ZipCode="48103" />

You can set the us zip code via a property...

Have fun:
Phil

3 Answers, 1 is accepted

Sort by
0
Accepted
Tsvetina
Telerik team
answered on 11 Jan 2012, 09:24 AM
Hi Phil,

Thank you for sharing your knowledge with the community, I think it would be useful both for developers who want to do this integration and for those who need an example of binding RadListView to live XML-based data.
As a token of gratitude for contributing with this sample, you can find your Telerik points updated.

Kind regards,
Tsvetina
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Phil
Top achievements
Rank 2
answered on 12 Jan 2012, 03:43 AM
Hi All:

Little update, I added and AJax update panel and made it the style container, such that title is now 100%.  This is all meant to be less than half of a 800px web-parts page.  Have fun.
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
  <style type="text/css">
    .wthrTitle     { font-family: Tahoma; font-size: 14px; width: 100%; color: White; background: blue; border-top: 1px solid navy; text-align: center; }
    .wthrContainer { width: 74px; text-align: center; border: 1px; float: left; }
    .wthrDayTitle  { font-family: Tahoma; font-size: 14px; width: 100%; color: White; background: blue; border-bottom: 1px solid navy; border-top: 1px solid navy; }
    .wthrForcast   { font-family: Tahoma; font-size: 12px; color: blue; }
    .wthrTemp      { font-family: Tahoma; font-size: 10px; color: blue; }
    .wthrClear     { clear: left; }
  </style>
<telerik:RadAjaxPanel ID="weatherRadAjaxPanel" runat="server" Width="370px">
    <div class="wthrTitle"><asp:Label ID="descriptionLabel" runat="server" Text='' /></div>
    <telerik:RadListView ID="weatherRadListView" runat="server">
        <ItemTemplate>
            <div class="wthrContainer">
                <div class="wthrDayTitle"><asp:Label ID="dayLabel" runat="server" Text='<%# Eval("DayName") %>' /></div><br />
                <asp:Image ID="forcastImage" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' /><br />
                <asp:Label ID="forcastLabel" runat="server" Text='<%# Eval("Forcast") %>' CssClass="wthrForcast" /><br />
                <div class="wthrForcast"><asp:Label ID="highLabel" runat="server" Text='<%# Eval("High") %>' />° -
                    <asp:Label ID="lowLabel" runat="server" Text='<%# Eval("Low") %>' />°</div><br />
            </div>
        </ItemTemplate>
    </telerik:RadListView>
    <br class="wthrClear" />
    <asp:HiddenField ID="zipcodeHidden" runat="server" Value="49333" />
</telerik:RadAjaxPanel>
0
Phil
Top achievements
Rank 2
answered on 22 Mar 2012, 12:14 AM
Hi:
Another change...
I took the loading out of page init and move it to needs data.  You have to remove the manual bind (that a needs data thing).
Phil
Tags
ListView
Asked by
Phil
Top achievements
Rank 2
Answers by
Tsvetina
Telerik team
Phil
Top achievements
Rank 2
Share this question
or