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

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.

How to work with Custom Method in WCF Data Service?

In this post we will see how could we expose a custom method in WCF Data Service? There are three steps involved in doing that

  1. Create a partial class of Entity class and add desired custom method in that.
  2. Add a method with WebGet attribute in service class. This method will make a call to the custom method added in partial entity class.
  3. At the client side call custom method using Execute method

Add Method in Partial Entity class

Create a partial class for entity class. If you are working on School database and your entity class name is SchoolEntities then add one more partial class along with custom method.



namespace WebApplication10
{
public partial class SchoolEntities
{
public string MyCustomMethod()
{
return "Hey I am returned from Custom Method ";
}

}
}

Modifying Service Class

Once you have added custom method in partial entity class, next you need to add method in service class (.svc) with WebGet attribute

image

Above function is creating instance of entity class and making a call to custom method. Custom method will be called at URL baseaddress/service.svc/CustomMethod

Putting all together service class with one custom method will be as below,


using System.Data.Services;
using System.Data.Services.Common;
using System.ServiceModel.Web;

namespace WebApplication10
{
public class WcfDataService1 : DataService<SchoolEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{

config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}


[WebGet]
public string CustomMethod()
{
SchoolEntities entities = new SchoolEntities();
return entities.MyCustomMethod();
}



}
}


Calling custom method at client side

To call custom method at client side you need to make call to Execute method on instance of Entity class. Execute is a generic method and it takes return type of custom method as parameter. In this case return type of custom method is string. Execute method returns IEnuramble. As the parameter to Execute method you need to pass URI od custom method.

image

We can print returned value from custom method from WCF Data Service as below,


using System;
using ConsoleApplication32.ServiceReference1;

namespace ConsoleApplication32
{
class Program
{
static void Main(string[] args)
{
SchoolEntities entities = new SchoolEntities
(new Uri("http://localhost:2580/WcfDataService1.svc/"));
var result = entities.Execute<string>
(new Uri("http://localhost:2580/WcfDataService1.svc/CustomMethod"));

foreach (var r in result)
{
Console.WriteLine(r.ToString());
}
Console.ReadKey(true);


}
}
}


On running of above code you should be getting output as below,

clip_image002

In this way you can work with custom method in WCF Data service. I hope this post is useful. Thanks for reading.

Consuming ODATA in Silverlight 4.0

ODATA is everywhere and so is Silverlight. In this post, I will show, How ODATA can be consumed in Silverlight? “

OData URL

I will be using NorthWind OData URL. You can access that URL from below link.

http://services.odata.org/Northwind/Northwind.svc/

We are going to fetch Customers table from NorthWind DataBase.

Create Project and Add Service Reference

Create a Silverlight project

image

Choose Silverlight 4 as version

clip_image001

Right click on project and add Service Reference

In Address you need to give URL of OData. As we discussed in previous steps, here I am giving OData URL of NorthWind Database hosted by OData.org.

clip_image003

Add below namespaces on MainPage.Xaml.cs page

clip_image004

Please make sure about second namespace. Since, I have added service reference of OData with name ServiceReference1 and name of project is ODatainMangoUpdated.

Globally defined below variables

clip_image006

In constructor of MainPage,

  1. Create instance of NorthWindEntities
  2. Create instance of DataServiceCollection passing context
  3. Write the LINQ query.
  4. Attach event handler LoadCompleted on DataServiceCollection object.
  5. Fetch the result asynchronously

image

On the completed event

  1. Check whether next page exist or not , if yes load automatically
  2. Set the DataContext of layout as result.

image

Design Page and Bind List Box

Here you need to create a ListBox and in Data Template put three TextBlock vertically. Bind the different columns of table to the text blocks

image

For your reference full source codes are given below. Feel free to use them Smile

MainPage.Xaml


<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="ODATAWithSilverLight.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox x:Name="MainListBox" Margin="0,0,-12,0"
                 ItemsSource="{Binding}"
                 Height="350"
                 Width="250"
                 ScrollViewer.VerticalScrollBarVisibility="Visible">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,0,0,17" Width="432">
                        <TextBlock Text="{Binding Path=CompanyName}"
                                          TextWrapping="NoWrap"
                                       />
                        <TextBlock Text="{Binding Path=ContactName}"
                                         TextWrapping="NoWrap"
                                       Margin="12,-6,12,0" />
                        <TextBlock Text="{Binding Path=Phone}"
                                          TextWrapping="NoWrap"
                                       Margin="12,-6,12,0"
                                       />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

