List View Data Binding in Windows 8 JavaScript Metro Application

In this post we will see,

  1. Working with ListView control in WinJS
  2. ItemTemplte in WinJS
  3. Data Binding to ListView
  4. Creating Data Source in WinJS

For purpose of this post I am going to bind name and images of Indian cricket player in ListView. After data binding ListView should look like below,

image

To bind data with ListView you need to follow certain steps.

  1. Create a Data Source
  2. Create ItemTemplate and bind data source properties to Html elements of ItemTemplate
  3. Create ListView and attach ItemTemplate to ListView
  4. Set the DataSource of ListView

Create Data Source

Let us create data to bind to the List View. I have given name of the array as PlayerData. This contains two objects Name and Photo.


var PlayerData = [
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' },
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' }
];

To create Data Source, I have put all the images of players in image folder. In real time applications, data must be downloaded from the Service.

Create Item Template

We need to create ItemTemplate to bind with the ListView. There are few points you need to keep in mind while creating ItemTemplate

  • ItemTemplate is a div
  • To convert div as ItemTemplate div need to have attribute data-win-control set to WinJS.Binding.Template
  • Other HTML elements should be inside the template div tag.
  • Data-win-bind is used to bind data to HTML elements.

Below I have put one div to bind name of the player and image to bind image of the player.

image

Create ListView

Data has been created. ItemTemplate has been created. Next you need to create ListView and bind ItemTemplate to that ListView.

  • ListView is a div
  • data-win-control property of div should be set to WinJS.UI.ListView
  • data-win-options take complex values.
  • Value of itemRenderer should be set to id of the div created as ItemTemplate. In our case id of ItemTemplate div is playeritemtemplate. So value of itemRenderer should be playeritemtemplate.
  • Layout should be set.
  • Value of maximum rows can be set.

Below you can find, I have created ListView and bind it to the ItemTemplate.

image

Putting all together HTML should be as below. I have put an output div. Selected value from the ListView will be displayed in output div.

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DataBindingPlayer</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/ui.js"></script>
<script src="/winjs/js/binding.js"></script>
<script src="/winjs/js/controls.js"></script>
<script src="/winjs/js/animations.js"></script>
<script src="/winjs/js/uicollections.js"></script>
<script src="/winjs/js/wwaapp.js"></script>

<!-- DataBindingPlayer references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<h2>Indian Team</h2>
<br />

<div id="playeritemtemplate"
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>

<div id="PlayerListView"
data-win-control="WinJS.UI.ListView" style="height:185px;"
data-win-options="{itemRenderer:playeritemtemplate,layout:{type:WinJS.UI.GridLayout,maxRows:1}}" >
</div>

<br />
<div id="ouputDiv" >
<span>You Selected </span>
<span id="selectedPlayer" style="height:20px;" ></span> <br />
<img id="selectedPlayerImg" style="width:200px;height:150px;"/>
</div>
</body>
</html>

Binding Data Source to ListView

To bind ListView with data source, first you need to fetch ListView div and then simply set datasource value. Below I am fetching ListView div and then setting data source value to PlayerData. If you remember, I created PlayerData as data source in starting of this post.

image

Attaching event to ListView

As of now you have created ListView and bind data source to that. Next you may want to fetch the selected item. For that you need to attach iteminvoked event to the ListView. You can add that as below. In below SelectItem is a function and it will get called on the item selection

image

In SelectItem function you will have to fetch the value of selected item and set as value of HTML element of output div.

image

Putting all together js file will have below codes

Default.js


(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);


var PlayerData = [
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' },
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' }
];

WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
WinJS.UI.processAll().then(function () {
var PlayerList = document.getElementById('PlayerListView').winControl;
PlayerList.dataSource = PlayerData;
PlayerList.addEventListener('iteminvoked', SelectItem);
});

}
}

function SelectItem(e) {
var selectedItem = PlayerData[e.detail.itemIndex];
var selecteplayer = document.getElementById('selectedPlayer');
selecteplayer.innerText = selectedItem.Name;
var selecteplayerImg = document.getElementById('selectedPlayerImg');
selecteplayerImg.src = selectedItem.Photo;
}


WinJS.Application.start();
})();



On running you should get ListView bind with players name and image.

image

I hope this post is useful. Thanks for reading.

How to launch Call Task from Secondary Tile in Windows Phone 7

Recently I got a mail from one of the reader. She asked; How could be launch Call Task from Secondary Tile? In this post I am going to show the way to do that. Before you go ahead with this post, I strongly recommend reading below three posts for more on Live Tiles and Call Task.

Video on How to work with Live Tiles in Windows Phone 7

Live Tiles in Windows Phone 7.5 or Mango phone

Code to make call in Windows Phone 7

Delete Secondary Tiles in Windows Phone 7.5 or Mango Phone

