65.9K
CodeProject 正在变化。 阅读更多。
Home

创建 ASP.NET 天气用户控件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.84/5 (20投票s)

2010年9月23日

CPOL

5分钟阅读

viewsIcon

79816

downloadIcon

3388

本文档提供了一个关于如何创建 ASP.NET 天气控件的指南,该控件将使用 Google 天气 API 显示天气。该控件还包含一些属性,允许用户选择显示天气的地点。

Screen Shot

引言

通过本文,我将创建一个漂亮的 ASP.NET 天气控件,该控件可以用于任何 ASP.NET 页面,并可多次使用,显示不同的地点天气。

我们需要遵循以下步骤

  1. 什么是 ASP.NET Web 用户控件?
  2. 我们将从哪里获取特定地点的天气数据?
  3. 如何使用 System.XML 获取天气数据
  4. 处理意外错误
  5. 为我们的用户控件添加一些属性
  6. 一点点扩展 - 显示访问者所在地的天气

特点

我们的天气用户控件的功能和外观

  • 此控件将显示用户定义的地点天气。
  • 如果将 ShowVisitorWeather 设置为 True,此控件将显示访问者所在地的天气
  • 此控件将显示天气预报信息
  • 该控件能够因错误而隐藏自身
  • 可以在同一页面上添加多个控件,显示不同地点天气
  • 控件将显示用户选择的华氏度或摄氏度天气

Using the Code

1. 什么是 ASP.NET Web 用户控件?

用户控件是您可以放置标记和 Web 服务器控件的容器。然后,您可以将用户控件视为一个单元,并为其定义属性和方法。有时,您可能需要在页面上多次显示同一部分内容,或者在多个站点中使用。如果您可以将这部分内容绑定到一个控件中,并在多个站点中多次使用,那不是很棒吗?ASP.NET 提供了一种简单的方法来实现这一点。您可以创建自己的控件。有关用户控件的更多信息,请访问 此处。我们将创建一个天气控件。为此,我们需要先在我们的网站中添加一个用户控件。请执行以下操作:

  1. 在 Visual Web Developer / Visual Studio 2005/2008/2010 中创建一个新网站
  2. 在“解决方案资源管理器”中右键单击并添加一个新文件夹。将其命名为 Controls。
  3. 再次在“解决方案资源管理器”中右键单击并选择“添加新项”。在弹出的对话框中,选择“Web 用户控件”。将其命名为 ASTGDWeather.ascx。勾选“将代码放在单独的文件中”。按“添加”,您的新用户控件就会被添加。

Add Web User Control

您已添加了一个新的 Web 用户控件。现在我们需要对其进行设计和编码,以便它能显示天气。

2. 我们将从哪里获取特定地点的天气数据?

我们可以使用许多天气 API。对我来说,最好的就是非官方的 Google 天气 API。虽然 Google 天气 API 用于 iGoogle 获取天气信息,但该 API 本身尚未对公众正式发布。网上有一些非官方文档,但还没有官方文档。请谨慎使用。GoogleWeather 接受三个参数,它们如下:

  1. Place:这是一个必填字段。您可以传入邮政编码(例如,12203),城市名称后跟州(例如,Albany, NY),或者城市名称后跟国家名称(例如,London, England)。
  2. Language:这是一个可选字段。您必须传入一个 ISO 639-1 语言代码。有关 ISO 639-1 代码列表,请访问 此处
  3. Unit:这是一个可选字段。您可以传入 C (Celsius) 或 F (Fahrenheit)。默认情况下,它设置为 F(即华氏度)。
    与许多其他 API 不同,Google 天气 API 调用的 XML 响应相当直观。无需弄清楚某个缩写的意思,或某个代码对开发者意味着什么。要么是积极响应(包含天气状况),要么是通知错误的响应。实际上,您只需传入一个城市名称或邮政编码,例如 http://www.google.com/ig/api?weather=New+York,您将获得纽约的天气以及如下所示的 XML 格式的预报。

