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.