Download From CodePlex
View a Demo
After looking around for a simple, customizable ASP.NET control that reads weather and forecast data from weather.com’s xml feed…and finding nothing, I decided to create one myself.
This ascx control displays current weather and weather forecast data on your ASP.NET website straight from an xml feed on weather.com. This is meant to be very easy to implement and extremely easy to customize. All you need to do is add a few files to your site, copy and paste a couple lines of code, switch a few variables, and you’re off and running.
Oh…and this control also caches the xml data from weather.com so it doesn’t ping the xml data with every user request. I have it set to clear and refresh the cached data every 15 minutes, but you can set it to any time frame you want…or even turn off caching if you so chose.
Without further adieu, let’s get started.
VERY IMPORTANT: You will first need to register on weather.com for their xml weather service. They provide this all for FREE. This will get you a License Key, PartnerID, and LocationID which are all required to use this control. So….go to weather.com now and get ‘em.
https://registration.weather.com/ursa/xmloap/step1??
Got ‘em? You’re 90% there…Keep reading.
OK…so you have your weather.com account information. Now, download the zip file at the top of this web page and unzip it. Next, do the following:
Step1: copy the WeatherControl.ascx file into your web project
Step2: copy and paste the entire ccicons folder into your web project
Step3: copy the css folder into your web project (contains stylesheet.css)
Step4: in any aspx file you want to use this weather control, add the following code (see the default.aspx file for example):
<%@ Register TagPrefix="My" TagName="Weather" src="WeatherControl.ascx" mce_src="WeatherControl.ascx" %>
And add the following code where you want the generated weather table to show up on your web page. YOU NEED TO ENTER YOUR OWN LicenseKey, PartnerID, and LocationID values that you got from weather.com!!!:
NOTE: For LocationID visit: http://aspnetresources.com/tools/locid.aspx
<My:Weather ID="Weather" runat="server" LicenseKey = "" PartnerID = "" LocationID = "" EnableWeatherCaching = "False" TimeToRefreshCache = "15" NumForecastDays = "3" showDateInForecast = "True" showWind = "True" forecastIconSize = "sm" showLastUpdateLabel = "True" showCelsius = "False" showKPH = "False" locationClass = "ccLoc" curTempClass = "temp" curDescClass = "cc" curWindClass = "curWind" fcastDateClass = "fcastDate" fCastTableClass = "fcastTable" fcastWeekdayClass = "fcastWeekDay" lastUpdateClass = "cc" />
The definable properties listed above are all set to the control’s default values. I listed all of them so you can see which properties you can set in the control. They are pretty self-explanatory but if you want to see the definition of each property, just open the ascx file. You’ll see a comment next to each public property that describes it. If the default values for the control are OK for your application, then simply use the following code and just set your license variables and location id:
<My:Weather ID="Weather" runat="server" LicenseKey = "" PartnerID = "" LocationID = "" />
That’s it!
You can go into the ascx file and, at the bottom, change the format of the table to whatever layout you want.
If you want to customize it further…go nuts. You can pull even more data out of the weather.com xml file as well. Just use the two “Node Reading” functions at the top. See the code for examples on how to navigate through the xml tags…pretty self explanatory.Enjoy!
Download From CodePlex
View a Demo

