ListView in WinJS based Windows Store Application

In 2012 I wrote a post List View Data Binding in Windows 8 JavaScript Metro Application. If you follow along this post some of the code will not work. So I decided to write a post again on working with ListView in WinJS. There are three simple steps to work with the ListView.

Step1: Create the Data Source

Let us use JavaScript array as the data source. In the real application you may want to call a service to fetch the data and create the data source. The JavaScript array is created as follows:

 


var MovieData = [
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                   ];

We cannot set an array directly as the data source of ListView. So to set array as the data source we need to convert the array as List object. MovieArray can be converted to the List object as shown follows:

 


var dataList = new WinJS.Binding.List(MovieData);

Step2: Create the Template

Once the data source is in placed we need to decide how to display the data in the ListView. Using the Template we decide the way ListView item will be rendered. Binding template can be created setting data-win-control attribute of a div to WinJS.Binding.Template. We are displaying and Photo from the data source. You need to make sure to use exact the same property name as it is in the data source.

 


<div id="movieitemtemplate"
         data-win-control="WinJS.Binding.Template">
        <div data-win-bind="innerText:Name"
             style="height:20px;">
        </div>
        <img data-win-bind="src:Photo"
             style="width:200px;height:150px;" />
    </div>


Step3: Create the ListView

A div can be converted to a ListView setting data-win-control property to WinJS.UI.ListView. We are setting the itemTemplate to movieitemtemplate which we created in the previous step.

 


<div id="MovieListView"
         data-win-control="WinJS.UI.ListView"
         data-win-options="{itemTemplate: select('#movieitemtemplate')}">
    </div>


After the ListView is created last step is to bind the ListView to the data source. We have already created List using the JavaScript array. To bind set data source of the list as the itemDataSource of the ListView. It is shown as follows:

 

args.setPromise(WinJS.UI.processAll());
            var dataList = new WinJS.Binding.List(MovieData);
            var MovieList = document.getElementById('MovieListView').winControl;
            MovieList.itemDataSource = dataList.dataSource;


That’s it. These three steps are needed to work with a ListView in WinJS. Hope you like it. Happy coding.

Working with app bar in WinJS based Windows Store Application

In this post we will learn to work with the app bar in a WinJS based Windows Store application. Let us start with creating an app bar. The app bar can be created by setting the data-win-control value of a div to WinJS.UI.AppBar.

 


<div data-win-control="WinJS.UI.AppBar" data-win-options="{placement:'bottom'}">


</div>

Now you can add command buttons in an app bar as follows:

 


   <div data-win-control="WinJS.UI.AppBar" data-win-options="{placement:'bottom'}">
        <button data-win-control="WinJS.UI.AppBarCommand"
                data-win-options="{id:'cmdhome',icon:'home',section:'selection',tooltip:'home'}"></button>
        <button data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdsave',icon:'save',tooltip:'click to save'}">
        </button>
       
    </div


As of now we have added two command buttons with the icon, tooltip etc. A command button can be added to a app bar using the button control attributed with the WinJS.UI.AppBarCommand attribute.

image

Let us say you want to add a flyout on the click of the app bar command. That can be added in two steps.

 


<div id="volumeFlyout"
         data-win-control="WinJS.UI.Flyout">
        <h3>Volume</h3> <input type="range" />
    </div>

As the second step we can use this flyout as option in app bar command. This can be done as follows

 

<button data-win-control="WinJS.UI.AppBarCommand"
                data-win-options="{
            id: 'flyout',
            icon: 'volume',
            label: 'Volume',
            type: 'flyout',
            flyout: select('#volumeFlyout')}"></button>

On running application you will find that click of volume command gives a flyout .

image

You can also style the app bar. For example app bar color can be changed using the CSS a below,

 


.win-appbar
{
    background-color: red;
    border: 3px solid blue;
}

On running you will find that app bar color has been changed as shown below:

image

You can change the image of the icons using the CSS shown below:

 


.win-appbar .win-commandimage
{
    color: rgb(28, 160, 218);
}


On running you will find that app bar color has been changed as shown below:

