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.

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.

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.

Fetching Windows Azure Mobile Services Data in XAML based Windows Store Application

In last post we started learning about Windows Azure Mobile Service in XAML based Windows Store Application. Read it here

In last post we learnt

  • Configuring Window Azure Mobile Service in portal
  • Consuming Windows Azure Mobile Service in Windows Store Application
  • Insert a record from application in Windows Azure Mobile Service data table.

In this post we will take a look on fetching records from table. I recommend you to follow Part 1 of this series here . I will start from where I left in part 1.

Let us design application page. There are two buttons. On click of first button we will fetch all data. On click of second button filtered data will fetched. Let us design application page as following


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" >
 <Grid.RowDefinitions>
 <RowDefinition Height="*" />
 <RowDefinition Height="*" />

 </Grid.RowDefinitions>

<StackPanel Orientation="Vertical" Grid.Row="0">
 <Button x:Name="btnFetch" Click="btnFetch_Click_1" Content="Get Data" Height="72" Width="233"/>
 <GridView x:Name="lstBloggers" >
 <GridView.ItemTemplate>
 <DataTemplate>
 <StackPanel Orientation="Horizontal">
 <TextBlock Text="{Binding Name}" />
 <TextBlock Text="{Binding Technology}" />
 </StackPanel>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>
 </StackPanel>
 <StackPanel Orientation="Vertical" Grid.Row="1">
 <StackPanel Orientation="Horizontal">
 <TextBox x:Name="txtSearch" Height="59" Width="436" />
 <Button x:Name="btnFilterfetch" Click="btnFilterfetch_Click_1" Content="Get Filtered Data" Height="72" Width="233"/>
 </StackPanel>
 <ListView x:Name="lstFilterBloggers" Margin="368,20,271,-599">
 <ListView.ItemTemplate>
 <DataTemplate>
 <StackPanel Orientation="Horizontal">
 <TextBlock Text="{Binding Name}" />
 <TextBlock Text="{Binding Technology}" />
 </StackPanel>
 </DataTemplate>
 </ListView.ItemTemplate>
 </ListView>
 </StackPanel>
 </Grid>

Yes this is not one of the best UI we can create but any way creating highly immersive UI is not purpose of this post. Right now UI will look like below image

image

Now to fetch all the records you need to follow following steps

Define Global variables


MobileServiceClient client;
 MobileServiceCollectionView<TechBloggers> items;
 MobileServiceCollectionView<TechBloggers> filteredItems;
 IMobileServiceTable<TechBloggers> bloggerstable;


You need to create mobile service table client in application. That can be created as following


public MainPage()
 {
 this.InitializeComponent();
 MobileServiceClient client = new MobileServiceClient("https://youappurl", "appkey");
 bloggerstable = client.GetTable<TechBloggers>();

 }

&nbsp;

Next you need to create entity class representing table from the Windows Azure Mobile Service. Let us create entity class as following. We are creating entity class TechBloggers.


public class TechBloggers
 {
 public int id { get; set; }
 [DataMember(Name="name")]
 public string Name { get; set; }
 [DataMember(Name = "technology")]
 public string Technology { get; set; }

}

On click event of button you can fetch all data from Mobile Service Table as following


private void btnFetch_Click_1(object sender, RoutedEventArgs e)
 {

items = bloggerstable.ToCollectionView();
 lstBloggers.ItemsSource = items;

}

You can fetch filtered data as following. We are filtering data on search term given in textbox.

private void btnFilterfetch_Click_1(object sender, RoutedEventArgs e)
 {
 filteredItems = bloggerstable.Where
 (blogger => blogger.Technology == txtSearch.Text)
 .ToCollectionView();
 lstFilterBloggers.ItemsSource = filteredItems;

 }

&nbsp;

When you run application you will find all data and filtered data as following

image

In this way we can fetch data from Windows Azure Mobile Service. In next post we will get into update and deletion of record. I hope this post useful. Thanks for reading.

Step by Step working with Windows Azure Mobile Service Data in JavaScript based Windows Store Apps

In my last post I discussed Step by Step working with Windows Azure Mobile Service Data in XAML based Windows Store Apps . In this post we will have a look on working with JavaScript based Windows Store Apps. Last post was divided in two parts. First part was Configure Windows Azure Mobile Service in Portal. You need to follow step 1 from last step to configure Windows Azure Mobile Service Data. To work with this proceed as given in following steps,

  1. Configure Windows Azure Mobile Service in Portal. For reference follow Step 1 of this Blog
  2. Download Windows Azure SDK and install.

Now follow post to work with Windows Azure Mobile Service Data from JavaScript based Windows Store Application.

Create Windows Store Application in JavaScript

Create Blank App from creating Blank App template from JavaScript Windows Store App project tab.

image

After creating project add Windows Azure Mobile Services JavaScript Client reference in project.

