Viewing Flickr Images on Windows 7.1 Phone or Mango Phone

In this post I will show you how you can create a Photo Viewer from images of the Flickr Service.

Flickr Service

Flickr expose a REST based feed to access images. You can find information about Flickr public feed at below link.

http://www.flickr.com/services/feeds/docs/photos_public/

Public images feed can be find at

http://api.flickr.com/services/feeds/photos_public.gne

Expected Output

imageimage

Approach

  1. Call Flickr Service
  2. Parse XML feed
  3. Bind it to List Box.

Create Windows Phone 7.1 Application

Create Windows 7 Phone Application and select Windows Phone 7.1 as target Windows Phone version.

clip_image002

clip_image003

Create Photo class

To bind images to the ListBox, let us create Photo class. Right click and add a class called Photo in the project. When we parse Flickr Image feeds, we will bind public Image URL here

Photo.cs

clip_image005

Parsing Image Feed of Flickr Service

When you open public feed URL of Flicker in browser; you can view the feeds in browser itself.

clip_image007

We are going to give value of link element from the feed in Image as source value.

We will have to make asynchronous calls as below,

image

Then in DonwnloadStringCompleted event, we will have to perform below tasks,

  1. Create a Observable collection of Photos
  2. Parse the Feed
  3. Iterate through all the public image url in feed and add to collection.

image

Parsing of feeds can be done as below,

  1. We are parsing Link URL.
  2. Fetching the value of href attribute in Link URL.
  3. There are two link elements and we are fetching value of link element having rel attribute value as enclosure

image

Design the Page

We are going to put a ListBox in content grid and inside ItemTemplate of ListBox , we will put Image control.

clip_image001

As source of the Image you need to bind PhotoSource property of Photo class.

For Reference full source codes are given below. Feel free to use for your purpose  Smile

MainPage.xaml


<phone:PhoneApplicationPage
    x:Class="FlickerImageFeed.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Mango Phone" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Flicker Images" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox x:Name="lstImage" Width="450" Margin="3,6">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding PhotoSource}"
                                   Width="425"
                                   Height="auto"
                                   Stretch="Uniform"
                                   HorizontalAlignment="Center" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Xml.Linq;

namespace FlickerImageFeed
{
    public partial class MainPage : PhoneApplicationPage
    {

        IEnumerable<List<string>> imageURL;
        List<string> lstImageURl;
        Photo P;
        ObservableCollection<Photo> photos;
        public MainPage()
        {
            InitializeComponent();
            GetAllPhotos();
        }

        private ImageSource GetImageSource(string fileName)
        {
            return new BitmapImage(new Uri(fileName, UriKind.Absolute));
        }
        private void  GetAllPhotos()
        {

            WebClient proxy = new WebClient();
            proxy.DownloadStringAsync(new Uri("http://api.flickr.com/services/feeds/photos_public.gne"));
            proxy.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);

        }

        void proxy_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            photos = new ObservableCollection<Photo>();
            lstImageURl = new List<string>();
            imageURL = ParseXML(e.Result);
            foreach (var r in imageURL)
            {
                foreach (var a in r)
                {
                    P = new Photo { PhotoSource = GetImageSource(a.ToString()) };
                    photos.Add(P);
                }
            }

            lstImage.ItemsSource = photos;

        }
        private IEnumerable<List<string>> ParseXML(string xmlData)
        {
            XNamespace ns = "http://www.w3.org/2005/Atom";
            XDocument doc = XDocument.Parse(xmlData);
            var photo = from r in doc.Descendants(ns + "entry")
                        select r.Elements(ns + "link")
                        .Where(f => (string)f.Attribute("rel") == "enclosure")
                        .Select(f => f.Attribute("href").Value).ToList();
            return photo;
        }
    }
}

Run the Application

Press F5 to run Photo viewer from images of Flicker service Smile

imageimage

I hope this post was useful. Thanks for reading  Smile

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Photo Viewer in Windows Phone 7.1 or Mango Phone

In this post I will show you how to create a simple Photo Viewer? Before I start, I would like to inform you about a gray part of this post that all the Images are attached as a resource in the phone application and this is not recommended. We should have either image in Isolated Storage or should be downloading from remote Server.

Expected Output

imageimage

Idea here is very simple,

  1. Create Observable collection of Images
  2. Bind it to List Box.

Create Windows Phone 7.1 Application

Create Windows 7 Phone Application  and select platform as Windows Phone 7.1

imageimage