clip_image002

You can apply many such style to app bar and its commands. You can attach event to the command buttons and call a function to perform a task.

I hope this post is useful. Thanks for reading.

Capture photo and save on the disk in WinJS based Windows Store App

In this post we will learn to capture a photo and save the captured photo on the disk. You can work with camera and capture a photo in the WinJS using the Windows.Media.Capture.CameraCaptureUI(). Let us start with creating the UI for the application. In the UI, we will have

  • Application bar with two buttons
  • One button to capture the photo
  • Second button is to save the photo in the Picture Library
  • Image control to preview the capture photo

Let us get it started with creating the UI. The UI mark-up will look like as follows:


<body>

    <div id="application">
        <img id="imgCaptured" />
    </div>

    <div id="AppBar" data-win-control="WinJS.UI.AppBar" data-win-options="">
        <button id="cmdSave" data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdSave',label:'Save',icon:'save',section:'global',tooltip:'save'}">
        </button>
        <button id="cmdCamera" data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdCamera',label:'Capture Photo',icon:'camera',section:'global',tooltip:'Capture Photo'}">
         </button>
       
    </div>
</body>


On running the application you should have a blank page with the app bar. There are two buttons to capture the photo and to save the captured photo on the disk. On the click event of the cmdCamera button we will capture a photo using following code.

 


function startCamera() {
       
            cam.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (file) {
                if (file) {

                    imgCaptured.src = URL.createObjectURL(file)
                    FileToSave = file; 

                } else {
                    
                }
            }, function (err) {
                displayError(err);
            });
       
    }


Globally we have defined three variables as below,

 


     var FileToSave; 
    var cam = new Windows.Media.Capture.CameraCaptureUI();
    var folder = Windows.Storage.KnownFolders.picturesLibrary; 


Attaching click events to both buttons as shown below:

 


args.setPromise(WinJS.UI.processAll());

            document.getElementById("cmdCamera").addEventListener("click", startCamera, false);
            document.getElementById("cmdSave").addEventListener("click", takePhoto, false);

As you see on the cmdCamera button we are calling the startCamera function which is shown above. In this function by using the Media.Capture.CameraCaptureUI capturing the photo and binding that to an image control. On the other hand on the click of cmdSave we are saving the image on the disk.


function takePhoto() {
        
       
        folder.createFileAsync("photo.jpg", Windows.Storage.CreationCollisionOption.replaceExisting)
          .then(function (file) { 
              FileToSave.copyAndReplaceAsync(file);

          });
    }

The captured photo is saved in the picture library using the instance of Windows.Storage.KnownFolders.picturesLibrary. The captured image is saved with the name photo.jpg.

This is all you need to capture an image and save it in the picture library. On running application should look like follows,

image

If you are following along then find application should look like shown above. I have also used CSS to display captured image in the centre. Used CSS is given below:

 


#imgCaptured {
    
    margin-top: 200px;
    margin-left: 100px;
    width:400px;
    height: 400px; 
    margin-right:10px;
 
}

I hope this post is useful. Thanks for reading. Happy coding.

Classes in WinJS

Even if we have heard many times about the classes in the JavaScript, it is not an object oriented language. Rather JavaScript is a prototypal language. Working with classes in JavaScript can be but cumbersome syntactically. WinJS is a JavaScript library and it reduced the syntactical complexity of working with classes. In this post we will learn to work with classes in WinJS.

Let us start with creating a class in pure JavaScript and then we will compare how easy it is to work with classes in WinJS. In JavaScript a class can be created as shown below,


    function Product(name, price) {
        this.name = name;
        this.price = price;
        this.Display = function () {
            console.log(this.name + this.price);
        }
    }

    var p = new Product("Pen", 30);
    p.Display();


If we want we can derive the class using prototype which makes working with classes’ complex in JavaScript. A class in WinJS can be created using WinJS.Class.define . It mainly contains three sections as constructor, instance members and static members.

image