MainPage.Xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ODATAWithSilverLight.ServiceReference1;
using System.Data.Services.Client;

namespace ODATAWithSilverLight
{
    public partial class MainPage : UserControl
    {

        private NorthwindEntities context;
        private readonly Uri ODataUri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");
        private DataServiceCollection<Customer> lstCustomers;

        public MainPage()
        {
            InitializeComponent();
            context = new NorthwindEntities(ODataUri);

            lstCustomers = new DataServiceCollection<Customer>(context);
            var result = from r in context.Customers select r;
            lstCustomers.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(lstCustomers_LoadCompleted);
            lstCustomers.LoadAsync(result);

        }

        void lstCustomers_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (lstCustomers.Continuation != null)
            {
                lstCustomers.LoadNextPartialSetAsync();
            }
            else
            {
                this.LayoutRoot.DataContext = lstCustomers;
            }

        }

    }
}

Run Application

Press F5 to run the application. You should get all the records from Customer table in List box.

image

I Hope this post was useful. Thanks for reading Smile



********************

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Consuming OData in Windows Phone 7.1 or Mango Phone

Background

If you would have read my posts discussing WCF Data Service and Windows Phone 7, there were many steps involved in consuming WCF Data Service in Windows Phone 7

  1. Download OData client for Windows Phone 7 and add as reference in Windows Phone 7 project
  2. Create Proxy of WCF Data Service using svcutil.exe
  3. Add as existing item create proxy in Windows Phone 7 project.
  4. Performing the operations from Phone.

You can read previous article here

In Beta release of Windows Phone 7.1 or Mango phone consuming OData has been improved very impressively Smile essentially now you do not need to perform all the steps mentioned in previous articles.

OData URL

In this post, I will be using NorthWind OData URL. You can access that URL from below link.

http://services.odata.org/Northwind/Northwind.svc/

We are going to fetch Customers table from NorthWind DataBase.

Create Project and Add Service Reference

Create a new Windows Phone 7.1 project and choose target framework as Windows Phone 7.1

imageimage

Right click on project and add Service Reference

image

In Address you need to give URL of OData. As we discussed in previous steps, here I am giving OData URL of NorthWind Database hosted by OData.org.

image

Writing Code behind

Add below namespaces on MainPage.Xaml.cs page

clip_image001

Please make sure about second namespace. Since, I have added service reference of OData with name ServiceReference1 and name of project is ODatainMangoUpdated.

Globally defined below variables

image

In constructor of Page,

  1. Create instance of NorthWindEntities
  2. Create instance of DataServiceCollection passing context
  3. Write the LINQ query.
  4. Attach event handler LoadCompleted on DataServiceCollection object.
  5. Fetch the result asynchronously

image

On the completed event

  1. Check whether next page exist or not , if yes load automatically
  2. Set the DataContext of layout as result.

image

Design Page and Bind List Box

Here you need to create a ListBox and in Data Template put three TextBlock vertically. Bind the different columns of table to the text blocks

image

For your reference full source codes are given below. Feel free to use them Smile

MainPage.Xaml


<phone:PhoneApplicationPage
    x:Class="ODatainMangoUpdated.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="OData in Mango" Style="{StaticResource PhoneTextNormalStyle}"/>

        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Margin="0,0,0,17" Width="432">
                            <TextBlock Text="{Binding Path=CompanyName}" TextWrapping="NoWrap"
                                       Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                            <TextBlock Text="{Binding Path=ContactName}" TextWrapping="NoWrap"
                                       Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                            <TextBlock Text="{Binding Path=Phone}" TextWrapping="NoWrap" Margin="12,-6,12,0"
                                       Style="{StaticResource PhoneTextSubtleStyle}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

MainPage.Xaml.cs


using System;
using System.Linq;
using Microsoft.Phone.Controls;
using System.Data.Services.Client;
using ODatainMangoUpdated.ServiceReference1;

