Solved Exception in Passing Relative URI to Windows Runtime

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

 

image

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

 

image

 

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

image

 

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

 

image

 

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

 

image

 

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

What is Namespace in WinJS

Let us first try to understand, why we need Namespace? I will try to explain you with an example, let us suppose you have a function named GreetingMessage in JS file named Library.js

image

Now you need to use this function on default.js. When you try to call that function from other js file , you get following exception.

 

image

Essentially, you cannot access a function or variable outside its scope. Namespace in WinJS library allows you to access a function outside its scope.

  • Namespace allows you to access a function outside its scope.
  • Namespace allows you to use a function in different files along with file it is defined.
  • Namespace helps you to organize your code
  • Any type created in Namespace can be referenced outside the scope of Namespace

Now let us see that how can we define a Namespace in WinJs . You can define Namespace by calling the define function

 

image

There are two parameters need to be passed to create Namespace.

  1. Namespace name is a string
  2. Members of the Namespace as object

You can create a Namespace in Library.js as following,


(function () {

 function GreetingMessage() {

return "Hello from WinJS";

 }

WinJS.Namespace.define("MyLibrary.Function", {
 GreetingMessage: GreetingMessage
 });

})();

There are few points you need to take care here

  • Enclosed all the Namespace definition in self executed function
  • Make sure you are not forgetting the braces at the end.
  • We have defined a function named GreetingMessage
  • We have defined a namespace and function inside that can be accessed as following

image

We have defined a Namespace and now we want to access the function GreetingMessage() on the default.js file. To do this first step you need to do is to refer MyLibrary.js on default.html file. You can refer that as following,

image 
Now you can access GreetingMessage() function on default.js as following ,

var res = MyLibrary.Function.GreetingMessage();
 var output = document.getElementById("output");
 output.innerHTML = res;

In this way by using Namespace, you can access functions and objects in different files and beyond scope of the declaration. I hope you find this post useful. Thanks for reading.

Thanks to Student created Windows 8 App of my Blog

I am very pleased to write here that one student Akrita Agarwal has shown her love to my blog and voluntarily created Windows 8 Application of my blog. I am very touched by this kind effort. You can get that app from App Store from here


Link to download Application from Store


   

This is two column application. You can browse blog posts on selecting a particular blog post from left. There is feature of searching a blog post and about author as well.

   

 

This may not be the best application but we are celebrating proactive step taked by a student to create an Application for Windows Store here.

Thanks to Akrita and their friends.

Presented: Windows 8 App Development for web Developer

I had an opportunity to present on “Windows 8 App Development for Web Developers” at Microsoft Gurgaon on 13th October 2012. It was nice experience presenting in front of more than 125 enthusiast audiences.

I presented on the topic “Windows 8 App Development for Web Developers” and shown demos on

  1. Migrating CSS based HTML Web Application to Windows 8 Application
  2. Understanding App Package
  3. Understanding different capabilities
  4. Understating different Development options
  5. Create “Netflix Movie Explorer” App for Windows Store

Read step by step documentation shown in this demo

Please find below slides from the presentation,

Thanks for attending the presentation.

Create App Package for Windows Store

 

 

In this post we will follow step by step procedure to create app package for Windows Store. Let us suppose you have created a “Hello World “application for Windows Store and want to create an App Package for the same. To create that from menu select PROJECT

 

image

 

From the POROJECT menu, select Store->Create App Package

 

image

 

Next you will get Create App Package wizard. At the point, we do not want to upload package to Windows Store so select the option No and click on Next

 

image

 

In next screen you need to choose Platform for the package. You can create package for

 

  1. 64 bit platform
  2. 32 bit platform
  3. ARM
  4. Neutral platform

 

Subsequently you need to choose whether you want to create package for Release Mode or Debug Mode. Here, I am creating a package for Neutral platform. Select that option and click on Create to create package.

 

image

 