Right click and add a folder called Images. We are going to upload all the images in this folder. So after uploading all the existing images solution explorer would look like below,

image

I know sometime these screen shorts may be annoying but I do it purposefully  for the beginners Smile

 

Create Photo class

To bind images to the ListBox , let us create Photo class. Right click and add a class called Photo in the project.

Photo.cs

clip_image002

 

We have added the photos and created a Photo class to represent the Photos.

Now add below namespaces on MainPage.Xaml.cs

 

clip_image001

 

To bind a photo (image) to Image control, we need to provide ImageSource. So let us write a function taking as input parameter filename and retuning BitmapImage of that file name. Here we will pass filename of images we uploaded in Images folder.

 

clip_image003

Next we need to create collection of Images. I am creating observable collection.

 

image

 

You need to set ItemSource of ListBOX as output of above function.

 

clip_image001[5]

Here lstImage is name of the ListBox.

Design the Page

We are going to put a ListBox in content grid and inside ItemTemplate of ListBox , we will put Image control.

 

clip_image001[7]

As source of the Image you need to bind PhotoSource property of Photo class.

For Reference full source codes are given below. Feel free to use for your purpose  Smile

 

MainPage.xaml

 


<phone:PhoneApplicationPage
    x:Class="ImageinMango.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text=" IClicked MVP OpenDays Photo on Mango" Style="{StaticResource PhoneTextNormalStyle}"/>
          </StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox x:Name="lstImage" Width="450" Margin="3,6">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding PhotoSource}"
                                   Width="425"
                                   Height="auto"
                                   Stretch="Uniform"
                                   HorizontalAlignment="Center" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>


 

MainPage.xaml.cs


using System;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel ;
using System.Windows.Media.Imaging ;

namespace ImageinMango
{
    public partial class MainPage : PhoneApplicationPage
    {

        public MainPage()
        {
            InitializeComponent();
            lstImage.ItemsSource = GetAllPhotos();
        }


        private ImageSource GetImageSource(string fileName)
        {
            return new BitmapImage(new Uri(fileName, UriKind.Relative));
        }

        private ObservableCollection<Photo> GetAllPhotos()
        {
            ObservableCollection<Photo> photos = new ObservableCollection<Photo>
                                                   {

                                                       new Photo{PhotoSource = GetImageSource("Images/AbhiM.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/AnandKH.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Harish.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/HarishV.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Abhi.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Suprotim.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/HarishVAlone.png")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Pinal.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Shaivi.jpg")},                                                       new Photo{PhotoSource = GetImageSource("Images/Shobhan.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Vikram.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Host.jpg")}




                                                   };
            return photos;
        }
    }

}

 

Run the Application

Press F5 to run Photo viewer.  Smile

imageimg1

 

I hope this post was useful. Thanks for reading  Smile In further post , I will show you how to fetch Images from server instead of attaching them as resource.

Picture Gallery in ASP.Net MVC Application

 Objective
Objective of this aricle is to show, how to work with Images in ASP.Net MVC application. This article will explain, how to display images from Xml file and how to add images in Xml resourece.

The Final Output would be something like below.

Creating the Resource folder for Image

  1. Create an ASP.Net MVC application, by New->Project->Web->ASP.Net MVC Application.
  2. Now add a folder in application and give it name as Images.


  1. Add few images in Images folder. For that right click on Image folder and add existing items.



  1. After adding Images in Images folder. Folder will look like below.

  1. Add an XML file in Image directory as source of the images. Give any name, here name is ImageMetaData.xml. To add XML file in Images directory, right click on directory and add XML File as shown below.


  1. Create XML elements for images. Here filename and description are xml elements. Give value according to name of your added images. For my Images the xml file is as below.

<?xmlversion=1.0encoding=utf-8 ?><images><image>

<filename>anthonyrobins.jpg</filename>

<description>Anthony Robbins</description></image>

<image>

<filename>chetanbhagat.jpg</filename>

<description>Chetan Bhagat</description>

</image>

<image>

<filename>deepak.jpg</filename>

<description>Deepak Chopra</description>

</image>

<image>

<filename>robinsharma.jpg</filename>

<description>Robin Sharama</description>

</image>

<image>

<filename>stevenkovey.jpg</filename>

<description>Steven Covey</description>

</image>

<image>

<filename>taslima.jpg</filename>

<description>Taslima Nasrren</description>

</image>

<image>

<filename>vikarm.jpg</filename>

<description>Vikram Seth</description>

</image>

</images> 

Displaying Images

Creating the Model

Right click on Model folder and add new class. Give name of the class as Image.