namespace ODatainMangoUpdated
{
    public partial class MainPage : PhoneApplicationPage
    {
        private NorthwindEntities  context;
        private readonly Uri ODataUri = new Uri("http://services.odata.org/Northwind/Northwind.svc/");
        private DataServiceCollection<Customer> lstCustomers;

        public MainPage()
        {
            InitializeComponent();
            context = new NorthwindEntities(ODataUri);
            lstCustomers = new DataServiceCollection<Customer>(context);
            var result = from r in context.Customers  select r;
            lstCustomers.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(lstCustomers_LoadCompleted);
            lstCustomers.LoadAsync(result);

        }

        void lstCustomers_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (lstCustomers.Continuation != null)
            {
                lstCustomers.LoadNextPartialSetAsync();
            }
            else
            {
                this.LayoutRoot.DataContext = lstCustomers;
            }

        }
    }
}

Run Application

Press F5 to run the application. You should get all the records from Customer table in List box.

image

I hope this post was useful. Thanks for reading  Smile

Fetching Data from SQL Azure table in Windows 7.1 [Mango] Phone using WCF Data Service

In this article, we will discuss about how to consume data from cloud [SQL Azure] in a Windows 7.1 [Mango] phone. SQL Azure and Windows 7.1 [Mango] phones are two common terms that you can hear about from many tech-savvy people. So I thought it is the right time to integrate these technologies. In this article, I have tried my best not to focus on the theoretical aspects. Instead, I will present a step-by-step approach on how to consume Data from cloud in a Windows 7 phone application.

What we intend to achieve is given below:

image

 

In this article, we will cover

  1. Migrating local Database to SQL Azure
  2. Creating Data Model on Database in Cloud
  3. Expose Data Model as WCF Data Service
  4. Consumption of Data from cloud in Windows 7.1 or Mango phone through WCF Data Service.

 

The block diagram for the same is given below. We have a School Database on our local (In premise) SQL Server. We will be moving the local school database along with the schema and data to SQL Azure. Then, we will create a Data Model on the school database in the cloud and expose that Data model as WCF Data Service. Once the data from cloud is exposed as WCF Data Service, we will fetch that in the Windows 7.1 phone

 

image

So, actually, there are two major steps involved,

  1. Exposing Data from cloud as WCF Data Service
  2. Consuming WCF Data Service in Windows 7 Phone

 

Creating local Database and migrating to SQL Azure

Creating Database

The first step is to create the database. We are going to use School database. Script of sample School Database copy from here

Generate Database Script for SQL Azure

Right click on School Database and select Tasks. From Tasks, select Generate Script.

 

image

From the Pop up, select Set Scripting option.

image

 

Give the file name by selecting Save to file option.

Now the main thing to be noticed here is that we need to so some change in the advanced setting. For that, click on advanced options.

 

image

 

And in types of data to script, select Script and Data – both options.

image

 

After that, click next and Finish. You can see that a SQL file is created, and we will be using this script to migrate our in-house school database to SQL Azure.

 

Create School Database in SQL Azure

Login the SQL Azure portal with your live credential

https://sql.azure.com/

SQL Azure can be explored by selecting Database option from the left panel.

image

To create School Database, select Data base server and from Database section, select Create option.

image

Provide Database name, Edition and Maximum Size.

image

 

Run the Script in SQL Azure

Open the SQL Server management studio

clip_image001

You will get Connect to server dialog box. Click on cancel.

clip_image002

After cancelling the dialog box, click on New Query (top left corner).

clip_image003

On clicking New Query, the Connect to Server dialog box appears again.

clip_image004

Now, here you need to provide the Server name of SQL Azure and Login credential of SQL Azure

You can get fully qualified server name in Properties tab of SQL Azure portal

image

You will get the server name in form of

abc.database.windows.net

where abc is name of your SQL Azure server. We need to provide this server name at the local SQL server management studio.

image

Make sure to select SQL Server Authentication and provide login user name and password of your SQL Azure database portal.

After that, before clicking Connect, click on Option

image

From Option, select School database.

image

Run the Script

Now once you have successfully connected to School Database in SQL Azure, copy the script and Run as given below.

 

