Friday, March 7, 2008

Linq and untyped DataSets

As a small update to the previous post - if you don't fancy looking through each table in an untyped dataset then linq is your friend. For instance to join information from two of the yr.no-service tables you can do this:

// Join "time" and "temperature"-tables,
// Get id, temperature, from time and to time
var query =
from time in ds.Tables["time"].AsEnumerable()
join temp in ds.Tables["temperature"].AsEnumerable()
on time.Field<int>("time_id") equals
temp.Field<int>("time_id")
select new
{
TemperatureId = time.Field<int>("time_id"),
Tempearature = temp.Field<string>("value"),
FromTime = time.Field<string>("from"),
ToTime = time.Field<string>("to"),
};


// Simple output
foreach (var tempInfo in query)
{
Console.WriteLine("{0} - {1}:\t{2}",
tempInfo.FromTime,
tempInfo.ToTime,
tempInfo.Tempearature);
}

For more information check this link on MSDN.

Thursday, March 6, 2008

Reading weather data from www.yr.no

Thanks to Sjur for the tip about the weather service at www.yr.no, which actually has a web service publishing pure xml data.

To access a weather service for your favourite location, look it up through the yr.no search and add "Varsel.xml" to the URL.

Access from C# / .Net:

// Load xml from URL
string feedURL = @"http://www.yr.no/sted/Norge/Oslo/Oslo/Oslo/Varsel.xml";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(feedURL);

// Get forecast information
XmlNodeList forecast = xDoc.GetElementsByTagName("forecast");


// Read into dataset
DataSet ds = new DataSet();
StringReader readerStream = new StringReader(forecast[0].OuterXml);
ds.ReadXml(readerStream);

And you have an untyped dataset full of weather information.

Thank you yr.no.

(check the next post for how to read the data with Linq)