Share Text in between Windows 8 Metro Application using Share Contract

Two Metro applications can shared the content between them using Share Charm. Content can be as simple as text or may be image or a file. In content sharing, the application that shares content is called as Source Application and the application that receives content is called as Target Application. Source Application and Target Application need to declare the type of content; they are intent to share in a Declaration.

Declaration can be configured in the package.appmanifest file. Click on package.appmanifest file and then select Declaration tab. From the Available Declarations drop down select Share target and check SupportedAnyFile Type in Supported File Types. See the image below.

image

Source Application

After configuring the declaration we need to write the code to share relevant text. Let us put a button and click event of that button we will share the text.

image

In code behind attach click event to button and call bellow function

image

Function to share text is as following. User can share the text from the Share Charm. Note that in the code below, we have explicitly displayed the Share charm by calling function showShareUI.


function ShowandShareContract() {

Windows.ApplicationModel.DataTransfer.DataTransferManager.showShareUI();
 var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
 dataTransferManager.addEventListener("datarequested", function (e) {
 var request = e.request;
 request.data.properties.title = "Debugmode";
 request.data.properties.description = "Debugmode Share App";
 request.data.setText("Hello from DebugMode App");
 });
 }

The actual data sharing happens in the datarequested event handler. We are sharing the text “Hello from DebugMode App “

Target Application

Now let us create an application, which can consume the shared text. An application can be launched in multiple ways; we need to first check whether the application was launched as Share Target or not before accepting any data.

image

We also need to check whether shared operation is containing text or not. That can be check as following

image

Below is the code required to read the text shared and display in an output div.

 if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.shareTarget) {

 var shareOperation = args.detail.shareOperation;
 if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.text)) {
 var SharedText = " Title : " + shareOperation.data.properties.title;
 SharedText = SharedText + " Description : " + shareOperation.data.properties.description;
 document.getElementById("outputDiv").innerText = SharedText;

 }

}

In this way text can be shared between source application and target application using shared contracts. When you run the source application, you will get a ShareContent button. On clicking of the button Share Charm will get displayed. You will get list of all applications can act as Target Application. For example Mail application can also act as Target Application.

image

Let us choose target application we created. Click on ShareContreactTarget application. You can see two applications can run side by side and text from source application is displayed in output div of target application.

image

In this way we can share Text between two metro applications. I hope you find this post useful. Thanks for reading.

Netflix Movie Explorer a Metro Application: Creating Step by Step

Download source code of this article from here

In this article we will follow step by step approach to create Netflix Movie Explorer Metro Application. We will use HTML and WinJS to create this application. See the video to understand expected behavior of the application.

Some of the features of application are as following

  • Browse movies from Netflix
  • Rate the Movies
  • Browse movies in Semantic views
  • Share the Rating of a particular movie with social media or via mail

To get it started, launch Visual Studio and create a new project by choosing Blank App Project template from Windows Metro Style tab. You need VS12 to create this application.

image

After creating project in default.html change “content goes here “with following

clip_image001

After that follow the steps as below,

Step 1: Create Data Source

Very first we need to create data source by reading JSON data from OData feed of Netflix movie database. That can be done using WinJS.xhr function

image

In above code snippet, we are performing following tasks

  • Making a call to Netflix OData using WinJS .xhr function
  • As input parameter to xhr function, we are passing exact url of OData Endpoint.
  • We are applying projection and providing JSON format information in URL itself.
  • Once JSON data is fetched form Netflix server data is being parsed and pushed as individual items in the WinJS list.

After fetching, data is being parsed using JSON Parser and individual items are pushed to movieArray. movieArray is defined as following

image

Step 2: Create ListView

After creating data source we need put WinJS ListView control on the page.

image

A HTML div can be converted to WinJS ListView by setting data-win-control attribute to WinJS.UI.ListView. Other options can be set like layout of the ListView. In this case we have set it to GridLayout, so data will be displayed horizontally. ListView needs data source to display data. Data source can be set either in HTML or in code behind. Let us set data source of movieListView to the movieArray.

image

Make sure that you are setting data source of ListView after the WinJS.xhr function call. At this point of time if you go ahead and run the application, you should be getting following output.

