When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article

ASP ASP.NET ASP FAQs Message Board Feedback
 
Print this Page!
Published: Wednesday, September 16, 2009

Accessing Images On Flickr From An ASP.NET Website Using The Flickr.Net Library

By Scott Mitchell


Introduction


Flickr is a popular photo-sharing website. Like many "Web 2.0" and "social" websites, Flickr includes a programmatic interface through which other programs and websites can view and manage photos, comments, groups, tags, and other Flickr assets. I recently started work on a website that offers its users a customized homepage where they can upload pictures, enter biographical and contact information, and integrate with other social websites, such as Flickr. Specifically, a user can supply their Flickr screen name and have a random collection of their public photos in Flickr appear on their customized homepage.

Flickr's API includes a number of methods, such as flickr.people.findByUsername and flickr.photos.getInfo, which return information about a particular Flickr user and a particular photo, respectively. To call one of these methods you need to send a properly formatted message to the Flickr API URL, which returns the results in a specified format. Flickr's API documentation provides all of the gory details.

If you're more interested in interacting with Flickr from an ASP.NET website and are less interested in the low-level details, you'll be delighted to know that there are mature, open source .NET libraries for accessing the Flickr API. With these libraries you don't need to know the ins and outs of the Flickr API; instead, you just work with the .NET library from your ASP.NET application and let it handle all the low-level formatting and message transport details.

This article explores the open source Flickr API library called Flickr.Net, which was created by Sam Judson and was used in my aforementioned project. Specifically, we'll look at how to create an ASP.NET website that displays a smattering of randomly selected pictures from a particular Flickr user, along with how to show a specific picture's comments (if any exist). And the complete code in both Visual Basic and C# is available for download at the end of this article. Read on to learn more!

- continued -

An Overview of the Flickr API


The Flickr API provides a means for application developers to interface with Flickr assets - photos, users, comments, blogs, groups, and so forth. In order to use the Flickr API you must have an API key, which you can get for free from the Flickr API Keys page at http://www.flickr.com/services/api/keys.

Flickr assets can have different permissions and access levels associated with them. For example, a user who had added pictures to their Flickr album can mark their pictures as being public, private, or only accessible to users who they've classified as friends or family. Similarly, users can set configure their account so that their pictures or account details are not available through a public search. The Flickr API provides access to both public and private assets. To access a user's private assets or to modify his public or private assets you must first authenticate that your application can interact with the user's account. This involves obtaining a token from the user, which indicates that the user has granted your application access to his account. After authenticating your application can upload photos to the user's account, delete photos, add comments on the user's behalf, view private photos, and so on.

This article does not explore authentication, but rather focuses on using the Flickr API in concert with the Flickr.Net library to display public assets.

Getting Started With Flickr.Net


Once you have created a Flickr API key, the next step is to download the Flickr.Net library, which you can do from its CodePlex page: http://flickrnet.codeplex.com. From the project's homepage, go to the Downloads tab and download the Flickr.Net Binaries. The download includes a FlickrNet.dll file; copy this file to the Bin folder in your ASP.NET application.

The primary workhorse in the Flickr.Net library is a class named Flickr. When using this class you need to specify your Flickr API key. This can be done in the Flickr class's constructor like so:

// C#: Create a Flickr object
Flickr flickr = new Flickr("my_Flickr_API_Key");


' VB: Create a Flickr object
Dim flickr As New Flickr("my_Flickr_API_Key")

A better approach is to put the Flickr API key in Web.config. That way you don't have to copy and paste the API key into each page that uses the Flickr.Net library, and you only have one place to modify should you start using a new key. The demo available for download at the end of this article puts the key in Web.config, and the Example Config File demo at the Flickr.Net project page shows exactly what to put in Web.config to achieve this.

Once the Flickr class has been instantiated you can use it to make calls to the Flickr API. For example, the Flickr class's PhotosGetInfo(photo_id) method returns information about a particular photo. (To determine the photo_id of a picture you are viewing at Flickr, just look at the URL, which has the format: http://www.flickr.com/photos/your_nickname/photo_id/.) So to get information about a picture you could use code like the following:

// C#: Create a Flickr object
Flickr flickr = new Flickr();