image

 

After successfully run script, run the below command and all the tables name will get listed.

 

clip_image001[6]

In this way, you have successfully migrated database to SQL AZURE Smile

 

Exposing SQL Azure Database as WCF DATA Service

 

Create a Web Application

Create a new project and select ASP.Net Web Application project template from the Web tab. Give a meaningful name to the web application.

image

Create a Data Model

We can create a Data Model, which can be exposed as WCF Data Service in three ways

  1. Using ADO.Net Entity model.
  2. Using LINQ to SQL class.
  3. Custom Data Model.

Here, I am going to use ADO.Net Entity model to create the data model. So to create an entity model, do the following:

  1. Right click on web application and add a new item
  2. Select ADO.Net Entity model from Data tab.

image

3. Since we have table in SQL Azure DataBase, we are going to choose the option Select from database

image

 

4. Choose a new connection.

image

After clicking on New Connection, this is the important step. We need to give extra care here Smile

So provide the information as below,

image

Click on Test Connection to test if the connection established successfully or not? After this, you will get prompted if the Connection string contains sensitive data regarding if you want to keep that in configuration file or mange through program. You can select any one of these options according to what you need.

image

On providing your option, click on Next button; you can see that all the tables, Views, and Stored Procedures’ are available to be chosen as a part of the data model for WCF Data Service.

image

5. Select tables, views and stored procedure from the database you want to make as the part of your data model.

Creating WCF Data Service

  1. Right click on Web Application project and add a new item.
  2. Select WCF Data Service from Web tab. Give any meaningful name. I am leaving the default name here.

image

3. After adding the WCF Data Service, we can see a service file with extension .svc has been added to the solution explorer.

Very first, we need to put data source name. To do so, uncomment the first commented line and put the data source name. In our case, the name of the model which we created in the 2nd step is the data source. Our data model name is SchoolEntities

 

image

 

Now we need to set access rules for the entity or entity set. Since we have only one table; so either we can give name of the table explicitly or if we want to set the same access rule for all the table in the data model or data source, we can put *.

 

image

 

image

 

So we are setting the access rule that, on the entity in data source perform all the operations.

So finally, the svc file will look like

 

image

Run WCF Data Service

Just press F5 to run the WCF Data Service. The Data Service will be hosted in the default ASP.Net server.

On running, you can see all the table is listed there.

clip_image002

Append the URL with People and you will get all the records from People table

clip_image004

Note: If your browser is not showing the expected result, make sure that the Feed reading of the browser is off. To do so, from the menu of IE, select Tools-> Internet Options -> Content

clip_image005

clip_image006

So we have exposed data from cloud using WCF Data service. Now any OADTA client can consume the data from cloud by consuming WCF Data Service.  Smile

 

Consuming WCF Data Service in Windows 7 Phone

First, we need to do is to create proxy of WCF Data service for Windows 7 phone. So to do this,

  1. Open command prompt in administrator mode.
  2. Navigate to folder C:\Windows\Microsoft.Net\FrameWork\V4.0.30319 Version of framework may vary depending on .Net framework you are working on.
  3. Once navigated to this particular folder, run the below command to create proxy class. We will add this proxy class in Windows 7 mobile application.

 

image

Explanation of command

  • There is space between all /out, /uri and /version
  • We are redirecting the output to D drive and Temp folder. So make sure that the Temp folder exists in the D drive.
  • School.cs is name of proxy class. You can give any name of your choice here. Once the command runs successfully, you will get School.cs class in Temp folder of D drive.
  •  After uri tag, give the uri of WCF data service.

 

Now after the execution of this command, we will have School.cs in Temp folder of D Drive.  Smile

Download the ODATA client library for Windows 7 phone from the below link and save the dll on local drive. We will add this DLL in Windows 7 phone application.

Download OData client library for Windows 7 Phone from here

Create a windows 7.1 phone application. Open Visual Studio and select the Windows phone Application project template from Silverlight for Windows Phone tab.

 

image

Choose  Windows Phone 7.1

image

Right click on the project and add existing item. Then navigate to Temp folder where you have created the WCF Data Service proxy class. In our case, it is School.cs. We created this in the previous step.

clip_image001[8]