image

Step 3: Create ListView Template

In above output, data is in raw form. To make data more immersive and to show the way we want, we need to create template out of data. After creating template, it needs to be set as attribute of ListView. Template can be created as following

image

Template can be created by setting data-win-control attribute of HTML div as WinJS.Binding.Template . Inside div element

  • Binding image to Picture property of WinJS List or Array
  • Binding inner text of h4 element to Title property of WinJS List or Array

Once Template is created, it needs to be attached to the ListView. After attaching Template, ListView will be as following

image

No go ahead and run the application, you should be getting following shape of the application

image

Before we move ahead, let us put some CSS on ListView to make it more immersive

image

After applying styles on List View, your application should be in following shape.

image

Step 4: Grouping of DataSource

Next we want to group the movies as per first character of their title. For that create group functions as following.

image

After creating grouped functions, we need to create grouped item list and set it as itemDataSource of List View. Modify setting of ListView data source as following

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 5: Creating Header Template

Above we can see the header data is in raw form. So to make header information more immersive, you need to create template for header and then attach that to ListView

A header template can be created in same way as of item template. Header template is created as following

image

After creating Header Template, we need to attach this to ListView. So ListView will be modified as following

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 6: Adding Semantic Zoom

Next we need to add sematic zoom to the ListView. For that very first let us create a Semantic Zoom Template. We want to display movies with first letter of title in semantic zoom view.

image

After creating Semantic Zoom View template, we need to add a SemanticZoom WinJS control. Inside the Semantic Zoom control we need to put ListView (created in previous steps) and a Semantic Zoom View. We can put that as following.

image

After adding Semantic Zoom view we need to set data source of it. This can be set as following.

image

Last work we need to do in Semantiz Zoom is to apply styles.

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

image

Step 7: Adding Output DIV

Now we need to add code to add output div. When user will select a particular movie detail of that movie will be displayed in the output div for rating.

image

And in code behind on the touch of a particular ListView item, we need to display that information in output div. For that add the following code in code behind

image

In above code snippet

  • Iteminvoked event is attached to the ListView
  • When item is invoked then itemPromise function is being called with parameter invokedItem
  • On the invokeditem data we can fetch attributes of ListView items
  • In last set the vales of HTML elements from selected items data.

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 8: Adding Rating control

To allow user for Rating, let us go ahead and add a WinJS Rating control. Rating control can be added as following

image

We can create a Rating control by setting data-win-control attribute of a div as WinJS.UI.Rating. Other data options like maxRating and averageRating can be set in data-win-options attribute.

After adding Rating control, we need to write code to allow users to perform rating.

image

Let us go ahead and run the application. At this point shape of the application should be as following

image

Step 9: Adding Code to Share Contract

We want our user should able to share the rating of movie on other applications like Mail, Twitter, Facebook. For that we will have to use ShareContract.

image

In above code we are getting the request and setting the title and description in data property. After that creating text to share and setting it in the data request. Above is the code to simple text sharing via ShareContract feature of Windows 8. Once we have share function is ready, we need to get the current view of application using DataTransferManager.getForCurrentView () and attach and event handler datarequested on same. When datarequested event will be fired ShowandShareContract function (created above) will be called and user will able to share using Share Charm.

image

Put above code just before ProcessAll() function and do not forget to declare following variable globally

image

Let us go ahead and run the application. At this point shape of the application should be as following. This is our final application.

image

In this application user can browse the movies, rate a particular movie and then share the rating with the friends on social media or mail.

Conclusion

In this post we learnt to create a Metro Application from scratch. Even though you can download source code of this article from here , I am sharing the codes below . Feel free to use them as you required.

default.html


<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <title>testdemo</title>

<!-- WinJS references -->
 <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
 <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
 <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>

<!-- testdemo references -->
 <link href="/css/default.css" rel="stylesheet" />
 <script src="/js/default.js"></script>
</head>
<body>
 <h1>Netflix Movie Application</h1>
 <div id="moviesTemplate"
 data-win-control="WinJS.Binding.Template">
 <div style="width: 150px; height: 130px;">
 <img src="#" style="width: 100px; height: 100px;"
 data-win-bind="alt: title; src: picture" />
 <div>
 <h4 data-win-bind="innerText:title"></h4>
 </div>
 </div>
 </div>

