In this post we will create application shown in below video. Essentially we will see how we can work with

  • GridView and ListView in Windows 8 Application
  • Consuming REST Service in Windows 8 Application
  • Share Contract in Windows 8 Application

To create on Flickr based application you need API Key from Flickr. You can apply for API key here . You need to fill the required information and click on Submit button to create API key. We need this API key in application. You need to submit App information in order to generate key. After submitting app information you will be navigated to App Garden and there you will find APP key and secret key as given in below image.

image

Very first create a Windows Store Application by choosing blank App template. Let us start with initializing variable. To search photos Flickr provides us REST end point. Globally we are initializing Flickr app key we created in previous step and constructing an URL to search on Flickr with search parameter. We are appending app key and search text in URL.


private HttpClient httpClient;
 private string key = "51fc5b3802c6ed36924ed3d6a8cc085a";
 private string flickrSearchUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&text={1}";

Now switch to MainPage.xaml to design application. Very first let us divide content Grid in three rows. In second row we will put text box and button to search Flickr and in third row images returned will be displayed. First row contains header message of application.

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

<Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 <RowDefinition Height="700" />
 </Grid.RowDefinitions>

 </Grid>

Next let us put header message and controls. In below XAML we are creating following controls

  • Creating TextBlock in first to display application header message.
  • Creating StackPanel in second row with orientation horizontal.
  • In StackPanel creating TextBlock to get user input to search Flickr.
  • Creating a Button in StackPanel to get user input to search on Flickr.
<TextBlock Text="Flickr Search Application"
 Margin="30"
 FontSize="36" />
 <StackPanel Grid.Row="1" Orientation="Horizontal">
 <TextBox x:Name="txtSearch" Width="200"
 VerticalAlignment="Center"
 HorizontalAlignment="Center"
 Margin="30"/>
 <Button x:Name="btnSearch"
 Content="Search on Flickr"
 Height="40" />
 </StackPanel>

Now let us create output GridView in third row. In this GridView we will display returned images from Flickr. In GridView we are creating ItemTamplate and putting an Image control in that. Image control is been bind to ImageUrl property. We will create class containing this property in later steps.

 <GridView x:Name="grdFlickrImageOutput" Grid.Row="2" Margin="30,0,0,0" >
 <GridView.ItemTemplate>
 <DataTemplate>
 <Image Width="300" Height="300" Source="{Binding ImageUrl}"></Image>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>

We have created design for the application. Now let us go ahead and create a class representing Flickr photo. This class will contain all the properties required to fetch an image from Flickr. Last property ImageUrl is of type URI and we are constructing it using other properties of Flickr Image


using System;

namespace debugmodeflickrsearch
{
 public class FlickrPhoto
 {
 public string ImageId { get; set; }
 public string FarmId { get; set; }
 public string ServerId { get; set; }
 public string Secret { get; set; }
 public string Title { get; set; }

public Uri ImageUrl
 {
 get
 {
 return new Uri(string.Format("http://farm{0}.static.flickr.com/{1}/{2}_{3}.jpg", FarmId, ServerId, ImageId, Secret));
 }
 }
 }
}

On click event of button we need to make a call to Flickr and get the response. To call Flickr REST API we are using HttpClient. We are making async call to get the response from Flickr. After getting reponse ParseIamges function is called to parse the response.


async void btnSearch_Click(object sender, RoutedEventArgs e)
 {
 httpClient = new HttpClient();
 HttpResponseMessage response = await httpClient.GetAsync(String.Format(flickrSearchUrl, key,txtSearch.Text));
 ParseImages(response);
 }

We will parse response using LINQ to XML. After parsing response is set as ItemSource of output GridView.


private async void ParseImages(HttpResponseMessage response)
 {
 XDocument xml = XDocument.Parse(await response.Content.ReadAsStringAsync());
 var returnedphotos = from results in xml.Descendants("photo")
 select new FlickrPhoto
 {
 ImageId = results.Attribute("id").Value.ToString(),
 FarmId = results.Attribute("farm").Value.ToString(),
 ServerId = results.Attribute("server").Value.ToString(),
 Secret = results.Attribute("secret").Value.ToString(),
 Title = results.Attribute("title").Value.ToString()
 };

grdFlickrImageOutput.ItemsSource = returnedphotos;
 }

Now let us go ahead and run application. We should able to search Flickr for images.

clip_image002

Now we want to share photo we like on social media or in a mail. We can achieve that using Windows 8 Share Contract. Very first let us go ahead and add itemclick event to output GridView. After adding event output GridView will get modified as following


<GridView x:Name="grdFlickrImageOutput" Grid.Row="2" Margin="30,0,0,0"
 IsItemClickEnabled="True" ItemClick="grdFlickrImageOutput_ItemClick_1"
 >
 <GridView.ItemTemplate>
 <DataTemplate>
 <Image Width="300" Height="300" Source="{Binding ImageUrl}"></Image>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>

&nbsp;

Next go ahead and define following variable globally,

 private string strTitleToShare = "Debugmode Flickr Photo Search App";
 private string strDescriptionToShare = "Sharing from Debugmode Flickr Photo Search App";
 private string strsharedText = string.Empty;