You can create constructor using the function as shown below. You can pass parameters in the constructor and set the value of the private variables. A constructor with two input parameter can be created as shown below

    var Product = WinJS.Class.define(

          //constructor
          function (name, price) {
              this.name = name;
              this.price = price;

          }
          //instancemembers
          //staticmembers

        );


Next we can add instance members using the methods. To add instance members after constructor put a comma and then start a curly braces. Within this curly braces you can put all the instance members.


   {

              Display: function () {
                  return this.name + " costs " + this.price + "$";
              }
  }

You can also static member in the WinJS class. That can be added as third parameter after the comma of instance members. So let us go ahead and add a static member distributor. This can be added as follows:


//staticmembers
          {
              DistributorName : "ABC Corp"
          }

Entire Product class with constructor, instance functions and static members will look like as follows:

var Product = WinJS.Class.define(

          //constructor
          function (name, price) {
              this.name = name;
              this.price = price;

          },
          //instancemembers
          {

              Display: function () {
                  return this.name + " costs " + this.price + "$";
              }
          },
           //staticmembers
          {
              DistributorName : "ABC Corp"
          }
         

        );


Once class is created we can create instance of class and use the properties as show below.


var product1 = new Product(name, price);
                var textToDisplay = product1.Display();
                var disName = Product.DistributorName;


If you notice we are using static variable name directly with the class name. If you have any experience working with classes in JavaScript you should able to notice that working with classes in WinJS is relatively very easy syntactically.

Now let me show you a real example of working with the Product class created above. I have created a view in which user can enter name and price and on click of the button message from the Product class will get updated in the label.

<input id="txtName" type="text" />
    <input id="txtPrice" type="text" />
    <br/>
    <button id="btnDisplay">Display Product</button>
    </br/>
    <label id="lblProduct">result here </label>
    <label id="lblDis" >result here </label>

On the JS file on the click event of the button we are creating instance of the Product class by passing user input and displaying the message in the label.


document.querySelector("#btnDisplay").onclick= 
                function () {

                var name = document.querySelector("#txtName").value;
                var price = document.querySelector("#txtPrice").value;

                var product1 = new Product(name, price);
                var textToDisplay = product1.Display();
                var disName = Product.DistributorName;


                document.querySelector("#lblProduct").textContent=textToDisplay;
                document.querySelector("#lblDis").textContent = disName;

            };


Great now let us see how we can derive a class from another class.


var SportsProduct = WinJS.Class.derive(Product,
        
        function(name,price,color)
        {
            this.name = name;
            this.price = price;
            this.color = color;
        },

        {
             //instance members
        },
        {
            //static members 
         });


Derived class will have access of all the members of base class. Now we can use derive class to create new instance as show below:


       var product1 = new SportsProduct("Pen", 30,"Red");

In this way we can work with classes in WinJS and you can see that working with class syntactically very easy as compare to JavaScript.

Happy Coding.

Data Binding and Observable in WinJS

Source code on GitHub

In this post we will learn how to work with the data binding and observable class in the Windows Store application created using WinJS. We will learn to work with

  • Data binding
  • Two way data binding
  • Observable object

By default WinJS

  • Provides one way binding
  • When the data source is updated HTML element gets updated
  • Updated value of HTML element does not update the data source.

Let us start with working with a basic data binding example. So I have a JavaScript object as shown below,


var student = { name: "Dj" };

We can perform data binding in winJS using data-win-bind attribute on the HTML element.

clip_image002

In above code snippet we are using data-win-bind attribute to bind span inner text with the name property of the student object. As of now HTML is very simple and looks like as follows:


<body>
     <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerText: name">
        </span>
    </div>

</body>

As the last step of the data binding we need to call WinJS.Binding.processAll() by passing the data source and the target HTML element. Make sure that you call this after the execution of all the activation codes.


    var personDiv = document.querySelector('#nameSpan');
    WinJS.Binding.processAll(personDiv, student);

Essentially we are selecting the element using the document.querySelector and the in the process all function passing the target element and the data source as a data context. By now we have successfully data bind html element to the data source. On running the application you should get output as follows

clip_image002[6]