<div id="headerTemplate"
 data-win-control="WinJS.Binding.Template"
 style="display: none">
 <div class="simpleHeaderItem">
 <h1 data-win-bind="innerText: title1"></h1>
 </div>
 </div>

<div id="semanticZoomTemplate" data-win-control="WinJS.Binding.Template"
 style="display: none">
 <div class="semanticZoomItem">
 <h1 class="semanticZoomItem-Text"
 data-win-bind="innerText: title1">
 </h1>
 </div>
 </div>
 <div id="semanticZoomDiv" data-win-control="WinJS.UI.SemanticZoom">
 <div id="movieListView"
 data-win-control="WinJS.UI.ListView"
 data-win-options="{itemTemplate:moviesTemplate,
 groupHeaderTemplate: headerTemplate
 ,layout: {type: WinJS.UI.GridLayout} }">
 </div>
 <div id="zoomedOutListView"
 data-win-control="WinJS.UI.ListView"
 data-win-options="{itemTemplate: semanticZoomTemplate,
 selectionMode: 'none',
 tapBehavior: 'invoke',
 swipeBehavior: 'none' }">

</div>
 </div>
 <table>
 <tr>
 <td>
 <img id="selectedPlayerImg"
 style="width:250px;height:250px;"/>
 </td>
 <td>
 <h3>You are rating movie</h3><br />
 <span id="selectedPlayer"></span> <br />
 <span id="ratingPlayer"></span> <br />

<div id="ratingcontrol"
 data-win-control="WinJS.UI.Rating"
 data-win-options="{maxRating:10,avrageRating:4}" />

 </td>
 </tr>
</table>

&nbsp;

</body>
</html>

default.js


// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
 "use strict";

 var app = WinJS.Application;
 var activation = Windows.ApplicationModel.Activation;
 WinJS.strictProcessing();
 var movieArray = new WinJS.Binding.List();
 var dataTransferManager;
 var movieName;
 var selectRating;
 app.onactivated = function (args) {

 if (args.detail.kind === activation.ActivationKind.launch) {
 if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
 // TODO: This application has been newly launched. Initialize
 // your application here.
 } else {
 // TODO: This application has been reactivated from suspension.
 // Restore application state here.
 }

 dataTransferManager = Windows.ApplicationModel.
 DataTransfer.
 DataTransferManager.getForCurrentView();
 dataTransferManager.addEventListener("datarequested", ShowandShareContract);
 args.setPromise(WinJS.UI.processAll());

 WinJS.xhr({
 url: "http://odata.netflix.com/Catalog/Titles" +
 "?$format=json&$select=ShortName,BoxArt&$top=300"
 }).then(function (xhr) {
 var movies = JSON.parse(xhr.response).d;
 movies.forEach(function (i) {
 movieArray.push({
 title: i.ShortName,
 picture: i.BoxArt.MediumUrl
 });
 });
 });

var lstMovies = document.getElementById("movieListView").winControl;
 var groupedItemsList = movieArray.createGrouped(getGroupKey, getGroupData, compareGroups);
 lstMovies.itemDataSource = groupedItemsList.dataSource;
 lstMovies.groupDataSource = groupedItemsList.groups.dataSource;
 var lstMoviesZoom = document.getElementById("zoomedOutListView").winControl;
 lstMoviesZoom.itemDataSource = groupedItemsList.groups.dataSource;
 lstMovies.addEventListener("iteminvoked", function (eventObject) {
 eventObject.detail.itemPromise.then(function (invokedItem) {
 var selecteplayer = document.getElementById('selectedPlayer');
 selecteplayer.innerHTML = "<h2>" + invokedItem.data.title + "</h2>";
 movieName = invokedItem.data.title;

var selecteplayerImg = document.getElementById('selectedPlayerImg');
 selecteplayerImg.src = invokedItem.data.picture;

var ratingcontrolc = document.getElementById("ratingcontrol").winControl;
 ratingcontrolc.addEventListener("change", function () {
 selectRating = ratingcontrolc.userRating;
 document.getElementById('ratingPlayer').innerHTML = "<h3> as "
 + selectRating +
 " on scale of 10 <h3>";

});

});
 }, false);

&nbsp;
 }
 };

