For some reason you’ve decided to show user some photos from Flickr. You can navigate him to the other page or the Flickr main site, but that not the way it goes in Silverlight world…
Flickr is an image-sharing website that provides REST-like services. You supply your parameters by tacking query string onto the end of the URL. The web service will return a response in XML format.
Example of response:
<?xml version="1.0" encoding="utf-8" ?> <rsp stat="ok"> <photos page="1" pages="985" perpage="10" total=987566> <photo id="63565636" owner="5844563DS" secret="22154136547df" server="4153" farm="2" title="Tiger ready to jump..." ispublic="1" isfriends="0" isfamily="0"/> .... </photos> </rsp>
First of all, you must have free API key. It’s unique and allows to get access to Flickr’s services. Visit www.flickr.com/services/api to obtain one. Secondly, we must perform a correct query:
//We will use WebClient with Async string loading to get the data WebClient client = new WebClient(); //This is our url with parameters for the service Uri addr = new Uri("http://api.flickr.com/services/rest/?method=flickr.photos.search&tags=Tiger&api_key=your_api_key"); //As you can see we are looking for Tigers. For more info about parameters - visit the API site. //Now we are adding handler for completion client.DownloadStringCompleted += client_DownloadStringCompleted; //And sending the request client.DownloadStringAsync(addr);
Inside the Completed Handler we have:
private void client_DownloadingStringCompleted(object sender, DownloadStringComppletedEventArgs e) { //Xdocument holds a collection of XNode objects (abstract class). More info you can get in XPath page of MSDN. XDocument document =XDocument.Parse(e.Result); //Now we need to get all photo elements with attribute data var fetched_photos = from found in document.Descendants("photo") select new { Id= (string)found.Attribute("id"), Farm= (string)found.Attribute("farm"), Server= (string)found.Attribute("server"), Secret= (string)found.Attribute("secret"), } }
Let’s take a closer look on the fetched_photos variable. LINQ defines a set of method names (called standard query operators, or standard sequence operators), along with translation rules from so-called query expressions to expressions using these method names, lambda expressions and anonymous types. In or case we have anonymous type generation. We are creating a collection of dynamically defined type that includes 4 properties (Id,Farm,Server,Secret). To learn more – check the MSDN.
There is one thing left. How we are going to get dynamic type from the collection?
foreach(var photo from fetched_photos) { string ImageUrl = string.Format("http://farm{0}.static.flickr.com./{1}/{2}_{3}_m.jpg", photo.Farm, photo.Server, Photo.Id, photo.Secret); }
This will define the urls of the image. You can now bind one of them to UI element:
Image im = new Image(); im.Source=ImageUrl;