I'm a web developer, UI/UX specialist and online strategist with over 10 years of experience in the field. I am currently freelancing and am available for hire. I have hands-on experience in all stages of the SDLC. If you or your business needs a web site, could use some help with your online strategy, or if you need to get started with SEM, please feel free to contact me.
I can help you with: Web Site Design and Development, Search Engine Optimization, Search Engine Marketing, Multivariate Testing, Metrics Analysis, Campaign Optimization, Social Site Integration, E-mail Marketing and everything else that has to do with the Web.
I work/haved worked with the following technologies: XHTML, CSS, Javascript, Ajax, JQuery, MySQL, SQL Server, ASP, ASP.Net, Coldfusion, PHP, Wordpress, Flash, Google Analytics, Google Adwords.
@John Batdorf ,
Could you please share your code here to exclude the control when there is an error? I am having this problem when XOAP is down, my whole website goes down too. I just want to exclude this control when there is an error loading.
Cheers,
Tajuddin
[...] http://www.leonamarant.com/2008/01/09/a-free-and-simple-aspnet-weather-control-you-can-customize-in-... [...]
Great post…
I am so happy to use it in my project.
Thanks
You’ll notice that RIGHT NOW the XOAP service is totally down. The code does no checking nor error handling for this. You should consider adding that to the code.
In fact, it takes the whole http://www.theseabreezeinn.com site down! I’ve added an error check in my code, as well as I don’t call the module again if it’s found to be down for that session.
do enyone know way i cant show it in celcius i get the following errors System.FormatException: Input string was not in a correct format.
hi
I am getting the same error-
System.Net.WebException: The remote name could not be resolved: ‘xoap.weather.com’
urgent plz.
any help would be appreciated.
Please share the C# code for the same,if anyone has worked on it.
hi
I am getting the following error-
System.Net.WebException: The remote name could not be resolved: ‘xoap.weather.com’
Also please can any one could share the C# version of the code?
Hi,
Thanks for the nice and easy control. When I am trying to run this I have getting following error, any idea/s?
There are multiple root elements. Line 2, position 2.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Xml.XmlException: There are multiple root elements. Line 2, position 2.
Source Error:
Line 158: End If
Line 159: Else
Line 160: xmlDoc.Load(URLString)
Line 161: Application(“weatherLastUpdated”) = DateTime.Now
Line 162: End If
Could not figure it out why I am having this problem. Sorry for sending it twice, I just want have follow up notification.
Regards,
Tajuddin
thx alot for ur help.
i found the solution: the problem arrised when i commented these lines:
xmlDoc.Load(URLString)
Application(“weatherLastUpdated”)=DateTime.Now
lblLocation.Text = “Weather in ” & NodeText(xmlDoc, “/weather/loc/dnam”)
and when i ucommented those lines it gave me no errors.
i’m just wondering if i can display weather information in Arabic language ??
hamzeh: it looks like you need to check to see if the value returned for the temperature is in the right format…then, only if it is, perform the conversion. In other words, there needs to be a conditional statement within that IF statement that checks to see if the value you are trying to convert can be first converted to an integer. I think you can use a “TRY-CATCH” statement…something like:
Function displayTemp(ByVal degF As String, ByVal dispCel As Boolean) As String
If dispCel Then
TRY
degF = Int(degF)
displayTemp = System.Math.Round((degF – 32) / 1.8)
CATCH
displayTemp = “N/A”
END TRY
Else
—do the other stuff–
End If
End Function
…something like that. give it a shot.
i changed showCelsius = “False” and i got the following error:
Conversion from string “N/A” to type ‘Date’ is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Conversion from string “N/A” to type ‘Date’ is not valid.
Source Error:
Line 187: Dim localTime As DateTime
Line 188: Dim Day1ShowNight As Boolean
Line 189: localTime = NodeText(xmlDoc, “/weather/loc/tm”)
Line 190: ’show night forecast for current day if local time is past 2pm
Line 191: If Right(localTime.ToString, 2) = “PM” And Hour(localTime) >= 14 Then
hamzeh: it looks as if somewhere in the script an invalid value for temperature is being passed into that function. try debugging by first setting the default temperature format back to Degrees F…then see what happens. If you continue to experience errors, e-mail me through my contact form on this site and I will try to help you further.
i have this error:
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: Input string was not in a correct format.
Source Error:
Line 72: Function displayTemp(ByVal degF As String, ByVal dispCel As Boolean) As String
Line 73: If dispCel Then
Line 74: degF = Int(degF)
Line 75: displayTemp = System.Math.Round((degF – 32) / 1.8)
Line 76: Else
any idea?
any help plzzz ?
This is classic asp script will allow you to monitor your current local weather via a Weather.com XML feed.
It parses the XML data and then outputs formatted HTML.
Hi Leon, I tried your code, but it doesn’t seem to be working for me.When I first ran my code: I got ‘WebException was unhandled by user code’-it pointed to this line: xmlDoc.Load(URLString). I then added a try and catch clause just to see what will happen.
I got:”InvalidCastException was unhandled by user code”-pointing to this line:
localTime = NodeText(xmlDoc, “/weather/loc/tm”), apparently ‘NodeText()’ is always returning ‘N/A’. I commented this line out, and all I got was: N/A all over the screen, the images were also not displaying.
Is it because of my location (I’m not in US by the way), if yes, then what can I do to get this weather control working?
Thanks in advance.
Yeah, I can understand about using others code! I was just messing with your code to see if I could get it to work with WeatherBug’s API. I guess it’s more than I can do as their API returns information which is different, although well documented, but that doesn’t do me any good…
You should create a VB control to interact with WeatherBug which would give you the same small footprint above, as well as a bigger full-page interaction with the full gambit of data they offer!
Anyway, thanks again and this is the best information that I have found anywhere on the net… and I have been talking to all the major weather .coms … none have clear examples that I can find… not even good working examples to interact with thier own api’s!
Thanks again!
TT
Tom: if removing “mce_src” worked for you, then it works for me! to tell you the truth, I’m not even sure what that does (some back-end .NET voodoo that I don’t care to understand).
NP with the inbound link either. Feel free to reply to this thread with a link to your site as well.
Glad I could be of help. God knows I’ve used my fair share of other people’s code…just returning the favor.
Also, I linked to this page from mine. Hope you don’t mind!
Yes, that did the job, I set the 3 to 0 (zero) for EST in line 265.
So, was it ok to remove the mce_src attribute to register the control? Seems to be working without it.
Also, i’d like to tell you that I have looked for 3 days for easy ways to attach to a weather service and yours is BY FAR the easiest I have run across to understand and edit with a small footprint in my site. I really apprciate you and the time you took to do this!
Thanks again m8!
Tom
Tom: Look at line 265. I adjust the time there to accommodate for my server being 3 time zones away from the location I’m displaying…hence the 3 hour adjustment. Change the value there to change the displayed time. Let me know if that solves your problem.
I am having an issue with the date as it’s saying that it is 1:27 PM when it’s 10:27 AM EST. I saw in the post above that you made it for EST … is there something i can check?
I just removed the mce_src attribute and it worked … is that a problem?
This seems to be great, all instructions are easy to understand but when I try to browse to the page, i get:
Parser Error Message: The ‘mce_src’ attribute is not supported by the ‘register’ directive.
and then it references:
Line 2:
any thoughts on that? Thanks again!
Hi, anyone converted this control to C#? Thanks
Hi, many thanks of the example. One problem though, how am I going to make the weather control changeable, so I can change the city in the drop down list?
Looks great so far
Anybody tried to TRANSLATE static and dynamic content?
-Ideally some kind of automatic translation where i can modify he dictionary (Need French and Dutch).
We also need 24h clock.
Hello !!
Great example Leon. Thanks for the uploading the code.
I am a little stuck though. I’ve got an intranet site and have the project set up as per your instructions. I’ve also got the Partner ID and License Key from weather.com, however when I run the app I get the following error message.
“Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.”
I can see from the blogs, someone else also received a similar error. Did anyone find a solution to this?
Please advice. Appreciate your time and help.
I’m using this control and it’s really a good control. But, my problem is that I want show the weather according to my date. Currently it shows the on the base of Date.Now.
can anyone help me in this…
I cannot get any of the online converter to properly convert this code to C#. Can someone please convert it and share it. Here is my email hm_team2003@hotmail dot com. I would be willing to pay to have working c# code!
I cannot get any of the online converter to properly convert this code to C#. Can someone please convert it and share it. Here is my email hm_team@hotmail dot com. I would be willing to pay to have working c# code!
Can come one please share a converted c# version of this? I would really appreciate it. I’m having problems converting this:
Function NodeAttr(ByRef xmlDOM As XmlDocument, ByVal sXPathQuery As String, ByVal myAttr As String) As String Dim oNode As XmlNode oNode = xmlDOM.SelectSingleNode(sXPathQuery) If Not (oNode Is Nothing) Then NodeAttr = UCase(Left(oNode.Attributes.GetNamedItem(myAttr).InnerText, 3)) Else NodeAttr = "N/A" End If Return NodeAttr End FunctionIt is working fine normally,but when I host it on the IIS it is givinng the following error.
“An existing connection was forcibly closed by the remote host ”
Can anybody fix this problem.It is very urgent.
I’ve seen where several people have converted to C# (JeffH) anyone have this posted anywhere?????? Would really like c# version.
Thanks
Tinhtam and Leon,
I was wonderng if you all found a fix for the error:
“Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.”
I also got the code to work flawlessly on my development and staging server, however when I moved it to the production server it gave the above error for some reason.
Excellent weather control.
Thanks for any assistance.
John
Its very useful for me. Your Explanation was very good. I think you are a good faculty for teaching web service.
Thanking You.
I want touch with you. I want learn more from you that only the reason.
Again Thank you..
Did anyone ever rewrite this in C#?
Hi, I want to add the ability to provide weather for UK post codes, is there a database of locationIDs?
Many Thanks
James
JeffH…thanks for the feedback. A few weeks ago, weather.com changed the url for their xml feed by 1 letter and hence, broke the control. I also caught this error and corrected it. In addition to changing the url, I also added error checking inside the control. In the somwhat likely case that this will happen again, the control will now not break your page but will instead display an error. Other modifications were made as well to streamline the control further.
You can find the new control on codeplex by clicking on the link at the top of this blog.
I have been using this control for months, And I Love it like the others… But It broke a few weeks ago, apparently because they change the URL format… But i was able to snag it out of your version, Thanks! I have also converted it to c# and customized it alittle for my site… But if you would like a copy of it, just let me know…
By the way, when I register on weather.com, do I have to put the exact domain name that I’m using or the licensekey should be working for any site. Thanks.
Tinhtam
Leon,
I can connect to the weather.com service from my web server. I even cut and paste the url to the browser from my web server and it did return the xml information. I’m not sure why xml.Load(URLString) doesn’t work. You have any ideas what I am missing here… Thanks.
Tinhtam
Tinhtam…that looks to me like a server specific error. It looks as if maybe your server is preventing your code from connecting to the weather.com service??? If this turns out to be a code issue however, please let me know so I can correct the code.
First, thanks for the great user control Leon. You did an excellent job.
Second, I have successfully converted this control from VB to C#, it works perfectly when I run from Visual Studio. Yet, when I promote it to my server and run it I got this error (see below). Any advice please. Thank you.
“Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.”
Tinhtam
I updated the code with the following:
- changed weather.com xml url to new url
- added some basic error checking
- all properties are now public and can be set directly in the aspx page with no need to modify the ascx file
- added date function by eddy that catches date conversion errors
enjoy!!!
i’ve added the control and worked beautifully, however today it is not working…and if you go to your page example (www.theseabreezeinn.com), you will see your page does not work either
My contrib: I use a function to return a valid date (with hours and minutes)
'--get base date for showdate in forecast --
Dim baseDate As DateTime
baseDate = WeatherDateToDate(NodeText(xmlDoc, "//weather/dayf/lsup"))
Dim updDate As DateTime
updDate = WeatherDateToDate(NodeText(xmlDoc, "//weather/cc/lsup"))
Function WeatherDateToDate(ByVal stringDate As String) As Date
'4/25/08 2:00 PM Local Time
Dim separados As Array = stringDate.Split(" ")
Dim fechaseparados As Array = separados(0).Split("/")
Dim retval As Date = DateSerial(CInt("20" + fechaseparados(2)), CInt(fechaseparados(0)), CInt(fechaseparados(1)))
Dim HoraSeparados As Array = separados(1).Split(":")
retval.AddHours(CInt(HoraSeparados(0)) + IIf(separados(2) = "PM", 12, 0))
retval.AddMinutes(CInt(HoraSeparados(1)))
Return retval
End Function
ok!
thanx!
Wow, great work! I had been searching for days and trying a few other code projects out there. This approach was a no brainer in my book. Took me less than 15 minutes from start to finish. Worked the first time I ran it. Thanks for the great contribution!!
Did you use this link:
http://www.weather.com/services/xmloap.html
?
i signed up in the weather.com, they sent me an email, but i cant find a partnerid and a licencekey!!! It only contains the locationID
Any help?
I keep getting
System.InvalidCastException: Conversion from string “4/7/08 10:04 AM Local” tp tu[e ‘Date’ is not valid.
I used one of the posters code above to see if that helped and it didnt. Any idea ?
I’m having problems with the .png files. They are always showing up with a gray background. When I look at them in Photoshop, the background is transparent. I’m using ASP.Net 1.1. Is there something that I’m missing?
Hi,
Great UserControl.
Exist a C# version? (user “rewdboy” can share?)
One ideia for this Control, a translation section where all text displayed can be translated. More quick to have the messages in another language.
Leon, you update the User Control with tips/bugs from other users (referred in post’s) ?
Regards, great work.
LB
Hi,
Can i use this as a webpart part in my MOSS site???
but i wat to convert in webpart application…can anybody helpout me in this.
Kuldeep Kadyan
Ed…change this variable:
Dim showCelsius As Boolean = False
in the “variables” section to True…that should display your temps in Celsius. Let me know if this doesn’t work…I thought I successfully solved that but I could be mistaken.
Also, I think the high temp for the current day is only given in the xml feed during the day. after a certain time, the high temp is not provided (this is by design) so the control will not display it.
hope that helps.
Post 11.,
please don’t spend time on it. It seems that weather.com is (so far) always sending “N/A” in the xml file for that field!
thanks anyway, ed
thanks for the time anybody spends,
what do I do wrong?
when using the original .ascx (.zip) file I always get “N/A” for the high temperature of the current day like “H: N/A” . Otherwise the screen is complete with correct info … as long as I use Farenheit!?
However I would like to change to Celsius (i.e. unit=m) BUT then I get , correctly, an error:
“Conversion from string “N/A” to type ‘Double’ is not valid.” at
If dispCel Then
degF = Int(degF) ‘ ==> error!
displayTemp = System.Math.Round((degF – 32) / 1.8)
Else
displayTemp = degF
……………..
thanks for any help/hint
ed
in case someone has the d/m/y format or has a problem using tis control (which by the way is one of the best i have seen and i give my thanks for it to the author), i had some problems integrating it to my site so i did some modify , below is the code : i changed :::
Dim baseDate As DateTime
Dim tmpDate As String
Dim tmpspl() As String
tmpDate = Trim(Left(NodeText(xmlDoc, “//weather/dayf/lsup”), 8))
tmpspl = Split(tmpDate, “/”)
‘baseDate = CDate(tmpspl(1) & “/” & tmpspl(0) & “/” & tmpspl(2))
‘baseDate = FormatDateTime(baseDate, DateFormat.ShortDate)
baseDate = FormatDateTime(tmpspl(1) & “/” & tmpspl(0) & “/” & tmpspl(2), DateFormat.ShortDate)
‘ baseDate = CDate(Left(NodeText(xmlDoc, “//weather/dayf/lsup”), Len(NodeText(xmlDoc, “//weather/dayf/lsup”)) – 14))
Dim updDate As DateTime
‘ updDate = CDate(Left(NodeText(xmlDoc, “//weather/cc/lsup”), Len(NodeText(xmlDoc, “//weather/dayf/lsup”)) – 13))
Dim tmpDate1 As String
Dim tmpsp2() As String
tmpDate1 = Trim(Left(NodeText(xmlDoc, “//weather/dayf/lsup”), 8))
tmpsp2 = Split(tmpDate1, “/”)
updDate = FormatDateTime(tmpsp2(1) & “/” & tmpsp2(0) & “/” & tmpsp2(2), DateFormat.ShortDate)
look over this
Ok – All I needed to do was clear all the rows since
the section or displaying the rows are in a seperate table
fCastTbl.Rows.clear() ‘Clear all Rows
Also it you submit an illegal zipcode
test to see if the node text is “N/A”
if NodeText(xmlDoc, “/weather/loc/dnam”) = “N/A” then fCastTbl.Rows.clear()
So now you can change the zipcode and get the weather for that zipcode automatically
I placed a zipcode textbox on form (w…ascx) so that when you re exit the textbox it automatically provide the weather for the new zipcode submitted – but it keep generating two rows in the table rather than 1 row
Enter Zipcode:
public LocationID As String = “20905″
then…
sub changeZipCode(S as object, E as EventArgs)
LocationID = trim(zipCode.text)
bldgWeatherPage
end sub
sub bldgWeatherPage()
‘********* account specific variables *********
….
Initially it shows 1 row
but once you change the zipcode
It shows 2 rows no matter how many times you change the zipcode
so it always keeps the first row and then add a second row
Any suggestions
picksixweb…thank you for the comments. glad i could be of help.
the invalid cast error you are getting is due to the data that is being returned to you in your specific xml feed. in my case, i always get a string that is a date value with an extra 4 text characters appended to the end of the string. so i can remove those four extra characters, then convert that value into a date type and do date manipulations to add and subtract time. i do this in order to display the “date last updated” information in Eastern Standard Time. you can either comment out this code, or do further string manipulations to ultimately get a date…or do a try/catch in case of an error. you’ll have to experiment a little to figure that out.
if you are able to find a universal solution to this problem, i would be very interested in hearing from you and incorporating your code. any other suggestions are greatly appreciated as well.
Leon,
Best example (and working) of using the weather channel data feed. Nice job and I greatly appreciate you sharing the code. I’m working on some changes and was wondering if you had words of wisdom working with the weather xml structure to expedite the change. If I get it sorted out, I’ll send the updates to you.
My first need is the parsing of data from foreign codes (example GMXX0272 or ASXX0075). I need to display both domestic and foreign weather. I’m getting an InvalidCastException for the code line baseDate = CDate(Left(NodeText(xmlDoc, “//weather/dayf/lsup”), Len(NodeText(xmlDoc, “//weather/dayf/lsup”)) – 4)).
The second item of change, which I think should be straight forward, is making the weather channel ID code a parameter. That way the ascx control is more dynamic and useful as a generic page control.
ok, I will send you the code when rady, no problem.
but I am having some strange issues with the code though…seems like for example that the wind speed is not always returned as a number. it could be returned as as string like “calm”. so when setting your control to using KPH it tries to convert the windspeed from MPH to KPH and it fails. but it is possible to request the XML data with metric values (use parameter unit=m) and get everything back in KPH and celsius directly without need for conversion between formats
and I must point out that your control does not comply with the weather.com reguirements for using their service.
you must link back to them and use their logo. check the PDF doc in the SDK
when you’re finished with the c# version, please send me the code so I can add that version too (if you don’t mind). also, please send me suggestions on ways to improve this.
as for the icons, i downloaded them from a site that stated they were free for public use. you can also use the ones weather.com provides (free as well).
great!
i just downloaded your control.
but i will rewrite it to C#
are the weather icons free to use?