function compareGroups(left, right) {
 return left.charCodeAt(0) - right.charCodeAt(0);
 }

function getGroupKey(dataItem) {
 return dataItem.title.toUpperCase().charAt(0);
 }

function getGroupData(dataItem) {
 return {
 title1: dataItem.title.toUpperCase().charAt(0)
 };
 }

function ShowandShareContract(e) {

var request = e.request;
 request.data.properties.title = "Netflix Movie Explorer Application";
 request.data.properties.description = "Sharing from Netflix Movie Explorer Application";
 var textToShare = movieName + " has been rated " + selectRating + " out of 10 ";
 request.data.setText(textToShare);

}

app.oncheckpoint = function (args) {

 };

app.start();
})();

default.css

body {
}

@media screen and (-ms-view-state: fullscreen-landscape) {
}

@media screen and (-ms-view-state: filled) {
}

@media screen and (-ms-view-state: snapped) {
}

@media screen and (-ms-view-state: fullscreen-portrait) {
}
.win-listview
 {
 height: 500px;
 width: auto;
 border: 1px solid gray;
 }

.win-listview .win-container {
 margin: 10px;
 }
 .win-listview .win-container:hover {
 background-color: red;
 border-color: red;
 }

.semanticZoomItem
{
 width: 130px;
 height: 130px;
 background-color: rgba(38, 160, 218, 1.0);
}

.semanticZoomItem .semanticZoomItem-Text
 {
 padding: 10px;
 line-height: 150px;
 white-space: nowrap;
 color: white;
 }

&nbsp;

&nbsp;

I hope you find this post useful. Thanks for reading

Consuming WCF SOAP Service in Windows 8 Metro Application

In this post we will consume WCF SOAP Service in C#/XAML based Metro Application. This is level 100 post showing basic steps to create simple WCF Service and consume that in Metro Application.

Very first let us create a WCF Service using VS2012. Form File menu create a new project by choosing WCF Service Application project template from WCF tab.

image

Remove all the default code from IService1.cs and replace it with following code. In below service contract we are going to return a simple greeting message. From client a name as string will be input to the service and service will return a greeting message as string.

IService1.cs


using System.ServiceModel;
namespace ServiceToConsumeinMetro
{
 [ServiceContract]
 public interface IService1
 {

[OperationContract]
 string GreetingMessage(string name);

 }

}

Service is implemented as following. It is concatenating two string and returning it .

Service1.svc.cs


namespace ServiceToConsumeinMetro
{

 public class Service1 : IService1
 {
 public string GreetingMessage(string name)
 {
 return "Welcome to Metro Word " + name;
 }
 }
}

We will go with the default binding and will not configure anything in Web.Config. Leave Web.config as it is and press F5 to run and host created WCF service in local server. On successful running in your browser you should have below output.

image

Now let us create a Metro Application to consume this service. From File menu in VS 2012 choose Blank App project template from Windows Metro Style tab.

image

Next let us design the page. On the page we are going to put one TextBox, One Button and one TextBlock. User will enter Name in textbox and on the click event of the button service will be called. Returned output from service will be displayed in the textblock. Xaml is as following

MainPage.xaml


<Page
 x:Class="App1.MainPage"
 IsTabStop="false"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="using:App1"
 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="200" />
 <RowDefinition Height="200" />
 <RowDefinition Height="200" />
 </Grid.RowDefinitions>
 <TextBox x:Name="txtName" Margin="286,25,583,113" />
 <Button x:Name="btnCallService" Content="Enter Name above and touch to call service" Height="100" Width="364" Grid.Row="1" Margin="367,10,0,90" Click="btnCallService_Click_1"/>
 <TextBlock x:Name="textResult" Grid.Row="2" FontSize="30" FontWeight="Bold" />
 </Grid>
</Page>

Next we need to add Service Reference in the Metro project. For that right click on Metro Application project Reference tab and select Add Service Reference

image

