Tuesday, 23 April 2013

Display Photos in ASP.NET using Flickr.NET API


Display Photos in ASP.NET using Flickr.NET API




One of the most common ingredients of any successful website is to display photos to the site visitors along with photos and their metadata search facility. There are number of photo sharing web sites and services providing the large number of photos for websites and blogs. The most popular and commonly used site is Flickr.com, which provides very flexible and powerful API to web developers and exposes almost all the data stored on the site to offer web developers limitless possibilities for creating mashups, widgets, etc. Due to the popularity of Flickr API, many client libraries are available for almost all programming languages such as .NET, Java or PHP. These libraries make development with Flickr API even easier by hiding lower level API details and also allows you to work with your favorite programming language and environment. In this tutorial, I will show you how you can use one such library Flickr.NET to search and display photos using C# and ASP.NET.
Using Flickr.NET API in ASP.NET
Before I start this tutorial, please keep in mind that the developer key and shared secret is required to make requests to the Flickr API so make sure you have got your developer key and shared secret from the Flckr website at the following URL.

http://www.flickr.com/services/api

You also make sure that you have downloaded the latest version of Flickr.NET API from codeplex website.

http://flickrnet.codeplex.com

To get started, create a new ASP.NET website in Visual Studio and add the reference of FlickrNet.dll you just downloaded from codeplex. To create an interface shown in the above figure, you need to add a table with three rows and two columns. Inside that table, you need to add search textbox, go button, some labels and a DataList control to show thumbnails. Following is the complete markup of the page used in this tutorial. 
<div style="text-align: center">
   <center>
      <table cellpadding="5" cellspacing="0" style="border: 2px solid #0066CC; width: 60%;">
         <tr>
            <td style="width: 40%;">
               Search:
               <asp:TextBox ID="SearchTextBox" runat="server"></asp:TextBox>
               <asp:Button ID="GoButton" runat="server" Text="GO"
                  OnClick="GoButton_Click" />
            </td>
            <td style="vertical-align: top">
               <asp:Label ID="PhotoDateTaken" runat="server"></asp:Label>
            </td>
         </tr>
         <tr>
            <td style="vertical-align: top">
               <asp:DataList ID="ThumbnailsList" runat="server" HorizontalAlign="Center"
                  RepeatColumns="3" Width="100%"
                 OnSelectedIndexChanged="ThumbnailsList_SelectedIndexChanged">
                 
                  <ItemStyle HorizontalAlign="Center" />
                  <ItemTemplate>

                     <asp:ImageButton ID="ThumbnailImage" runat="server"
                        ImageUrl='<%# Eval("SquareThumbnailUrl") %>'
                        AlternateText='<%# Eval("Title") %>'
                        ToolTip='<%# Eval("Title") %>
'
                        CommandName="Select">
                     </asp:ImageButton>

                     <asp:Literal ID="HiddenPhotoId" runat="server"
                        Text='<%# Eval("PhotoId") %>' Visible="false" />
                     <asp:Literal ID="HiddenPhotoUrl" runat="server"
                        Text='<%# Eval("MediumUrl") %>' Visible="false" />

                  </ItemTemplate>
               </asp:DataList>
            </td>
            <td style="vertical-align: top">
               <asp:Image ID="PreviewImage" runat="server" />
            </td>
         </tr>
         <tr>
            <td style="vertical-align: top">&nbsp;</td>
            <td style="vertical-align: top">
               <asp:Label ID="PhotoDescription" runat="server"></asp:Label>
            </td>
         </tr>
      </table>
   </center>
</div>

The DataList control used in the above markup is using an ImageButton control to display image thumbnails inside theItemTemplate. Notice how the ImageUrl property of the ImageButton is bound with SquareThumbnailUrl property of the Flickr.NET API Photo class. Furthermore, notice the AlternateText and ToolTip properties are bound with Titleproperty. I also used two hidden literal controls to store PhotoId and its MediumUrl properties, which will be used to display photo preview and to get more details like its description or date the photo is taken from Flickr website.