Idea of launching Call Task from Secondary Tiles is very simple.

  1. On clicking of Secondary Tile user will get navigated to a blank page. Let us call that page as Page1.XAML
  2. On NavigatedTo method of the Page1.Xaml, we will instantiate Call Task and show call panel to user.

Let us create Secondary Tile on MainPage.Xaml. I have put a button on MainPage and on click event of the button Secondary Tile will get created.


private void btnCreateSecondaryTiles_Click(object sender, RoutedEventArgs e)
{

var newTile = new StandardTileData()
{
Title = "Blogs Update",
BackgroundImage = new Uri("background.png", UriKind.Relative),
Count = 42,
};
var uri = "/Page1.xaml?state=Live Tile";
ShellTile.Create(new Uri(uri, UriKind.Relative), newTile);



}

If you notice in above code, I have set navigation to Page1.Xaml. Now on onNavigatedTo() method we need to write code to launch Call Task.


protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//base.OnNavigatedTo(e);
PhoneCallTask callTask = new PhoneCallTask();
callTask.PhoneNumber = "999999";
callTask.DisplayName = "debugMode";
callTask.Show();


}


 

On running you should be getting below output

image

I hope this post was useful. Thanks for reading.

Message Dialog Control in Windows 8 HTML JavaScript Metro Application

In this post, I will discuss how to work with Message Dialog in Windows 8 Metro application. I will use WinJS to create message dialog. Message dialog look like below,

image

Message Dialog is part of UI surfaces in Windows 8. There are four types of UI surfaces in Windows 8.

  1. App Bar
  2. Context Menu
  3. Message Dialog
  4. Fly Out

We are going to popup a message dialog box on click event of a button. Let us put a button and output span on default.html as below,

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DataBindingSample</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<!-- DataBindingSample references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<h2>metro message dialog  demo</h2>
<br />
<button id="btnShowMessage" > Want to Make a call </button>
<br />
<span id="resultDiv" />
</body>
</html>

We are going to display result out of user selection in message dialog box on the span resultDiv.

Message Dialog can be created by making a call to below function.

clip_image002

Windows.UI.Popups.MessageDialog function is overloaded. It either takes content or content and title both as input parameters.

Message dialog can be created with content and title as below,

clip_image004

Once we have created message dialog, we need to add commands to that. Command can be added as below,

clip_image006

We can add as many commands as we want in the same way. After adding all the commands we need to start operation as below,

clip_image008

By putting all codes together code behind will have below codes.

Default.js


(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);

WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

// TODO: startup code here
//adding click event to button
var buttonToPopup = document.getElementById('btnShowMessage');
buttonToPopup.addEventListener('click', function()
{
ShowPopUp();
});
}
}

function ShowPopUp() {

var resultDiv = document.getElementById('resultDiv');

//Creating message dialog box
var messagedialogpopup = new Windows.UI.Popups.MessageDialog
('Allow to use your location ',
'Location Application');


// adding command to message dialog box

messagedialogpopup.commands.append(new Windows.UI.Popups.UICommand('yes', function () {
//calling callback function for Yes command
resultDiv.innerHTML = "<h2>Yes</h2>";
}));

messagedialogpopup.commands.append(new Windows.UI.Popups.UICommand('no', function () {
//calling callback function for No command

resultDiv.innerHTML = "<h2>no</h2>";
}));


messagedialogpopup.commands.append(new Windows.UI.Popups.UICommand('Yes but with limitd data', function () {
//calling callback function for Yes but with limited data command

resultDiv.innerHTML = "<h2>Yes but with limited data</h2>";
}));

messagedialogpopup.showAsync().operation.start();



}

WinJS.Application.start();
})();


On running you should be getting below message dialog on click event of the button.

clip_image002[6]

I hope this post is useful. Thanks for reading

DatePicker control in Windows 8 HTML5 Metro JavaScript Application

In this post I will show you, how to work with DatePicker control in HTML Metro App. DatePicker controls comes as part of WinJS.

To use DatePicker control very first let us create a blank application

clip_image002

Right click and open project in Expression Blend.

clip_image003

Choose Date Picker from Assets and put it below Body tag.

clip_image005

You can see in live DOM tab that Date Picker control is made up of different HTML elements. There are three Select tag are being used to create Date Picker tag.

clip_image007

After dragging Date Picker control on the DOM, you can see HTML generated as below,

clip_image009

To set the basic properties you need to select div contains Date Picker control and then click Attributes tab in Properties window.

clip_image010

After setting value of maxYear and minYear , when you switch to HTML view , you will notice added attribute in Date Picker control as below,

clip_image011

You may notice in above HTML that in Head section of the HTML a WinJS function is being called. This function is responsible for processing all the WinJS controls. It is very much possible to move this WinJS function call from HTML page to JS page as below,