So far we have done one way binding and if data changes at the data source target element won’t get any notification. We can convert a data context to a binding context using the WinJS.Binding.as. To understand this in better way let us start looking at a problem statement. I have modified the UI as follows,


<body>
    <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerText: name">
        </span>
        <br/>
        <input type="text" id="txtInput" />
        <button id="btnUpdataDs">Update DataSource</button>
    </div>

</body>

Now UI look like as follows and when we enter a value in the text box that should update the welcome span.

clip_image002[8]

On the click event of the button we can modify name property as follows


document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           student.name = updatedname;
        }

When run the application you will find that value of the welcome span is not getting updated. Reason behind is that when data source is getting updated it does not send any notification to the target elements bind to it. WinJS gives us a method to create notification on the data source and convert it to a binding context. You need to use WinJS.Binding.as to create binding context.

So let us modify the above code to perform two way binding,

var personDiv = document.querySelector('#nameSpan');
        WinJS.Binding.processAll(personDiv, student);
        var bindingSource = WinJS.Binding.as(student);
        document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           bindingSource.name = updatedname;
        }

In above code there is only one extra added line

clip_image002[10]

Now on running the application you will find that when you change the value in text box and click on update data source value of welcome span will also be changed.

clip_image004

WinJS data bind allows us to to do binding of styles as well. Let us go ahead and add one more property to set the color of the text. Updated data source is as follows:

 


   var student = {
        name: "Dj",
        color: "red"
     };

And we can bind color to the welcome span as follows


<span id="nameSpan"
              data-win-bind="innerHTML: name;
               style.background: color ">
        </span>

And we can update value of color as follows

var personDiv = document.querySelector('#nameSpan');
        WinJS.Binding.processAll(personDiv, student);
        var bindingSource = WinJS.Binding.as(student);
        document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           bindingSource.color = updatedname;
        }

Now let us see that how can we bind to a complex object. We will start with creating a complex object. Working with complex object can be summarized into following steps

  1. Create the class
  2. Add _initObservable method in the constructor of the class
  3. Make class observable by using the WinJS.Class.mix
  4. Create instance of the object
  5. Use bind methods to bind the properties
  6. Use the object in the binding

Let us start with creating a Student class

 


var Student = WinJS.Class.define(
       function()
       {

           this.name = "DJ";
           this.size = "16px";
       },
       {

           _names:
               ["foo", "loo", "koo", "too", "moo", "soo", "aoo", "too", "qoo", "coo"],
           _sizes:
               ["30px", "80px", "40px","20px","35px","67px","43px","23px","54px","12px"],

           _newName: function () {
               this["name"] = this._names[this._randomizeValue(this._names.length)];
               this["size"] = this._sizes[this._randomizeValue(this._sizes.length)];
           },
           _randomizeValue: function (max) {
               return Math.floor((Math.random() * 1000) % max);
           }

       });

In this class we have put two arrays and two functions. In the constructor of the class we are setting default value for name and the size. _newName function will return new name from the array with new size from the size array.

Next we need to add _initObservable inside the constructor. So updated constructor will look like as follows:

 


  var Student = WinJS.Class.define(
       function()
       {
           this._initObservable();
           this.name = "DJ";
           this.size = 16;
       },

Now to make the object observable we need to use WinJS.Class.mix. This can be done as follows:


    WinJS.Class.mix(Student,
    WinJS.Binding.mixin,
    WinJS.Binding.expandProperties({name: "", size: ""})
);

After this step we need to call the bind method on the instance of the Student class. Make sure to create instance in the app.onactivated event handler.

 

            var s = new Student();
            s.bind("name",onNameChange);
            s.bind("size", onSizeChange);

The bind method takes two parameters. First name of the property and second parameter as the function which will define how property will be bind. Below we have function calling on the bind.


function onNameChange (newValue) {
        var span = document.getElementById("nameSpan");
        span.innerText = newValue;
    };

    function onSizeChange (newValue) {
        var span = document.getElementById("nameSpan");
        span.style.fontSize = newValue;
    };

On the HTML markup is bind to properties of Student and there a button. On click event of the button we will call _newName function on the student object to change the name and the font size.


   <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerHTML: name;
               style.fontsize: size ">
        </span>
        <br/>
        <button id="btnUpdataDs">Update DataSource</button>
    </div>

On the click event of the button we will call _nameName function as shown below:

document.querySelector("#btnUpdataDs").onclick = function () {

            s._newName();
        }

When you run the application on the click of the button name and size of the name should change. Data binding and the observable are very important components of WinJS and you may want to use them while create app for the Windows Store.

Source code on GitHub

Happy Coding.

Store and Retrieve JSON data from Local storage in Windows Store App

In this tutorial step by step we will learn to save and Retrieve JSON data in Local folder of Windows Store App.

Follow following steps to save and retrieve JSON data in local storage.

Step 1

Right click on project and add Nuget package and add package of Json.NET.

image

Step 2

Let us assume that we need to store Student information in local storage. For that I have created a Student class.

 


public class Student
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Grade { get; set; }
    }