Now we need to add ODATA client library reference in the Windows 7 Phone application. Right click on the project and add reference. Navigate to the folder where you saved System.Data.Service.Clientdll

clip_image002[5]

Display Data from Person Table in Windows 7 Phone application

We are going to display records of Person table in the list box. So first, let us create an entity class at client side. Right click and add a class called Person

Person.cs

 



namespace PhoneClient
{
    public class Person
    {

        public string PersonID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }


    }
}

 

Create a list box and we will bind the data in this list box. On click event of the Button, Data will get bound to the list box.

In below XAML ,

  1. We are creating a Button . On click event of Button , Data would be fetched from SQL Azure table.
  2. In List Box , we are binding the returned result

 

MainPage.xaml

 



<phone:PhoneApplicationPage
    x:Class="PhoneClient.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Mango with SQL Azure" Style="{StaticResource PhoneTextNormalStyle}"/>

            <Button x:Name="btnGetData" Height="100" Width="449" Content="Get Data From SQL Azure Table" Background=" blue" />
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <ListBox x:Name="lstDataFromCloud"
                 ItemsSource="{Binding}" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" >
                            <TextBlock Text="{Binding PersonID}" Margin="20" />
                            <TextBlock Text="{Binding LastName}" Margin="20" />
                            <TextBlock Text="{Binding FirstName }" Margin="20" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>


        </Grid>
    </Grid>



</phone:PhoneApplicationPage>


 

 

Now on click event of the button, we need to call the WCF Data Service and bind the list box . We are making an asynchronous call here .

MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Data.Services.Client;
using SchoolModel;


namespace PhoneClient
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        SchoolEntities schoolEntity;
        List<Person> lstPersonClient;
        List<SchoolModel.Person> lstpersonWcf;


        public MainPage()
        {
            InitializeComponent();
            schoolEntity = new SchoolEntities(new Uri("http://localhost:27274/WcfDataService1.svc/"));
            btnGetData.Click += new RoutedEventHandler(btnGetData_Click);

            lstPersonClient = new List<Person>();
            lstpersonWcf = new List<SchoolModel.Person>();

        }

        void btnGetData_Click(object sender, RoutedEventArgs e)
        {

            MessageBox.Show("Hi");

            var query = schoolEntity.CreateQuery<SchoolModel.Person>("People");
            query.BeginExecute(ar =>
            {
                DataLoad(ar);
            }, query);

        }

                private void DataLoad(IAsyncResult result)
        {
            DataServiceQuery<SchoolModel.Person> query = result.AsyncState as DataServiceQuery<SchoolModel.Person>;
            lstpersonWcf = query.EndExecute(result).ToList();
            Dispatcher.BeginInvoke(() =>
                   {
                       foreach (var r in lstpersonWcf)
                       {
                           lstPersonClient.Add(new Person {PersonID = r.PersonID.ToString() , LastName= r.LastName , FirstName = r.FirstName});
                       }
                       this.lstDataFromCloud.DataContext = lstPersonClient ;
                   }


                );
        }
    }
}




 

On running you should get output as below,  Smile

image

 

If this post was useful to you then buy me a coffee Smile .  Thanks for reading.

 

 

WCF Data Service with SQL Azure

In this article we will expose database from cloud or SQL Azure as WCF Data Service.

There two steps mainly involved in this

1. Creating local Database and migrating to SQL Azure

2. Exposing SQL Azure Database as WCF DATA Service

Step1: Creating local Database and migrating to SQL Azure

Creating Database

The first step is to create database. We are going to use School database. Script of sample School Database copy from here

Generate Database Script for SQL Azure

Right click on School Database and select Tasks. From Tasks select Generate Script.

clip_image001

From Pop up select Set Scripting option.

clip_image003

Give the file name by selecting Save to file option.

Now the main thing to be noticed here is we need to so some change in advanced setting. For that click on Advanced options.

clip_image004

And in types of data to script select Script and Data both option.

clip_image005

After that click next and Finish. You can see a SQL file is created and we will be using this script to migrate our in house school database to SQL Azure.

Create School Database in SQL Azure

Login SQL Azure portal with your live credential

https://sql.azure.com/