Add the reference as following. My metro application name is App1. If your Metro application name is XYZ then you will be adding XYZ.ServiceReference1 provided you have not changed reference name while adding it.

image

In Metro word everything is asynchronous. So we need to make async call to service. When you add reference automatically visual studio creates async function for you.

image

We can call this function from service as following

image

If you notice we have put await keyword before making a call to service. Since service is called in await manner so the function inside which we are calling service must be async. On click event of the button service can be called as following

image

Combining all discussion together code behind will look like as following

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using App1.ServiceReference1;

namespace App1
{

 public sealed partial class MainPage : Page
 {
 public MainPage()
 {
 this.InitializeComponent();
 }

protected override void OnNavigatedTo(NavigationEventArgs e)
 {
 }

private async void btnCallService_Click_1(object sender, RoutedEventArgs e)
 {
 Service1Client proxy = new Service1Client();
 string result = await proxy.GreetingMessageAsync(txtName.Text);
 textResult.Text = result;
 }
 }
}

On running you should be getting output as following

image

I am sorry for poor UI experience but any way making UI immersive was not purpose of this post. I hope now you know basic steps to consume WCF SOAP service in metro application.

Migrate HTML5 WinJS Metro Application project to VS2012

In this post we will migrate a Metro Project created in HTML5 and WinJS from VS11 to VS2012 RC.

Recently I upgraded my system to Windows 8 Release Preview. After upgrading Windows, I migrated VS to VS2012 RC. After successful installation of VS2012, I tried opening a HTML5 + WinJS project created in VS11. When I tried to build that project, I got below exception.

image

Exception was in file C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets

To remove this error what all you need to do is go to solution and remove old reference of Microsoft.WinJS

image

And then again try to rebuild the solution. You should not be getting any build error. Though after than if you run the project you will be getting errors like

image

This error implies that reference has been missing. To solve this we need to add new reference in the project. Add Windows Library for JavaScript 1.0 RC reference in the project. image

After adding reference you need to change the references on HTML. Currently your reference may look like as following

clip_image002

You need to change Microsoft.WinJS.0.6 to Microsoft.WinJS.1.0.RC. After changing references should look like as following

clip_image004

No go ahead and run the project. You should be not getting any error. In this way you can migrate HTML5 WinJS Metro project to VS2012.

I hope this post is useful. Thanks for reading.

Presented in Mindcrcaker MVP Summit 2012

Second Mindcrcaker MVP summit held in Delhi from 6th April 2011 to 8th April 2011.Mindcracker MVP summit is yearly event hosted by http://www.c-sharpcorner.com/ to facilitate their MVP and one day regress technical sessions open for any aspired learner.

Find more details about summit here

Find summit Pics here

Some of the highlight of this event was as following,

  • Mindcrcaker launched all new version of http://www.c-sharpcorner.com/
  • Mindcracker reached 2.2 Million users.
  • Mindcracker announced new Mindcracker User Groups
  • Awarded Mindcracker MVP

I was awarded as Mindcracker Member of the Year in Mindcracker MVP Summit 2012

In this event, I got opportunity to present on “Introducing Metro Application Development using HTML and JavaScript”. I tried to give my session more as demo oriented session.

If you want PPT and demo source code from the session then send me a mail at dhananjay.25july@gmail.com with Mindcracker in subject line.

Isolated Storage Helper For C# and XAML based Metro Application

This post and helper class is based on work of Jamie Thomson . I thank him lot for that.

Why to use Metro Application Isolated Storage Helper?

This helper class helps you to perform Read,Write and Delete of structured data in Isolated storage folders.

How to use this?

Download Metro Application Isolated Storage Helper from here

You have a class Student



public class Student
    {
        public string Name { get; set; }
        public int RollNumber { get; set; }
    }


You want to save object of Student then you can save it in Local Folder of isolated storage as below


Student objStudent = new Student { Name = "DJ ", RollNumber = 1 };
            var objectStorageHelper = new StorageHelper<Student>(StorageType.Local);            
            objectStorageHelper.SaveASync(objStudent,"abc");



And you can read back Student from isolated storage as below