image

After adding reference let us go ahead and design app page to add a blogger in table. We are going to put two text boxes and one button. On click event of the button blogger will be inserted as row in data table of Windows Azure Mobile Services.


<body>

 <h2>Adding Record to Windows Azure Mobile Service Data</h2> <br />
 Name : <input id="txtname" type="text" /> <br />
 Technology : <input id="txttechnology" type="text" /> <br /> <br />
 <button id="btnInsert" >Insert Blogger</button>

</body>

Application will look like following,

image

We need to add reference of Windows Azure Mobile Service on HTML as following


<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
 <script type="text/javascript" src="/MobileServicesJavaScriptClient/MobileServices.js"></script>

Next let us create client for Windows Azure Mobile Service. To create this you need to pass application URL and application Key. Client in JavaScript based application can be created as following


args.setPromise(WinJS.UI.processAll());
 var client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
 "https://appurl",
 "appkey"
 );

Now let us create a proxy table. Proxy table can be created as following and after creating proxy table we can add record in table as following


var bloggerTable = client.getTable('techbloggers');

var insertBloggers = function (bloggeritem) {

bloggerTable.insert(bloggeritem).done(function (item) {
 //Item Added
 });

On click event of button we need to call insertBloggers javascript function.

btnInsert.addEventListener("click", function () {
 insertBloggers({
 name: txtname.value,
 technology: txttechnology.value
 });
 });

On click event of button you should able to insert blogger in Windows Azure Mobile Service Data table. In further post we will learn to perform update, delete and fetch data. I hope you find this post useful. Thanks for reading.

Step by Step working with Windows Azure Mobile Service Data in XAML based Windows Store Apps

In this post we will take a look on working with Windows Azure Mobile Service in XAML based Windows Store Application. We will follow step by step approach to learn goodness of Windows Azure Mobile Service. In first part of post we will configure Windows Azure Mobile Service in Azure portal. In second part of post we will create a simple XAML based Windows Store application to insert records in data table. This is first post of this series and in further posts we will learn other features of Windows Azure Mobile Services.

Configure Windows Azure Mobile Service on Portal

Step 1

Login to Windows Azure Management Portal here

Step 2

Select Mobile Services from tabs in left and click on CREATE NEW MOBILE SERVICE

image

Step 3

In this step provide URL of mobile service. You have two choice either to create mobile service in existing database or can create a new database. Let us go ahead and create a new database. In DATABSE drop down select option of Create New SQL database instance. Select SUBSCRIPTION and REGION from drop down as well.

image

Step 4

On next screen you need to create database. Choose either existing database server or create a new one. You need to provide credential to connect with database servers.

image

Step 5

After Successful creation of mobile services you need to select platform. Let us go ahead and choose Windows Store as platform

image

Step 6

After selecting platform click on Data in menu. After selecting Data click on ADD A TABLE

image

Next you need to provide Table name. You can provide permission on table. There are three options available

  1. Anybody with Application Key
  2. Only Authenticated Users
  3. Only Scripts and Admins

Let us leave default permission level for the table.

image

Step 7

Next click on tables. You will be navigated to table dashboard. When you click on Columns you will find one default created column id. This column gets created automatically. This column must be there in Windows Azure Mobile Service table.

image

On enabling of dynamic schema when you will add JSON objects from client application then columns will get added dynamically.

Create Windows Store Application in XAML

Very first you need to install Windows Azure SDK for Windows Phone and Windows 8.

image

After installing create a Windows Store Application by choosing Blank App template.

image

Before we move ahead to create Windows Store App let us go back to portal and mange App URL and key. You need key and application URL to work with Windows Azure Mobile Services from Windows Store application. You will find key and application URL at the portal.

image

Now go ahead and add following namespaces on MainPage.xaml.cs


using Microsoft.WindowsAzure.MobileServices;
using System.Runtime.Serialization;

Next you need to create entity class representing table from the Windows Azure Mobile Service. Let us create entity class as following. We are creating entity class TechBloggers.


public class TechBloggers
 {
 public int id { get; set; }
 [DataMember(Name="name")]
 public string Name { get; set; }
 [DataMember(Name = "technology")]
 public string Technology { get; set; }

}

After creating entity class go ahead and global variables.


MobileServiceClient client;
 IMobileServiceTable<TechBloggers> bloggerstable;

Once global variable is defined in the constructor of page you need to create instance of MobileServiceClient and MobileServiceTable. Let us go ahead and create that in constructor of the page.


public MainPage()
 {
 this.InitializeComponent();
 MobileServiceClient client = new MobileServiceClient("https://youappurl", "appkey");
 bloggerstable = client.GetTable<TechBloggers>();

 }

Now let us go back and design app page. On XAML let us put two textboxes and one button. On click event of button we will insert bloggers in the table.


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" >
 <Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 </Grid.RowDefinitions>
 <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="40,40,0,0">
 <TextBlock Text="Name" FontSize="40" />
 <TextBox x:Name="txtName" VerticalAlignment="Top" Width="400" />
 </StackPanel>
 <StackPanel Orientation="Horizontal" Grid.Row="1" Margin="40,40,0,0">
 <TextBlock Text="Technology" FontSize="40" />
 <TextBox x:Name="txtTechnology" VerticalAlignment="Top" Width="400" />
 </StackPanel>

 <Button Grid.Row="2" x:Name="btnInsert" Click="btnInsert_Click_1" Content="Insert Record" Height="72" Width="233" Margin="248,42,0,-14" />

 </Grid>

Application will look like as given in below image. I know this is not best UI. Any way creating best UI is not purpose of this post

image

On click event of button we can insert a record to table using Windows Azure Mobile Services using following code


private void btnInsert_Click_1(object sender, RoutedEventArgs e)
 {

TechBloggers itemtoinsert = new TechBloggers
 {
 Name = txtName.Text,
 Technology = txtTechnology.Text
 };

InserItem(itemtoinsert);

}

InsertItem function is written like following,

private async void InserItem(TechBloggers itemtoinsert)
 {

await bloggerstable.InsertAsync(itemtoinsert);

 }

On click event of button you can insert records in Windows Azure Mobile Service data table. To verify inserted records browse to portal and click on table.

image

In further posts we will learn update, delete and view of the records. I hope you find this post 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.

Presented in C-Sharp Corner MVP Summit

View Event Photos here

It was electrifying, high on energy and absolute impeccable event. I love each second spent at C-Sharp Corner MVP SUMMIT.

image

This three days event was in Country Inn and Suites from 21st March 2013 to 23rd March 2013. All participants was indulged for all three days in this very successful event.

image

I got an opportunity to be part of all three days. Third day was open developer’s day and any developer could attend that. There was sparkling 200+ developers all around Delhi/NCR present at third day. Third day 23rd March 2013 was lined up with industry speakers and veterans.

image

I got an opportunity to present on “Develop for Windows 8 “. This time I tried story telling way of presentation and found audience enjoyed that too much. Please find PPT of presentation below,

 

In demo I created “Flickr Search Application”. Read full blog post about Demo here

clip_image002

View Event Photos here

I had great time presenting and being part of this esteem event. Excited to see you soon in next event. Thanks !

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.

How to work with Navigation App Template in Windows Store App with JavaScript

Recently I was attending a user group event and one young developer came to me with question, could you help me in finding out how to work with Navigation App Template in Windows Store App? So in this post I am trying to explain step by step working with Navigation App Template.

Very first start with creating a new project and select Navigation App from project template.

image

If you navigate to solution explorer you will find that there is one folder pages. Ideally all pages of the application should be (not must be) in this folder. By default there is one page called home page is there .

image

Let us stop at this point to explore default.html. In default.html you will find there is a PageControlNavigator. This control will host all the pages. Essentially Navigation Application Template follows singe page navigation mechanism. You will notice in data-win-option that there is home parameter and it is set to a page.

image

In this case home page or first page to be loaded in PageControlNavigator is home.html. Let us go ahead and design home.html. We will change title of the page and put a button. On touch of the button user will be navigated to another page.

image

Let us go ahead and run the application. You will get home.html loaded as home page with the title and button. You will notice that template has taken care of margin.

image

Let us say you want to navigate to Page2.html on click or touch of button. For that very first task you need to do is to add Page2.html in the project. For that right click on the pages folder and add a new subfolder called page2. Then right click on the newly added subfolder page2 and add a new item. Choose Page Control to add as new item.

image

After adding new page control solution explorer should look like following image. In the pages folder you can see that there is one more subfolder page2 with page2 page control.

image

Now we need to write code to navigate to page2.html on the click event of the button. Open home.js and type this code to navigate. You can navigate from one page to another page using WinJS.Navigation.navigate function. This function takes two parameters. First parameter is address of the page to navigate and second parameter is data to be passed while navigating.


element.querySelector("#btnnavigate").onclick = function (args) {
 WinJS.Navigation.navigate("/pages/page2/page2.html",
 { data: "data to other page" }
 );
 };

At this point you should able to navigate to page2 from home page. You can find that template has taken care of back button and margin in page2.

image

Above we are passing “data” while navigating. Now we need to write some code on page2.js to consume data being passed. Let us replace the title of the page2 with the data being passed. We will write this code in ready function of page2.js.


ready: function (element, options) {
 // TODO: Initialize the page here.
 var datapassedhere = options.data;
 element.querySelector(".pagetitle").innerText = datapassedhere;

Now on running application you will see page2 title has been replaced with the data being passed from home page.

image

In this way you can work with Navigation App template. I hope you find this post useful. Thanks for reading.