In constructor of the page create instance of DataTransferManager and add event for DataRequested.


DataTransferManager manager = DataTransferManager.GetForCurrentView();
 manager.DataRequested += manager_DataRequested;

Now we need to write code in DataRequested event to share text from application. In below code we are creating instance of DataRequest and setting Title , Description and Data to share.

void manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
 {
 DataRequest request = args.Request;
 request.Data.Properties.Title = strTitleToShare;
 request.Data.Properties.Description = strDescriptionToShare;
 request.Data.SetText(strsharedText);
 }

Now we need to handle item selection in GridView. When user will select a particular photo we will construct text to be shared with URL of photo. We can do this as following,


private void grdFlickrImageOutput_ItemClick_1(object sender, ItemClickEventArgs e)
 {
 FlickrPhoto selectedPhoto = e.ClickedItem as FlickrPhoto;
 var urt = selectedPhoto.ImageUrl;
 strsharedText= "Hey look at this photo "+urt+" I loved it #CSharpCornerMvpSummit #Demo" ;
 DataTransferManager.ShowShareUI();
 }

Now go ahead and run the application. You should able to search photo from Flickr and share them using the apps.

image

Below find full source code of above discussion.

Mainpage.xaml


<Page
 x:Class="debugmodeflickrsearch.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="using:debugmodeflickrsearch"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

<Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 <RowDefinition Height="700" />
 </Grid.RowDefinitions>
 <TextBlock Text="Flickr Search Application"
 Margin="30"
 FontSize="36" />
 <StackPanel Grid.Row="1" Orientation="Horizontal">
 <TextBox x:Name="txtSearch" Width="200"
 VerticalAlignment="Center"
 HorizontalAlignment="Center"
 Margin="30"/>
 <Button x:Name="btnSearch"
 Content="Search on Flickr"
 Height="40" />
 </StackPanel>
 <GridView x:Name="grdFlickrImageOutput" Grid.Row="2" Margin="30,0,0,0"
 IsItemClickEnabled="True" ItemClick="grdFlickrImageOutput_ItemClick_1"
 >
 <GridView.ItemTemplate>
 <DataTemplate>
 <Image Width="300" Height="300" Source="{Binding ImageUrl}"></Image>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>

 </Grid>
</Page>

Mainpage.xaml.cs


using System;
using System.Linq;
using System.Net.Http;
using System.Xml.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel.DataTransfer;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace debugmodeflickrsearch
{
 /// <summary>
 /// An empty page that can be used on its own or navigated to within a Frame.
 /// </summary>
 public sealed partial class MainPage : Page
 {
 private string strTitleToShare = "Debugmode Flickr Photo Search App";
 private string strDescriptionToShare = "Sharing from Debugmode Flickr Photo Search App";
 private string strsharedText = string.Empty;
 private HttpClient httpClient;
 private string key = "51fc5b3802c6ed36924ed3d6a8cc085a";
 private string flickrSearchUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&text={1}";

public MainPage()
 {
 this.InitializeComponent();
 DataTransferManager manager = DataTransferManager.GetForCurrentView();
 manager.DataRequested += manager_DataRequested;
 btnSearch.Click += btnSearch_Click;
 }

void manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
 {
 DataRequest request = args.Request;
 request.Data.Properties.Title = strTitleToShare;
 request.Data.Properties.Description = strDescriptionToShare;
 request.Data.SetText(strsharedText);
 }

&nbsp;

async void btnSearch_Click(object sender, RoutedEventArgs e)
 {
 httpClient = new HttpClient();
 HttpResponseMessage response = await httpClient.GetAsync(String.Format(flickrSearchUrl, key,txtSearch.Text));
 ParseImages(response);
 }

private async void ParseImages(HttpResponseMessage response)
 {
 XDocument xml = XDocument.Parse(await response.Content.ReadAsStringAsync());
 var returnedphotos = from results in xml.Descendants("photo")
 select new FlickrPhoto
 {
 ImageId = results.Attribute("id").Value.ToString(),
 FarmId = results.Attribute("farm").Value.ToString(),
 ServerId = results.Attribute("server").Value.ToString(),
 Secret = results.Attribute("secret").Value.ToString(),
 Title = results.Attribute("title").Value.ToString()
 };

grdFlickrImageOutput.ItemsSource = returnedphotos;
 }

/// <summary>
 /// Invoked when this page is about to be displayed in a Frame.
 /// </summary>
 /// <param name="e">Event data that describes how this page was reached. The Parameter
 /// property is typically used to configure the page.</param>
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
 }

private void grdFlickrImageOutput_ItemClick_1(object sender, ItemClickEventArgs e)
 {
 FlickrPhoto selectedPhoto = e.ClickedItem as FlickrPhoto;
 var urt = selectedPhoto.ImageUrl;
 strsharedText= "Hey look at this photo "+urt+" I loved it #CSharpCornerMvpSummit #Demo" ;
 DataTransferManager.ShowShareUI();
 }
 }
}

In this way we can create a Flickr Photo Search App for Windows Store. I hope you find this post useful. Thanks for reading.

Advertisements

4 thoughts on “Create Flickr Photo Search Windows Store App in XAML

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s