public async void ReadData()
        {            
            var objectStorageHelper = new StorageHelper<Student>(StorageType.Local);           
            Student objStudent = await objectStorageHelper.LoadASync("abc");
            
        }


Abc is name of the file. If you want to store List<Student> then you can do that as following,



List<Student> lstStudent = new List<Student>()
                                        {new Student { Name = "DJ ", RollNumber = 1 },
                                         new Student { Name = "debugmode", RollNumber = 2 }
                                        };

            var objectStorageHelper = new StorageHelper<List<Student>>(StorageType.Local);
            objectStorageHelper.SaveASync(lstStudent, "abc");



You can read List<Student> from local folder of isolated storage as following



public async void ReadData()
        {            
            var objectStorageHelper = new StorageHelper<List<Student>>(StorageType.Local);           
            List<Student> lstStudent = await objectStorageHelper.LoadASync("abc");
            foreach (var r in lstStudent)
            {
                string n = r.Name;
            }
        }




Background

I was working with storing and retrieving structured data in Isolated Storage. While Binging I came across nicely written Generic Object Storage Helper for WinRT . This is written by Jamie Thomson . When I tried using this utility I came across an exception. I tried to store object of Student as following.


private void btnSaveData_Click_1(object sender, RoutedEventArgs e)
        {
            Student objStudent = new Student { Name = "Hary ", RollNumber = 1 };
            var objectStorageHelper = new ObjectStorageHelper<Student>(StorageType.Local);            
            objectStorageHelper.SaveASync(objStudent);
        }

But while running the program I came across exception as below,

image

After inspecting I found that library is written in Developer Preview and few API has been changed in Consumer Preview. Thankfully Jamie Thomson has put the source code on the CodePlex also. A big thank to him for the same. Rather than adding DLL and working with API, I copied and pasted code in my program and started to debug that.

First changes in API from DP to CP was that there were no TryMoveToRecycleBin in StorageDeleteOption enum

image

Now StorageDeleteOption enum contains only two values as below,

image

So I replaced above line of code as below,

image

The Second changes from DP to CP I found was removal of OpenWrite and OpenRead method from IRandomAcccessStream interface

image

Where readStream is defined as below,

image

And OpenWrite has been replaced with AsStreamForWrite

image

I have modified code to explicitly take filename as well. After these changes have been done Code was ready to be used in Consumer Preview. Updated helper class code is as following,

 



     public enum StorageType
    {
        Roaming, Local, Temporary
    }

    public class ObjectStorageHelper<T>
    {
        private ApplicationData appData = Windows.Storage.ApplicationData.Current;
        private XmlSerializer serializer;
        private StorageType storageType;

        
        public ObjectStorageHelper(StorageType StorageType)
        {
            serializer = new XmlSerializer(typeof(T));
            storageType = StorageType;
        }

        public async void DeleteASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFolder folder = GetFolder(storageType);

                var file = await GetFileIfExistsAsync(folder, FileName);
                if (file != null)
                {
                    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async void SaveASync(T Obj,string FileName)
        {

            FileName = FileName + ".xml";
            try
            {
                if (Obj != null)
                {
                    StorageFile file = null;
                    StorageFolder folder = GetFolder(storageType);
                    file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

                    IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);
                    Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;
                    serializer.Serialize(outStream, Obj);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<T> LoadASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFile file = null;
                StorageFolder folder = GetFolder(storageType);
                file = await folder.GetFileAsync(FileName);
                IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
                Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
                return (T)serializer.Deserialize(inStream);
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default 
                return default(T);
                //throw;
            }
            catch (Exception)
                 {
                //Unable to load contents of file
                throw;
            }
        }

        private StorageFolder GetFolder(StorageType storageType)
        {
            StorageFolder folder;
            switch (storageType)
            {
                case StorageType.Roaming:
                    folder = appData.RoamingFolder;
                    break;
                case StorageType.Local:
                    folder = appData.LocalFolder;
                    break;
                case StorageType.Temporary:
                    folder = appData.TemporaryFolder;
                    break;
                default:
                    throw new Exception(String.Format("Unknown StorageType: {0}", storageType));
            }
            return folder;
        }

        private async Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)
        {
            try
            {
                return await folder.GetFileAsync(fileName);

            }
            catch
            {
                return null;
            }
 }
    }