 Type the below code inside the Image class. This class is acting as a business class. This class got two properties . One for Path of the image and other for Description of the image.

Image.cs

 using System;

using System.Collections.Generic;
using System.Linq;

using System.Web;

 namespace ImageViewer.Models
{
public class Image
{
public Image(string path, string desc)
{
Path = path;
Description = d}
public string Path { get; set; }
public string Description { get; set;}
}
}
We need to fetch data from the disk. For this, we will add one more model class and in constructor of that class, we will fetch all the images from xml file. So add one class in Model folder as shown in step above. Give name ImageModel.

ImageModel.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Xml.Linq;

namespace ImageViewer.Models

{


public
class
ImageModel:List<Image>

{


public ImageModel()

{


string directoryOfImage = HttpContext.Current.Server.MapPath(“~/Images/”);


XDocument imageData = XDocument.Load(directoryOfImage + @”/ImageMetaData.xml”);


var images = from image in imageData.Descendants(“image”) select
new
Image(image.Element(“filename”).Value, image.Element(“description”).Value);


this.AddRange(images.ToList<Image>());

}

}

}

Creating the Controller

Right Click on Controller and add a controller called ImageController.


Type or paste below code inside ImageController class. This class got an action, which is returning View with instance of ImageModel in View dictionary.

Controller\ImageController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

using ImageViewer.Models;

namespace ImageViewer.Controllers

{


public
class
ImageController : Controller

{


//


// GET: /Image/


public
ActionResult Index()

{


return View(new
ImageModel());

}

}

}

Creating the View
Right click on View folder and add new View. Name of the View must be Index because controller name is here Index.



  1. Again right click on Image Folder in View and add a class. Give name of the class as Index.cs.
  2. Make this class as a partial class.
  3. Add reference

    using ImageViewer.Models;

  4. Inherit ViewPage<> in this partial class.
  5. Pass model class as parameter of ViewPage<ImageModel>

     

 

View/Image/Index.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using ImageViewer.Models;

namespace ImageViewer.Views.Image

{


public
partial
class
Index : ViewPage<ImageModel>

{

}

}

 

  1. Open Index.aspx
  2. Set code behind file as

    CodeBehind=”~/Views/Image/Index.cs”

  3. Here we will fetch all the images from ViewData dictionary.

     

View/Image/Index.aspx

<%@
Page
Title=””
Language=”C#”
MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”ImageViewer.Views.Image.Index”
CodeBehind=”~/Views/Image/Index.cs”
%>

<asp:Content
ID=”Content1″
ContentPlaceHolderID=”TitleContent”
runat=”server”>

    Index

</asp:Content>

<asp:Content
ID=”Content2″
ContentPlaceHolderID=”MainContent”
runat=”server”>


<%
foreach (var image in ViewData.Model) { %>


<span
class=”image”>


<a
href=”images/<%= image.Path %>“>


<img
src=”images/<%= image.Path %>
height=”100″
width=”100″
/></a>


<span
class=”description”><%= image.Description %></span>


</span>

<% }%>

</asp:Content>

Adding Link to navigate Image from Home page

  1. Click on View/Shared/site.Master
  2. Add below Action Link

    <li><%=Html.ActionLink(“Images”,“Index”,“Image”) %></li>