It is now time to show you the Flickr.NET API in action by moving to the page code behind file. Declare the following two variables on top of the class and store your developer key and shared secret in them.

string flickrKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string sharedSecret = "xxxxxxxxxxxxxxx";

Define the following GetPhotos method to search photos from Flickr website using Flickr.NET API and to bind the DataList with the photos returned from Flickr. This method will be called in Page Load event with default keyword and then from Go button click with the keyword user will specify in the search textbox.
private void GetPhotos(string tag)
{
   PhotoSearchOptions options = new PhotoSearchOptions();
   options.PerPage = 12;
   options.Page = 1;
   options.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
   options.MediaType = MediaType.Photos;
   options.Extras = PhotoSearchExtras.All;
   options.Tags = tag;

   Flickr flickr = new Flickr(flickrKey, sharedSecret);
   PhotoCollection photos = flickr.PhotosSearch(options);


   ThumbnailsList.DataSource = photos;
   ThumbnailsList.DataBind();
}

The method GetPhotos first declares an object of PhotoSearchOptions class that allows us to set all the search related parameters in a single place. You can set how many photos you want to retrieve per page along with the current page index. You can set the sort order, media type (photos, videos etc.) to fetch from Flickr website. You need to set theTags property with any string value you want to search. Flickr.NET API also exposes Flickr class that havePhotoSearch method to actually search photos from Flickr. It takes PhotoSearchOptions object as parameter and returns PhotoCollection returned by using the search options specified. Finally, I bind the photos collection with the DataList control on the page. Similar to the above method is the GetDescription method which takes photoId as parameter and returns Photo description and other useful information from Flickr website.
private void GetDescription(string photoId)
{
   Flickr flickr = new Flickr(flickrKey, sharedSecret);
   PhotoInfo info = flickr.PhotosGetInfo(photoId);


   PhotoDescription.Text = info.Description;
   PhotoDateTaken.Text = info.DateTaken.ToString("MMMM dd,  yyyy");
}

Call the above methods in the Page Load event as shown in the code below. Notice how I am getting hidden photoId and photoUrl from the first Item shown in the DataList to make sure user see the first image preview and its description when the page loads first time.
protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      string defaultKeyword = "nature";
      SearchTextBox.Text = defaultKeyword;
      GetPhotos(defaultKeyword);

      Literal HiddenPhotoId =
         ThumbnailsList.Items[0].FindControl("HiddenPhotoId") as Literal;
      Literal HiddenPhotoUrl =
         ThumbnailsList.Items[0].FindControl("HiddenPhotoUrl") as Literal;

      string photoId = HiddenPhotoId.Text;
      string photoUrl = HiddenPhotoUrl.Text;

      PreviewImage.ImageUrl = photoUrl;
      GetDescription(photoId);  
   }
}

The same GetPhotos method will be called from the Go button click event to search photos with the user given keyword.
protected void GoButton_Click(object sender, EventArgs e)
{
   string keyword = SearchTextBox.Text.Trim();
   GetPhotos(keyword);
}

Finally, I am using SelectedIndexChange event of the DataList control to allow user to select any photo by clicking the thumbnail and showing the user selected photo preview and description on the right hand side of the thumbnails. 
protected void ThumbnailsList_SelectedIndexChanged(object sender, EventArgs e)
{
   Literal HiddenPhotoId =
      ThumbnailsList.SelectedItem.FindControl("HiddenPhotoId") as Literal;
   Literal HiddenPhotoUrl =
      ThumbnailsList.SelectedItem.FindControl("HiddenPhotoUrl") as Literal;

   string photoId = HiddenPhotoId.Text;
   string photoUrl = HiddenPhotoUrl.Text;

   PreviewImage.ImageUrl = photoUrl;
   GetDescription(photoId);        
}

I hope I gave you a basic introduction of using Flickr.NET API in this tutorial. Flickr.NET API is huge and there are many ways you can use it to implement anything you want. Flickr.NET API has many more classes and features that I haven’t explored in this tutorial. I hope you will dig deep into the API and will start using this API in your ASP.NET websites and blogs. 

No comments:

Post a Comment