After clicking on create in bottom of Visual Studio you can notice Build Succeeded message. And in next window you will get Success Message with path of the created package.

 

image

 

When you browse to path you will find package has been created to upload.

clip_image001

In this way you can create application package for Windows Store. I hope you find this post useful. Thanks for reading.

 

Dilemma in choosing technology to create App for Windows Store?

 

image

 

When one start creating Applications for Windows Store, the first question come to mind is what technology should be used to create applications. In this post, I am trying to ease that decision to some extent. If you creating application form scratch then as of me you should rely on your existing skills. However for migrating application, you may want to take decision on basis of type of application need to be migrated. Below is the flowchart I would follow while taking decision for technology path

 

image

 

Some of the points you need to keep in mind while deciding are as follows

  • Know your existing skills and decide on that. If you are good at JavaScript and have worked with patterns then you may find WinJS very similar. Whereas if you have created Windows Phone App or WPF applications before then combination of C Sharp and XAML will make more sense to you .

 

  • You need to be more cognizant when deciding for the migration of application. In this scenario rather than relying on your existing skills, you should decide on the factor of what type of application you are going to migrate. For example if you are migrating Windows Phone application then you must choose combination of C Sharp and XAML such that you may reuse codes and functionalities. Imagine if your Windows Phone application is created using patterns like MVVM then you may able to use View and Model View.

 

  • So far what I have experienced that majority of the WinJS controls are created as Metro Controls. So you do not need to write any extra code to make WinJS controls as metro a control. So it may be wise to use HTML and WinJS combination if you skill set contains both web and CSharp XAML.

 

  • If you are creating high end Gaming applications then you may want to consider combination of C++ and XAML

 

  • >If you are a .NET developer and your skill set contains HTML and JavaScript as well. In that case I would recommend C Sharp and XAML. You will find development process very familiar as of .NET development. For example you may create application adhering same patterns like MVVM etc.

 

In this way you can decide on the combinations of technology for the development of applications for Windows Store.

<I hope you find these quick points useful. Thanks for reading.

 

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.

Working with OData and WinJS ListView in Metro Application

In this post we will see how to consume Netflix OData feed in HTML based Metro Application. Movies information will be displayed as following. At the end of this post, we should have output as below,

image

Netflix exposed all movies information as OData and that is publicly available to use. Netflix OData feed of movies are available at following location

http://odata.netflix.com/Catalog/

Essentially we will pull movies information from Netflix and bind it to ListView Control of WinJS. We will start with creating a blank application.

image

In the code behind (default.js) define a variable of type WinJS List.

image

Now we need to fetch the movies detail from Netflix. For this we will use xhr function of WinJS. As the parameter of function, we will have to provide URL of the OData feed.

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.

As of now we do have data with us. Now let us go ahead and create a ListView control. You can create WinJS ListView as following. Put below code on the default.html

clip_image002

In above code we are simply creating a WinJS ListView and setting up some basic attributes like layout and itemTemplate. Now we need to create Item Template. Template is used to format data and controls how data will be displayed. Template can be created as following

image

In above code, we are binding data from the data source to different HTML element controls. At last in code behind we need to set the data source of ListView

image

Before you go ahead and run the application just put some CSS to make ListView more immersive. Put below CSS in default.css

image

Now go ahead and run the application. You should be getting the expected output as following

image

Let us consolidate all the codes from discussion.

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="movieListView"
 data-win-control="WinJS.UI.ListView"
 data-win-options="{itemTemplate : moviesTemplate,
 layout: {type: WinJS.UI.GridLayout} }">
 </div>

</body>
</html>

Code behind will have following codes

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();
 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.
 }
 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;
 lstMovies.itemDataSource = movieArray.dataSource;

 }
 };

app.oncheckpoint = function (args) {

 };

app.start();
})();

And CSS will be as following

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: 100%;
 width: auto;

 }
 .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;
 }

In this way we can work with OData and winJS ListView. 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.