Add Web User Control

3. 如何使用 System.XML 获取天气数据

现在我们知道在哪里收集天气数据了。接下来,我们将使用 System.XML 解析天气值。在此之前,我们需要了解一点关于 XML 的知识。

XML 摘要: 如果您已经知道 XML 是什么,那么您可以跳过这一标题。我们这里不讨论 XML。您可以在 此处找到一个很好的 XML 教程。

编写代码:我们需要加载 Google 天气 API 提供的 XML。为此,首先声明一个 new XmlDocument

Dim doc As New XmlDocument

'Now Load the URL in XmlDocument
doc.Load("http://www.google.com/ig/api?weather=" & location)

'Now we will get the Weather Node
Dim fnode As XmlElement = doc.DocumentElement.FirstChild

'For handling multiple forcast data
Dim forcastnum As Integer = 0

'Weather node contains numbers of child nodes. Those are mainly forecast information, 
'current condition and forecast condition. We don't need forecast information. We will 
'use a For.. Next loop to examine each child nodes in Weather Root Node.

For Each cnode As XmlNode In fnode.ChildNodes
Select Case cnode.Name

Case "current_conditions"
'Process Current Conditions data here. cnode holds all child nodes in 
'current_conditions node. current_conditions has the following child 'node:
'condition
'temp_f
'temp_c
'humidity
'wind condition
'icon
'So we can use another For Next Loop and parse each child node's value.
For Each ccnode As XmlNode In cnode.ChildNodes
Select Case ccnode.Name
Case "condition"
'The value of condition is in data attribute.
ConditionTitle.InnerText = (ccnode.Attributes("data").Value)
Case "temp_f"
CurrentTemp.InnerHtml = ccnode.Attributes("data").Value & "° F"
Case "temp_c"
If viewcelcius = True Then
CurrentTemp.InnerHtml = ccnode.Attributes("data").Value & "° C"
End If
Case "humidity"
Humidity.InnerText = ccnode.Attributes("data").Value.Replace("Humidity: ", "")
Case "wind_condition"
Wind.InnerText = ccnode.Attributes("data").Value.Replace("Wind: ", "")
Case "icon"
CurrentIcon.Src = "http://www.google.com" &  cnode.Attributes("data").Value
End Select
Next

Case "forecast_conditions"
'Process Forcast Conditions data here. cnode holds all child nodes in 
'forecast_conditions. forecast_conditions has the following child node:
'day_of_week
'low
'high
'condition
'icon
'There are multiple forecast condition. We will process 3 day forecast 
'condition. we took a variable named forecastnum for this. We can use 
'another For Next Loop and parse each child node's value.
Select Case forcastnum
Case 1
For Each ccnode As XmlNode In cnode.ChildNodes
Select Case ccnode.Name
Case "day_of_week"
daytitle1.InnerText = (ccnode.Attributes("data").Value)
Case "low"
highlow1.InnerText = ccnode.Attributes("data").Value
Case "high"
highlow1.InnerText = highlow1.InnerText & "/" & ccnode.Attributes("data").Value
Case "icon"
dayicon1.Src = "http://www.google.com" & ccnode.Attributes("data").Value
Case "condition"
condition1.InnerText = ccnode.Attributes("data").Value
End Select
Next

Case 2
'Process the next forecast coding here. Do it yourself.

Case 3
'Process the next forecast coding here. Do it yourself.

End Select

End Select
Next

4. 处理意外错误

为了处理错误,我们需要找出可能发生的错误。

  1. Google 天气 API 可能会返回一个失败的 XML 结构。
  2. 由于网络问题或服务器问题,我们的加载调用可能会失败。

现在我们想处理这些错误。如果发生错误,我们的 XML 文档将加载我们服务器上之前保存的 XML 文档。如果找不到,它将退出代码执行。为了显示之前加载的 XML,我们将为不同地点在服务器上存储每个 XML 文件。加载 XML 文件后,我们将加载的 XML 与地点名称一起保存。