Step 3

Before saving data we need to serialize the class into JSON. We will serliaze that using JSON.net library. After serializing object into JSON we will save data in local folder of windows store application.

 


            string jsonContents = JsonConvert.SerializeObject(s);           
           StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           StorageFile textFile = await localFolder.CreateFileAsync("a.txt",CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
            {
        
                using (DataWriter textWriter = new DataWriter(textStream))
                {
                    textWriter.WriteString(jsonContents);
                    await textWriter.StoreAsync();
                }
            }

        }


S is object of class Student. We are reading student properties from various textboxes.

 


            Student s = new Student
            {
                Name =txtName.Text,
                City = txtCity.Text,
                Grade =txtGrade.Text
            };


In above code snippet,

  • We are saving file in application local folder
  • Data is saved in file a.txt
  • Opening file in asynchronous way for read write operation using IRandomAccessStream
  • Using DataWriter to write data in file

In these four steps data can be saved in local folder of Windows Store Application.

Step 4

To read JSON data back we need to first read data from local storage and then deserliaze that to object from JSON. Reading data is very simple.

  • Open local folder
  • Load file asynchronously
  • Open file asynchronously to read the streams
  • Using DataReader reading stream
  • Convert JSON to object
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           StorageFile textFile = await localFolder.GetFileAsync("a.txt");
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                       
                    using (DataReader textReader = new DataReader(textStream))
                    {                                            
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        string jsonContents = textReader.ReadString(textLength);                      
                        Student s = JsonConvert.DeserializeObject<Student>(jsonContents);
                        txtName1.Text = s.Name;
                        txtCity1.Text = s.City;
                        txtGrade1.Text = s.Grade;
                       
                    }
                }

In above code snippet,

  • We are opening local folder
  • Opening file asynchronously
  • Reading stream in IRandonAccessStream
  • Reading data using DataReader
  • DeSeralizing JSON to object using JsonConver

By following above steps you can save and retrieve data in local folder of Windows Store application. I hope you find this article useful.

Solved: WWAHost.exe remote endpoint was not reachable error in JavaScript Windows Store App

I was working on my office machine. While working I opened a JavaScript based Windows Store Application. When I tried to run application I got following exception,

image

I was baffled due to this exception. After sort of research I found that I was on VPN. I have no idea why on VPN this exception occurred. But to get rid of this exception you need to follow these two steps

  1. Closed all connections to VPN
  2. Restart machine

After performing above two steps you should not get above exception. I hope this quick post is useful. Thanks for reading.

Solved Exception in Passing Relative URI to Windows Runtime

While working today on a Windows Store Application I had a requirement to work with URI. Business class was as follows,

 

image

And I created instance of Product class in usual way setting values for both properties. I had put all images in ProductImages folder.

 

image

 

On running application I got following exception that given System.Uri cannot be converted.

image

 

After small research I found that WinRT does not support Relative URI. It only supports Absolute URI.

 

image

 

Now I fixed above problem by converting Relative URI to Absolute URI.

 

image

 

Exception got fixed after changing URI as absolute URI. I hope you find this quick fix useful. Thanks for reading.

