Yahoo API的天气功能使用起来还是很方便的,地址:http://xml.weather.yahoo.com/forecastrss?p=[location]&u=[type]/。其中p是城市的天气代码(可网上查询),type是指c(摄氏度)和f(华氏度)。

   网页返回的是一个xml页面,所以在读取时利用xmlDocument选择当中的节点读取需要的数据。另外放置一个dropdownlist选择城市,这里由于需要异步更新,需要利用到AJAX,所以使用了updatePanel.

   温度类型设置在webpart toolpane中选择,这里有很多种方法,由于本人比较笨也比较懒,这里使用最直接简单的方法,定义枚举类型。

    API返回的xml文本例子如下

View Code
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
<title>Yahoo! Weather - Sunnyvale, CA</title>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html</link>
<description>Yahoo! Weather for Sunnyvale, CA</description>
<language>en-us</language>
<lastBuildDate>Fri, 18 Dec 2009 9:38 am PST</lastBuildDate>
<ttl>60</ttl>
<yweather:location city="Sunnyvale" region="CA" country="United States"/>
<yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
<yweather:wind chill="50" direction="0" speed="0" />
<yweather:atmosphere humidity="94" visibility="3" pressure="30.27" rising="1" />
<yweather:astronomy sunrise="7:17 am" sunset="4:52 pm"/>
<image>
<title>Yahoo! Weather</title>
<width>142</width>
<height>18</height>
<link>http://weather.yahoo.com</link>
<url>http://l.yimg.com/a/i/us/nws/th/main_142b.gif</url>
</image>
<item>
<title>Conditions for Sunnyvale, CA at 9:38 am PST</title>
<geo:lat>37.37</geo:lat>
<geo:long>-122.04</geo:long>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html</link>
<pubDate>Fri, 18 Dec 2009 9:38 am PST</pubDate>
<yweather:condition text="Mostly Cloudy" code="28" temp="50" date="Fri, 18 Dec 2009 9:38 am PST" />
<description><![CDATA[
<img src="http://l.yimg.com/a/i/us/we/52/28.gif"/><br />
<b>Current Conditions:</b><br />
Mostly Cloudy, 50 F<BR />
<BR /><b>Forecast:</b><BR />
Fri - Partly Cloudy. High: 62 Low: 49<br />
Sat - Partly Cloudy. High: 65 Low: 49<br />
<br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>
(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>
]]></description>
<yweather:forecast day="Fri" date="18 Dec 2009" low="49" high="62" text="Partly Cloudy" code="30" />
<yweather:forecast day="Sat" date="19 Dec 2009" low="49" high="65" text="Partly Cloudy" code="30" />
<guid isPermaLink="false">USCA1116_2009_12_18_9_38_PST</guid>
</item>
</channel>
</rss>

    在VisualWebpartUserControl.ascx 中加入代码, 也可以直接在设计页面拖放控件。这里加入了两个label和一个dropdownlist在updatepanel中,由于更新天气由DropDownList出发,设置updateModel为Conditional并设置trigger节点

View Code
<asp:ScriptManagerProxy runat="server" ID="scriptManagerP1">
</asp:ScriptManagerProxy>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >

<ContentTemplate>
<asp:Label ID="lblCity" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:DropDownList ID="ddlistCity" runat="server" Height="20px"
onselectedindexchanged
="ddlistCity_SelectedIndexChanged" Width="79px"
AutoPostBack
="True">

<asp:ListItem Selected="True" Value="CHXX0037">广州</asp:ListItem>
<asp:ListItem Value="CHXX0008">北京</asp:ListItem>

<asp:ListItem Value="CHXX0140">厦门</asp:ListItem>
<asp:ListItem Value="CHXX0110">青岛</asp:ListItem>

</asp:DropDownList>

<br />

</ContentTemplate>

<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlistCity" />
</Triggers>
</asp:UpdatePanel>

      请求xml返回并读取数据,在VisualWebpartUserControl.ascx.cs中加入以下,其中重写了Render方法,这个方法是在tool pane中设置参数应用后能更新数据的必要步骤。

View Code
using System;
using System.IO;
using System.Net;
using System.Web.UI;
using System.Xml;

namespace WeatherWebpart.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
public VisualWebPart1 webpart;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ShowWeather();
}


}

protected override void Render(HtmlTextWriter writer)
{
ShowWeather();
base.Render(writer);
}


protected void ddlistCity_SelectedIndexChanged(object sender, EventArgs e)
{
ShowWeather();

}

protected void ShowWeather()
{
#region //根据选择城市请求返回xml
string tempertureType = webpart.WeatherT.ToString();
//string tempertureType = webpart.WeatherType;

if (tempertureType != "c" && tempertureType != "f")
{
tempertureType
= "c";
}
string url = "http://xml.weather.yahoo.com/forecastrss?p=" + ddlistCity.SelectedValue+"&u="+tempertureType;
WebRequest xmlRequest
= WebRequest.Create(url);
WebResponse xmlResponse
= xmlRequest.GetResponse();
Stream xmlStream
= xmlResponse.GetResponseStream();
XmlDocument xmlDom
= new XmlDocument();
xmlDom.Load(xmlStream);
#endregion

#region //读取节点,对控件赋值

lblCity.Text
= ddlistCity.SelectedItem.Text;
XmlNode cityNode
= xmlDom.SelectSingleNode("/rss/channel/lastBuildDate");
System.Globalization.DateTimeFormatInfo dateFormat
= new System.Globalization.CultureInfo("en-us",true).DateTimeFormat;
string dateTransfer = cityNode.InnerText;
dateTransfer
= dateTransfer.Substring(0, 16).Trim();
dateTransfer
= Convert.ToDateTime(dateTransfer).ToString("dd/MM/yyyy",dateFormat);
lblCity.Text
= lblCity.Text + " " + dateTransfer;
XmlCDataSection CData
= xmlDom.SelectSingleNode("/rss/channel/item/description").FirstChild as XmlCDataSection;
Label1.Text
= CData.Value;
#endregion
}


}
}

     到这里读取天气的功能基本OK了,接下来就是要自定义tool pane,在定义新的一栏时,若字段类型为string,显示出的则是textbox;若字段类型为Enum,则显示出来的就是CamboBox,编辑VisualWebpart.cs

View Code
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections;
using System.Collections.Generic;

namespace WeatherWebpart.VisualWebPart1
{
[ToolboxItemAttribute(
false)]
public class VisualWebPart1 : System.Web.UI.WebControls.WebParts.WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @"~/_CONTROLTEMPLATES/WeatherWebpart/VisualWebPart1/VisualWebPart1UserControl.ascx";

protected override void CreateChildControls()
{
Control control
= Page.LoadControl(_ascxPath);

VisualWebPart1UserControl v
= control as VisualWebPart1UserControl;
v.webpart
= this;

Controls.Add(control);

}


#region //使用枚举类型传值
public enum weatherType2
{
c, f
}

private weatherType2 weatherT;
[WebBrowsable,
Category(
"Tempreture Type"),
DefaultValue(
"c"),
Personalizable(),
FriendlyName(
"tempreture type:"), Description("select tempreture type")]
public weatherType2 WeatherT
{
get { return weatherT; }
set { weatherT = value; }
}

#endregion
}
}

    代码过程重要的一点是           

VisualWebPart1UserControl v = control as VisualWebPart1UserControl;
v.webpart = this;

暂时只到这样的方法才可以在VisualWebPartUserControl中读取到Visual Webpart的变量。

部署插入webpart中 效果如下~

   

作者: 飔颸颸飔 发表于 2011-07-15 18:14 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"