// Get information about photo 936265426
PhotoInfo photoInfo = flickr.PhotosGetInfo("936265426");

// Display the title
lblPhotoTitle.Text = photoInfo.Title;


' VB: Create a Flickr object
Dim flickr As New Flickr()

' Get information about photo 936265426
Dim photoInfo As PhotoInfo = flickr.PhotosGetInfo("936265426")

' Display the title
lblPhotoTitle.Text = PhotoInfo.Title

Note: in the above code we do not need to explicitly specify a Flickr API key in the Flickr constructor because it is already specified in Web.config. The constructor is able to get the API key value out of Web.config implicitly.

The PhotosGetInfo(photo_id) method returns a PhotoInfo object, which has properties that provide information like DateUploaded, Title, Description, and ViewCount, along with properties that return the URL to the actual image sitting Flickr's servers, including: ThumbnailUrl, SmallUrl, MediumUrl, LargeUrl, and OriginalUrl. These URLs are to an actual JPG image that you can display in your website through an Image Web control. A full listing of these properties, as well as the other objects and methods in the Flickr.Net library, are available in the documentation, which is available from the Flickr.Net library project's Downloads tab.

What's important to note is how the Flickr.Net library makes it possible to interact with the Flickr API without having to know a whit about the low-level details. We don't have to worry about how data is transferred between our application and Flickr's servers. We just create the Flickr object, call a method, and get back an object (or an array of objects) that models the results from Flickr.

Searching For Photos


The Flickr object's PhotoSearch method searches public photos on Flickr, returning a "page" of results. You can specify various search options, such as how many pictures to return per page, what page of data to retrieve, whether to filter by user or tags, and so on. The following code snippet returns the 100 most recently uploaded public images to Flickr that contain the tag "Hawaii".

// C#: Create a Flickr object
Flickr flickr = new Flickr();

// Get 100 most recent pictures with the tag "Hawaii"
PhotoSearchOptions options = new PhotoSearchOptions();
options.PerPage = 100;
options.Tags = "Hawaii";

Photos searchResults = flickr.PhotosSearch(options);



' VB: Create a Flickr object
Dim flickr As New Flickr()

' Get 100 most recent pictures with the tag "Hawaii"
Dim options As New PhotoSearchOptions()
options.PerPage = 100
options.Tags = "Hawaii"

Dim searchResults As Photos = flickr.PhotosSearch(options)

To limit our search to 100 photos per page (the default) and those pictures with the tag "Hawaii", we use create a PhotoSearchOptions object and set the relevant properties. Next, the Flickr class's PhotoSearch method is called and passed the PhotoSearchOptions object. The PhotoSearch method returns a Photos object, which contains a PhotoCollection property, which is a collection that includes details about each of the 100 matching pictures (their titles, URLs, descriptions, and so forth).

Users' Screen Names and User IDs


Flickr uniquely identifies each user via a User ID which has the a format like 74068408@N00. Users may also create a screen name, which is a more readable name and is used to identify the person when they make comments. This screen name is not necessarily the same name that appears in the URL to your photostream. A user's photostream is available via a URL like http://www.flickr.com/photos/nickname/. While the nickname and screen name are often one in the same, they need not be. In fact, a user can change her screen name as often as she likes, but her nickname is immutable.

When searching for photos by a particular user you need to search by their User ID. It is possible to get a user's User ID from their screen name using the Flickr class's PeopleFindByUsername(screen_name) method, which returns a FoundUser object. The FoundUser object has UserID and Username properties. One thing to bear in mind is that if the screen name is not found then this method raises a FlickrApiException exception. Moreover, a the PeopleFindByUsername(screen_name) method will only return information about a user if they have not configured their account to hide their details from public searches.

The following code shows how to look up a User ID when all you know is the user's screen name. Superficially, it is looking up the user ID associated with my Flickr screen name, scott_mitchell. The code is in a Try ... Catch block and swallows the FlickrApiException that is raised if the screen name entered is not found or if it is for a user who does not allow their results to be included in public searches. If it wasn't in a Try ... Catch block then an invalid screen name would result in a Yellow Screen of Death.

// C#: Look up the User ID
Flickr flickr = new Flickr();