Binding Image with Picture Library Images in Windows Store Application using FileOpenPicker

In this post we will take a look on binding image with Picture Library Images in Windows Store. In this post we will follow following steps

  • User will click on a button
  • On button click user will be select an image from Picture Library
  • Selected image will be bind to image control on the page

Application will behave as following,

image

In XAML based Windows Store Application object of FileOpenPicker allows us to choose files from Picture Library and Document Library. Essentially we will create instance of FileOpenPicker on click event of button and then restrict user to select only images. Once user has selected image, we will bind that Image to image control on the page.

Let us start with designing the page. Page design is very simple with button, image control and two text blocks.


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
 <Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="*" />
 </Grid.RowDefinitions>
 <TextBlock Text="Select Photo from Picture Library" Margin="15,20,0,0" FontSize="40"/>
 <StackPanel Orientation="Horizontal" Grid.Row="1">
 <Button x:Name="btnFilePickerOpen" Click="btnFilePickerOpen_Click_1" Content="Select Image" Width="303" Height="97" Margin="50,50,0,403"/>
 <StackPanel Orientation="Vertical" Margin="50,50,0,0">
 <Image x:Name="imgSelected" />
 <TextBlock x:Name="txtSelectedImagePath" Margin="30,30,0,0" FontSize="30" />
 </StackPanel>
 </StackPanel>
 </Grid>

On click event of button we will create object of FileOpenPicker and allow user to select an image. We need to follow following steps

  • Create object of FileOpenPicker
  • Select ViewMode. There are two ViewModes available Thumbnail and List. Let us choose Thumbnail for our demo.
  • Provide SuggestedStartLocation. Let us select PicturerLibrary since we want to choose an image. Other options are VideosLibrary, DocumetsLibrary etc.
  • Apply filter. We can apply filters on type of files we will allow user to choose. We are adding file types jpg,jpeg and png.
  • In last step asynchronously we are calling PickSingleFileAsync function and taking reference of selected file in StorageFile.
FileOpenPicker openPicker = new FileOpenPicker();
 openPicker.ViewMode = PickerViewMode.Thumbnail;
 openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 openPicker.FileTypeFilter.Add(".jpg");
 openPicker.FileTypeFilter.Add(".jpeg");
 openPicker.FileTypeFilter.Add(".png");
 StorageFile file = await openPicker.PickSingleFileAsync();
 if (file != null)
 {

 }
 else
 {

 }

On successful selection of file we need to convert that in image stream and bind that to image control. We are creating instance of BitmapImage and reading file stream in that. After successful reading setting bitmap image as source of image control.


if (file != null)
 {
 txtSelectedImagePath.Text = file.Name;
 var filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
 BitmapImage imagetobind = new BitmapImage();
 imagetobind.SetSource(filestream);
 imgSelected.Source = imagetobind;

 }
 else
 {
 txtSelectedImagePath.Text = "Some problem fetching file ";
 }

&nbsp;

This is what all we need to do to fetch an image from picture library and bind it to image control. Full source code of button click is given below,


private async void btnFilePickerOpen_Click_1(object sender, RoutedEventArgs e)
 {
 FileOpenPicker openPicker = new FileOpenPicker();
 openPicker.ViewMode = PickerViewMode.Thumbnail;
 openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 openPicker.FileTypeFilter.Add(".jpg");
 openPicker.FileTypeFilter.Add(".jpeg");
 openPicker.FileTypeFilter.Add(".png");
 StorageFile file = await openPicker.PickSingleFileAsync();
 if (file != null)
 {
 txtSelectedImagePath.Text = file.Name;
 var filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
 BitmapImage imagetobind = new BitmapImage();
 imagetobind.SetSource(filestream);
 imgSelected.Source = imagetobind;

 }
 else
 {
 txtSelectedImagePath.Text = "Some problem fetching file ";
 }
 }

Now when you run application you will able to choose an image from Picture Library and bind it to image control.

image

I hope you find this post useful. Thanks for reading.

Create Flickr Photo Search Windows Store App in XAML

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.