clip_image013

At this point if on running of the application, you should be getting Date Picker control on the app page. Let us move ahead and read the selected value from the Date Picker control. For that give an ID to Date Picker control div and read it on js file using standard java script function.

clip_image015

After fetching as Win Control, next you need to attach event handler to this.

clip_image017

Next if you want to fetch current date selected in Date Picker you can fetch as below,

clip_image019

In this way you can display selected date in result div. For your convenience full source code for default.js is given below,

Default.js


(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);

WinJS.Application.onmainwindowactivated = function (e) {

var result = document.getElementById("Result");
WinJS.UI.processAll().then(function () {

var dateFilterControl = document.getElementById("DatePickerDiv").winControl;
dateFilterControl.addEventListener("change", function () {
var month = dateFilterControl.current;
result.innerHTML = month;



});

});
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
// TODO: startup code here
}
}

WinJS.Application.start();
})();


Default.html is as below,

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AppBarSample</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<!-- AppBarSample references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
<script src="/winjs/js/ui.js" type="text/javascript"></script>
<script src="/winjs/js/controls.js" type="text/javascript"></script>

</head>
<body>
<h1>Date Picker Demo</h1>
<div id="DatePickerDiv" data-win-control="WinJS.UI.DatePicker"
data-win-options="{disabled:false,maxYear:2020,minYear:2001}">
</div>
<div id="Result">

</div>
</body>
</html>


I hope this post is useful. Thanks for reading

Create Hosted Service using Windows Azure Management API

In this post I will discuss, how could we create Hosted Service in Windows Azure using Windows Azure Management API?

To create Hosted Service you need to perform POST operation on the below URI. You need to change subscription id with your subscription Id.

https://management.core.windows.net/<subscription-id>/services/hostedservices

While making the request, Request Header must contain information as below,

image

Request Body must contain XML as body. XML elements should be in the same order as mentioned below.


<?xml version="1.0" encoding="utf-8"?>
<CreateHostedService xmlns="http://schemas.microsoft.com/windowsazure">
<ServiceName>service-name</ServiceName>
<Label>base64-encoded-service-label</Label>
<Description>description</Description>
<Location>location</Location>
<AffinityGroup>affinity-group</AffinityGroup>
</CreateHostedService>

On successful creation of the hosted service status code 201 will get returned. Response contains no body.

For more details read MSDN reference here

To create hosted service I have created below function. To create service you need to pass below parameters

  1. Service Name : This is name of the service you want to create
  2. Label : This is service label
  3. Description : This is service description
  4. Location : This is data center in which service will get deployed


public  String CreateHostedService(String subscriptionId, String serviceName, String label, String description, String location)
{


XDocument payload = CreatePayloadToCreateService(serviceName, label, description, location);
string operationUri = "https://management.core.windows.net/"+subscriptionId+"/services/hostedservices";
String requestId = Invoke(payload,operationUri);
return requestId;
}



In above function I am calling two different functions.

  1. One method to create payload. This payload will be passed as XML to perform POST operation
  2. Invoke method will perform actual HTTP request to Windows Azure portal.

Below function will create payload and return as XML. LINQ to XML is being used to create payload XML.


private XDocument CreatePayloadToCreateService(String serviceName, String label,String description, String location)
{
String base64LabelName = ConvertToBase64String(label);
XNamespace wa = "http://schemas.microsoft.com/windowsazure";
XElement xServiceName = new XElement(wa + "ServiceName", serviceName);
XElement xLabel = new XElement(wa + "Label", base64LabelName);
XElement xDescription = new XElement(wa + "Description", description);
XElement xLocation = new XElement(wa + "Location", location);
//XElement xAffinityGroup = new XElement(wa + "AffinityGroup", affinityGroup);

XElement createHostedService = new XElement(wa + "CreateHostedService");
createHostedService.Add(xServiceName);
createHostedService.Add(xLabel);
createHostedService.Add(xDescription);
createHostedService.Add(xLocation);
//createHostedService.Add(xAffinityGroup);

XDocument payload = new XDocument();
payload.Add(createHostedService);

payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");

return payload;
}


Other method used in CreateHosetdService function was Invoke.This function is used to make HTTP request to Azure portal.


public String Invoke(XDocument payload,string operationUri)
{



HttpWebRequest httpWebRequest = Helper.CreateHttpWebRequest(new Uri(operationUri), "POST");
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
using (StreamWriter streamWriter =
new StreamWriter(requestStream,
System.Text.UTF8Encoding.UTF8))
{
payload.Save(streamWriter,
SaveOptions.DisableFormatting);
}
}

String requestId;
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
{
requestId = response.Headers["x-ms-request-id"];
}

return requestId;
}


In this way you can create hosted service. I hope this post is useful. Thanks for reading.