string flickrUserId = string.Empty;
try
{
   FoundUser userInfo = flickr.PeopleFindByUsername("scott_mitchell");
   flickrUserId = userInfo.UserId;
}
catch (FlickrApiException)
{
   // Screen name not found...
   ...
}


' VB: Look up the User ID
Dim flickr As New Flickr()

Dim flickrUserId As String = String.Empty
Try
   Dim userInfo As FoundUser = flickr.PeopleFindByUsername("scott_mitchell")
   flickrUserId = userInfo.UserId
Catch ex As FlickrApiException
   ' Screen name not found...
   ...
End Try

Putting It All Together


The demo available for download at the end of this article puts the above concepts together using two ASP.NET pages:
  • RandomPicturesByScreenName.aspx - allows the user to enter a screen name into a TextBox control and then displays nine randomly selected pictures from that user's photostream.
  • ViewDetails.aspx - clicking on one of the photos in RandomPicturesByScreenName.aspx takes the user to this page, passing along the Photo ID through the querystring. ViewDetails.aspx displays a larger version of the picture, its title, description, and any comments.
The RandomPicturesByScreenName.aspx page displays the nine randomly selected images in an HTML <table> using the ListView control. Each image is displayed using a HyperLink control, as the following declarative markup illustrates:

<asp:HyperLink runat="server" ID="lnkImage"
          NavigateUrl='<%# Eval("PhotoId", "ViewDetailsCS.aspx?PhotoID={0}") %>'
          ImageUrl='<%# Eval("SmallUrl") %>'
          ToolTip='<%# Eval("Title") %>' />

When the user enters a screen name and clicks a Button, the code retrieves the 200 most recent photos from the specified user using the PhotosSearch method we discussed earlier. This method returns a Photos object whose PhotoCollection property is a collection of Photo objects. The properties that appear in the ListView's databinding syntax in the HyperLink markup above - PhotoId, SmallUrl, and Title - are all properties of the Photo object.

I use some of LINQ's extension methods to randomly order the 200 photos returned by the Flickr API and to get the first nine photos before binding that subset to the ListView. The pertinent code follows:

// C#: Get the 200 most recent public photos from the specified user
Photos searchResults = flickr.PhotosSearch(options);

// Rnadomize the searchResults.PhotoCollection array, take the first 9, and bind it to lvFlickrPictures
lvFlickrPictures.DataSource = searchResults.PhotoCollection
                               .OrderBy(p => Guid.NewGuid())
                               .Take(9)
;
lvFlickrPictures.DataBind();


' VB: Get the 200 most recent public photos from the specified user
Dim searchResults As Photos = flickr.PhotosSearch(options)

' Rnadomize the searchResults.PhotoCollection array, take the first 9, and bind it to lvFlickrPictures
lvFlickrPictures.DataSource = searchResults.PhotoCollection.OrderBy(Function(p) Guid.NewGuid()).Take(9)
lvFlickrPictures.DataBind()

Randomly ordering the arrays is done by ordering the results based on new globally-unique identifiers, and is discussed in more length in Techniques for Randomly Reordering an Array. For more information on using LINQ's extension methods, like OrderBy and Take, refer to my An Extensive Examination of LINQ article series.

The following screen shot shows the RandomPicturesByScreenName.aspx page in action.

The RandomPicturesByScreenName.aspx page shows nine random pictures from the specified user's Flickr photostream.

Clicking on one of these images takes the user to ViewDetails.aspx, where they can view a larger version of the picture along with the title, description, and comments (if any).

The ViewDetails.aspx page shows a larger version of the photo along with its title, description, and comments (if any).

Conclusion


Like many social websites, Flickr provides an API that enables developers to integrate Flickr assets into their applications. Working with the Flickr API in an ASP.NET application is made infinitely easier using a library like Flickr.Net, which handles all of the low-level communication details and provides a nice object model to work from. This article showed how to use Flickr.Net to display photos, titles, descriptions, and comments from a user's Flickr photostream within your own ASP.NET application. Be sure to download the demo and give the code a whirl.

Happy Programming!

  • By Scott Mitchell


    Attachments:


  • Download the complete code / demo
  • Further Reading


  • The Flickr API Documentation
  • The Flickr.Net Library


  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article