In this way you can work with structured data in XAML based Metro Application for Windows 8. I hope this post is useful. Thanks for reading.

Live Tiles in XAML based Windows 8 Metro Application

In this post we will discuss Live Tiles in XAML based Windows 8 Metro Application. We will see

  • Updating Live Tiles
  • Creating queue of information to update Live Tiles

What is Live Tile?

Tiles are the entry point for the application. You will find TILES for all applications installed on your machine at the start screen. These Tiles are termed as Live if we update the content of the Tiles on basis of some business rules. So when user sees the Tiles, She gets some vital information from the application. Below are the Tiles of some of the installed applications on my system.

 If you see weather application there is weather information about Seattle on the tiles itself. So to know weather information of Seattle, you do not need to open the application. You can get information by just seeing the Tile of the weather application. This information is live and will change as the weather of Seattle will be changed.

You can update information on Tiles in Four ways

  1. From Push Notification Service
  2. Locally
  3. Scheduled
  4. Periodic

In this post we are focusing on updating Tiles locally. To start with add below namespaces

image

You can update Tile using below line of code.

image

You can see that Update method takes TileNotification as input parameter. You need to pass content to update on Tile as XML to TileNotification. Tile XML can be created using below code.

image

There are many templates type available for TileTemplate. We are using TileWideText01 type (see 1st highlighted text).

There are 44 TileTemplateType available. You need to choose one as your requirement. In following post I will go in details of each TileTemplateType.

Each Tile Template Type is a XML document. We can update a particular element by selecting element with the tag name. We are doing this in second line of code. In last line we are setting the information we want to update on the Tile. You can set is dynamically according to your business requirement.

So putting all pieces of codes together on a click event of a Button, a Tile can be updated as following.


private void btnSendLiveTiles_Click_1(object sender, RoutedEventArgs e)
{
XmlDocument tileXml = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);

XmlElement textElement = (XmlElement)tileXml.
GetElementsByTagName("text")[0];
textElement.AppendChild(
tileXml.CreateTextNode
("Hey This my Text Updated on Tile"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml));
}

Before you run and see that whether Tiles has been updated or not. You need to set Wide Logo of the application. Text on live Tiles appears only when you have set the Wide Logo. Wide Logo need to be 310×150 Pixels. To set Wide Logo from solution explorer click on Package.appmanifest file and the set the Wide Logo.

image

I have set green rectangle of size 310×150 as Wide Logo. Now go ahead and run the application. After clicking on the button close the application and go to start screen. On start screen you can see that Tile text has been updated with the text we provided.

image

You can update Tile multiple times. For that you need to enable notification queue and you can have five information in the queue to be updated on the Tile. If there are more than five information available then recent five would be updated.

image

On click event of a button you can update Tiles with three different information as following.


private void btnSendLiveTiles_Click_1(object sender, RoutedEventArgs e)
{

TileUpdateManager.
CreateTileUpdaterForApplication().
EnableNotificationQueue(true);

XmlDocument tileXml = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);
XmlElement textElement = (XmlElement)tileXml.
GetElementsByTagName("text")[0];
textElement.AppendChild(
tileXml.CreateTextNode
("Updating Tile1"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml));

XmlDocument tileXml1 = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);

XmlElement textElement1 = (XmlElement)tileXml1.
GetElementsByTagName("text")[0];
textElement1.AppendChild(
tileXml1.CreateTextNode
("Updating Tile2"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml1));

XmlDocument tileXml2 = TileUpdateManager.
GetTemplateContent
(TileTemplateType.TileWideText01);

XmlElement textElement2 = (XmlElement)tileXml2.
GetElementsByTagName("text")[0];
textElement2.AppendChild(
tileXml2.CreateTextNode
("Updating Tile3"));

TileUpdateManager.CreateTileUpdaterForApplication()
.Update(new TileNotification(tileXml2));
}

You can have three information in queue getting updated on Tiles. In this way you can work with Live Tiles in XAML based window8 metro application. I hope this post is useful. Thanks for reading.

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.

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