    So, now three action links would be there in master page

<ul
id=”menu”>


<li><%= Html.ActionLink(“Home”, “Index”, “Home”)%></li>


<li><%= Html.ActionLink(“About”, “About”, “Home”)%></li>


<li><%=Html.ActionLink(“Images”,“Index”,“Image”) %></li>



</ul>

Press F5 to run with debugging


Click on Image tab to get Images.


Adding Image

Amending the Model

Go to ImageModel class and add below method, which will add image in Images folder and its entry in XML file.

 

public
void Add(Image image, HttpPostedFileBase filebase)

{


string imagerep = HttpContext.Current.Server.MapPath(“~/Images/”);

filebase.SaveAs(imagerep + image.Path);


this.Add(image);


XElement xml = new
XElement(“images”, from i in
this


orderby image.Path


select
new
XElement(“image”,


new
XElement(“filename”, i.Path),


new
XElement(“description”, i.Description))

);


XDocument doc = new
XDocument(xml);

doc.Save(imagerep + “/ImageMetaData.xml”);

}

 

So, now the ImageModel class is been modified to

Models\ImageModel.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Xml.Linq;

namespace ImageViewer.Models

{


public
class
ImageModel:List<Image>

{


public ImageModel()

{


string directoryOfImage = HttpContext.Current.Server.MapPath(“~/Images/”);


XDocument imageData = XDocument.Load(directoryOfImage + @”/ImageMetaData.xml”);


var images = from image in imageData.Descendants(“image”) select
new
Image(image.Element(“filename”).Value, image.Element(“description”).Value);


this.AddRange(images.ToList<Image>());

}


public
void Add(Image image, HttpPostedFileBase filebase)

{


string imagerep = HttpContext.Current.Server.MapPath(“~/Images/”);

filebase.SaveAs(imagerep + image.Path);


this.Add(image);


XElement xml = new
XElement(“images”, from i in
this


orderby image.Path


select
new
XElement(“image”,


new
XElement(“filename”, i.Path),


new
XElement(“description”, i.Description))

);


XDocument doc = new
XDocument(xml);

doc.Save(imagerep + “/ImageMetaData.xml”);

}

}

}

Amending the Controller

In ImageController add actions which will perform task of adding the image into the resource. For that add below actions called Add and Save in Image Controller.

So, now Image Controller would look like below. Both Add and Save actions are highlighted in different colors.

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

using ImageViewer.Models;

namespace ImageViewer.Controllers

{


public
class
ImageController : Controller

{


//


// GET: /Image/

public ActionResult Index()

{

return View(new ImageModel());

}


public
ActionResult Add()

{


return View();

}

[AcceptVerbs(HttpVerbs.Post)]


public
ActionResult Save()

{


foreach (string name in Request.Files)

{


var file = Request.Files[name];


string fileName = System.IO.Path.GetFileName(file.FileName);


Image image = new
Image(fileName, Request[“description”]);


ImageModel model = new
ImageModel();

model.Add(image, file);

}


return RedirectToAction(“index”);

}

}

}

 Creating the View

Right click on View folder and add new View. Name of the View must be Index because controller name is here Add.



  1. Again right click on Image Folder in View and add a class. Give name of the class as Add.cs.
  2. Make this class as a partial class.
  3. Add reference

    using ImageViewer.Models;

  4. Inherit ViewPage<> in this partial class.
  5. Pass model class as parameter of ViewPage<ImageModel>

     

View/Image/Add.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using ImageViewer.Models;

namespace ImageViewer.Views.Image

{


public
partial
class
Add: ViewPage<ImageModel>

{

}

}

  1. Open Add.aspx
  2. Set code behind file as

    CodeBehind=”~/Views/Image/Add.cs”

  3. Type the below code in Add.aspx

     

View/Image/Add.aspx

<%@
Page
Title=””
Language=”C#”
MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”System.Web.Mvc.ViewPage”
CodeBehind=”~/Views/Image/Add.cs”
%>

<asp:Content
ID=”Content1″
ContentPlaceHolderID=”MainContent”
runat=”server”>

    Add

    <form
method=”post”
action=”<%=Url.Action(“Save”) %>
enctype=”multipart/form-data”>


<input
type=”file”
name=”file”
/>


<input
type=”submit”
value=”submit”
/>
<br
/>


<input
type=”text”
name=”description”
/>

</form>

</asp:Content>

Amending Views\Index.aspx

Add below ActionLink in index.aspx.

<p><%= Html.ActionLink(“Add your own image”, “Add”, “Image”)%></p>

So, Now modified Index.aspx will look like below,

<%@
Page
Title=””
Language=”C#”
MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”ImageViewer.Views.Image.Index”
CodeBehind=”~/Views/Image/Index.cs”
%>

<asp:Content
ID=”Content1″
ContentPlaceHolderID=”TitleContent”
runat=”server”>

    Index

    

</asp:Content>

<asp:Content
ID=”Content2″
ContentPlaceHolderID=”MainContent”
runat=”server”>


<%
foreach (var image in ViewData.Model) { %>


<span
class=”image”>


<a
href=”images/<%= image.Path %>“>


<img
src=”images/<%= image.Path %>
height=”100″
width=”100″
/></a>


<span
class=”description”><%= image.Description %></span>


</span>

<% }%>


<p><%= Html.ActionLink(“Add your own image”, “Add”, “Image”)%></p>

</asp:Content>

Press F5 to run the application


Click on Add your own image to add new Image. Browse the Image, give a description and click on submit button.