'There was no error reading the content, now save it for future use
doc.Save(Server.MapPath("Controls\") & location & ".xml")

我们可以检查错误,如果出现错误,我们可以像这样加载已存储的 XML:

'Check failure
If fnode.FirstChild.Name = "problem_cause" Then
'Data retrieval failed, call the local XML file
If System.IO.File.Exists(Server.MapPath("Controls\") & location & _ ".xml") Then
doc.Load(Server.MapPath("Controls\") & location & ".xml")
Else
errordetails.InnerText = "There is an error occured while retrieving data. 
			Try again later."
errordiv.Visible = True
maindiv.Visible = False
Exit Sub
Else
'Hide the whole control
maindiv.Visible = False
errordiv.Visible = False
End If
End If

5. 为我们的用户控件添加一些属性

我们的用户控件将显示哪个地点的天气?如果我们能将此权利赋予用户,那会怎么样?这是一个好主意。然后我们需要创建一个 location 属性。代码放在此处:

Dim location As String = "New+York"

Public Property setlocation() As String
        Get
            Return location
        End Get
        Set(ByVal value As String)
            location = value
        End Set
End Property

我们将添加其他名为 showcelciushideonerrorshowuserweather 的属性。

显示摄氏度

默认情况下,我们的天气用户控件将显示华氏度天气。如果 ShowCelciusTrue,它将显示摄氏度天气。代码放在此处:

Dim viewcelcius As Boolean = False
Public Property showcelcius() As Boolean
        Get
            Return viewcelcius
        End Get
        Set(ByVal value As Boolean)
            viewcelcius = value
        End Set
    End Property

出错时隐藏

这同样是布尔值。如果为 true 且发生错误,它将隐藏整个控件。

Dim hideonerrorval As Boolean = False
    Public Property hideonerror() As Boolean
        Get
            Return hideonerrorval
        End Get
        Set(ByVal value As Boolean)
            hideonerrorval = value
        End Set
    End Property

'Replace your error handling code with the following:
'Check failure
If fnode.FirstChild.Name = "problem_cause" Then
'Data retrieval failed, call the local XML file
If System.IO.File.Exists(Server.MapPath("Controls\") & location & ".xml") Then
doc.Load(Server.MapPath("Controls\") & location & ".xml")
Else
'Check hideonerror value
If hideonerrorval = False Then
'Do not hide
errordetails.InnerText = "There is an error occured while retrieving data. 
			Try again later."
errordiv.Visible = True
maindiv.Visible = False
Exit Sub
Else
'Hide the whole control
maindiv.Visible = False
errordiv.Visible = False
End If
End If
End If

6. 一点点扩展 - 显示访问者所在地的天气

现在,如果我们想扩展我们控件的功能,那么这是必需的。这将允许我们的控件显示我们网站上访问者的天气数据。要做到这一点,我们需要执行以下操作:

获取访问者 IP 地址

Dim userip As String
userip = Request.ServerVariables("REMOTE_ADDR")

获取地点

我们将使用一个免费的 Web 服务 API,它位于 此处

代码放在此处:

Dim doc1 As New XmlDocument
doc1.Load("http://ipinfodb.com/ip_query.php?ip=" & userip & "&timezone=false")
For Each ifnote As XmlNode In doc1.DocumentElement.ChildNodes
If ifnote.Name = "City" Then
location = ifnote.InnerText
End If
Next

好了。现在我们的控件能够显示访问者的所在地天气了。

在您的网站中使用天气用户控件

要使用用户控件,请转到您的 web.config 文件。在以下代码之间添加以下代码:

<controls>
<add tagPrefix="ASTGD" tagName="weather" src="~/Controls/ASTGDWeather.ascx"/>
</controls>

结论

这是我在 CodeProject 上的第一篇文章。如果有什么错误,请不要犹豫指出。我将等待您的反馈。

历史

有关此控件的更新版本,您可以查看 此链接

© . All rights reserved.