Click on SQL Azure tab. You will get the project , you have created for yourself.

clip_image007

Click on the project. In my case project name is debugmode. After clicking on project, you will get listed the entire database created in your SQL Azure account.

clip_image009

Here in my account there are two database already created. They are master and student database. Master database is default database created by SQL Azure for you.

Click on Create Database

clip_image011

Give the name of your database. Select the edition as Web and specify the max size of database.

clip_image012

You can select other option also for the edition as business

After that click on Create you can see on Databases tab that Demo1 database has been created.

clip_image014

Run the Script in SQL Azure

Open SQL Server management studio

clip_image015

You will get Connect to server dialog box. Click cancel on that.

clip_image016

After cancelling the dialog box click on New Query from left top

clip_image017

On clicking New Query, you will get the connect to server dialog box again.

clip_image018

Now here you need to provide, Server name of SQL Azure and Login credential of SQL Azure.

To know what is database server name of SQL Azure portal, login to Windows Azure portal with your live credential and then click on SQL Azure tab

clip_image020

You will get the server name in form of

abc.database.windows.net

Where abc is name of your SQL Azure server. We need to provide this server name at local sql server management studio.

clip_image021

Make sure to select SQL Server Authentication and provide login user name and password of your SQL Azure database portal.

After that before clicking Connect click on Option

clip_image022

From Option select School database.

clip_image023

Run the Script

Now once you successfully got connected to School Database in SQL Azure. Copy the script and Run like below.

clip_image025

After successfully running of script, run the below command and all the tables name will get listed.

clip_image026

In this way you successfully migrated database to SQL AZURE.

Step2: Exposing SQL Azure Database as WCF DATA Service

Create a Web Application

Create a new project and select ASP.Net Web Application project template from Web tab. Give a meaning full name to the web application.

clip_image028

Create a Data Model

We can create a Data Model, which can be exposed as WCF Data Service in three ways

1. Using ADO.Net Entity model.

2. Using LINQ to SQL class.

3. Custom Data Model.

For our purpose, I am going to use ADO.Net Entity model to create the data model. So to create an entity model

1. Right click on web application and add a new item

2. Select ADO.Net Entity model from Data tab.

clip_image030

3. Since we have table in SQL Azure Dat aBase. So we are going to choose option, select from database.

clip_image031

4. Choose a new connection.

clip_image032

After clicking on New Connection, this is the more important step. We need to give extra care here.

So provide the information as below,

clip_image033

Click on Test Connection to test connection established successfully or not? After that you will get prompted as Connection string contains sensitive data, do you want to keep that in configuration file or mange through program. You can select as of your choice and need.

clip_image034

On providing your option click on Next button, you can see all the tables, Views, Stored Procedures’ are available to chosen as part of data model for WCF Data Service.

clip_image035

5. Select tables, views and stored procedure from data base you want to make as the part of your data model.

Creating WCF Data Service

1. Right click on Web Application project and add a new item.

2. Select WCF Data Service from Web tab. Give any meaningful name. I am leaving the default name here.

clip_image037

3. After adding the WCF Data Service, we can see a service file with extension .svc has been added to the solution explorer.

Very first we need to put data source name. To do so uncomment the first commented line and put the data source name. In our case name of the model, which we created in 2nd step is the data source. Our data model name is SchoolEntities

clip_image039

Now we need to set access rules for entity or entity set. Since we have only one table, so either we can give name of the table explicitly or if we want to set the same access rule for all the table in the data model or data source we could put *.

clip_image041

clip_image042

So we are setting the access rule that, on the entity in data source perform all the operations.

So finally svc file will look like

clip_image044

Run the WCF Data Service

Just press F5 to run the WCF Data Service. Data Service will be hosted in the default ASP.Net server.

On running you can see, all the table is listed there.

clip_image046

Append the URL with People and you will get all the records from People table

clip_image048

Note: If your browser is not showing the expected result, make sure Feed reading of browser is off. To do from menu of IE and select tool and then Internet Option then Content

clip_image049

clip_image050

So we have exposed data from cloud using WCF Data service. Now any OADTA client can consume the data from cloud by consuming WCF Data Service.

Thanks for reading , I hope this article was useful .