Reading coordinate values using Accelerometer API in Windows Phone 7

In this post we will see how to read different axis values using Accelerometer API.

To work with Accelerometer API first you need to add reference of Microsoft.Devices.Sensors

clip_image001

Then below namespace,

clip_image001[6]

Now to capture X Axis, Y Axis and Z Axis value you need to follow below steps

Step 1

Create task object of Accelerometer chooser

clip_image001[8]

Step 2

Call the callback method when user will complete a task and Implement the completed event to capture user data and status when user complete as tasks.

clip_image001[10]

Step 3

Call the start method to start the accelerometer,

clip_image001[12]

Step 4

We can read value of XAxis, YAxis and ZAxis as below along with timestamp of capturing data as below in the completed event. We are changing double values to string.

clip_image001[14]

You can save these data for further use that when accelerometer value got changed.

Let us run the application in debug mode to see value got captured,

image

When you click on Capture Data button control will go to Accelerometer reading changed event. Then each time you will move the ball Accelerometer reading changed event will get called.

image

For your reference full code is as below,


using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;

namespace EncryptingandDecryptinginMango
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
void accelerometerTaskObject_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
string xCordinate = e.X.ToString("0.00");
string yCordinate = e.Y.ToString("0.00");
string zCordinate = e.Z.ToString("0.00");
DateTimeOffset timeCaptured = e.Timestamp;
}

private void btnCaptureData_Click(object sender, RoutedEventArgs e)
{

var accelerometerTaskObject = new Accelerometer();
accelerometerTaskObject.ReadingChanged +=
new EventHandler<AccelerometerReadingEventArgs>
(accelerometerTaskObject_ReadingChanged);

try
{
accelerometerTaskObject.Start();
}
catch
{
//Error in starting the Accelerometer
}

}
}
}

In this way you can work with Accelerometer API to capture different axis values. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Charts in Windows Phone 7

Today morning I got a call from SQL Server Guru  Pinal Dave and conversation was as below.

image

 

image

 

image

 

So, I started working on this. I decided to go ahead with hard coded data as below,

 


public class Bloggers
    {
        public string Name { get; set; }
        public double Posts { get; set; }
    }


And function returning data is,

 


public static List<Bloggers> GetMembers()
        {
            List<Bloggers> lstMembers = new List<Bloggers>
                                        {
                                            new Bloggers
                                            {
                                                 Name ="Pinal",
                                                 Posts = 2000

                                            },
                                            new Bloggers
                                            {

                                                 Name ="Debugmode",
                                                 Posts = 400
                                            },

                                             new Bloggers
                                            {

                                                 Name ="Koiarala",
                                                 Posts = 1000


                                            },
                                              new Bloggers
                                            {

                                                 Name ="Mahesh",
                                                 Posts = 1500


                                            },


                                        };
            return lstMembers;
        }



image

 


<Grid x:Name="LayoutRoot">
        <controls:Panorama Title="Bloggers">

            <!--Panorama item one-->
            <controls:PanoramaItem Header="Series Chart">
                <Grid>
                    <charting:Chart x:Name="seriesChart" Background="Black">
                        <charting:ColumnSeries Background="Black" />
                    </charting:Chart>
                </Grid>
            </controls:PanoramaItem>

            <!--Panorama item two-->
            <controls:PanoramaItem Header="Pie Chart">
                <Grid>
                    <charting:Chart x:Name="pieChart"></charting:Chart>
                </Grid>
            </controls:PanoramaItem>
            <!--Panorama item three-->
            <controls:PanoramaItem Header="Scatter Chart">
                <Grid>
                    <charting:Chart x:Name="scatterChart"></charting:Chart>
                </Grid>
            </controls:PanoramaItem>
        </controls:Panorama>
    </Grid>




 

To add chart control on XAML, I added namespace on XAML as below ,

 


 xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;
assembly=System.Windows.Controls.DataVisualization.Toolkit"


And on code behind as below,

 


using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Data;


Creating Column Series


ColumnSeries series = new ColumnSeries();
            seriesChart.Series.Add(series);
            series.SetBinding(ColumnSeries.ItemsSourceProperty, new Binding());
            series.ItemsSource =  GetMembers();
            series.DependentValuePath = "Posts";
            series.IndependentValuePath = "Name";



There is nothing to get confused in above code. It is creating a Column Series and adding to the chart in the first panorama item. Expected output would be as below ,

image

 

Creating Pie Series



PieSeries pieSeries = new PieSeries();
            pieChart.Series.Add(pieSeries);
            pieSeries.SetBinding(PieSeries.ItemsSourceProperty, new Binding());
            pieSeries.ItemsSource = Model.Factory.GetMembers();
            pieSeries.DependentValuePath = "Posts";
            pieSeries.IndependentValuePath = "Name";



Expected output is as below,

image

 

Creating Scatter Series


ScatterSeries scatterSeries = new ScatterSeries();
scatterChart.Series.Add(scatterSeries);
scatterSeries.SetBinding(ScatterSeries.ItemsSourceProperty, new Binding());
scatterSeries.ItemsSource = Model.Factory.GetMembers();
scatterSeries.DependentValuePath = "Posts";
scatterSeries.IndependentValuePath = "Name";


Expected Output is as below,

image

 

image

 

Smooth Streaming on Windows Phone 7

Read Smooth Streaming in Silverlight here

This post is walkthrough on enabling smooth streaming of media over IIS and then stream over Windows Phone 7 client. There are very good documentation available on IIS official site to have a better understanding of smooth streaming. So I am not touching theoretical concept behind smooth streaming in this post. However I have shown steps by steps to enable smooth streaming of media over IIS then to stream over Windows Phone 7 client.

imageimage

Essentially there are four majors steps you need to do

  1. Enable Smooth Streaming on IIS
  2. Encode Media File .There is a point to be noted here that Windows Phone 7 [at time of writing this post] does not support variable bit rate of streaming. It does support only VC-IIS Smooth Streaming -480 VPR Smile]
  3. Publish Encoded file over IIS
  4. Play the streamed media on Windows Phone 7 using smfPlayer.

Enable Smooth streaming on IIS

You need to download and install IIS Media Services. Go to below URL to download and install IIS Media Services.

http://www.iis.net/download/SmoothStreaming

image

After successful installation, you will have a section of Media Services in IIS.

image

 

Encode Media File

To encode media for IIS smooth streaming you need Microsoft Expression Encoder 4.0 pro. If you don’t have installed that then download and install that. It comes as part of Microsoft Expression.

Step 1

Very first open Microsoft Encoder Pro 4.0. You will get prompted to choose Project type to be loaded. Select Transcoding Project and press Ok.

image

Step 2

In this step you need to choose the media file to be encoded and streamed over IIS. Click on File in menu and select Import.

clip_image001

Choose media file to be encoded and streamed.

clip_image003

 

Step 3

In right side tab select Preset option. If you are unable to find Preset tab, select windows from menu and check preset.

clip_image004

From Preset tab select Encoding for Silverlight and then select IIS Smooth Streaming. After selecting option of IIS Smooth Streaming, you can choose VBR rate of your choice.

clip_image005

After IIS Smooth streaming type doesn’t forget to click Apply button.

Step 4

There are many options available for you to configure like,

  1. Thumbnails
  2. Security
  3. Template options
  4. Output path
  5. Publish etc

You can set values for above options as per your requirement. I am going to set output path here. Make sure you have created a folder on your local derive to set as output path for the encoded media for the streaming. On my local D drive, I have created a folder called StreamDemo. So set the output path as below

clip_image001[5]

Make sure to check Sub-folder by job ID. Leave Media File name as default name.

 

Step 5

If you have set the values for everything required then go ahead and click on the Encode button in the bottom.

clip_image002

You should be getting Encoding status message as below.

clip_image003

 

After successful encoding you will get encoded media playing the browser from the local derive. Now you have encoded media file.

 

Publish Encoded File over IIS

To stream over IIS, you need to publish encoded media over IIS. Process to publish encoded media is same as publishing any other web site over IIS.

Step 1

Open IIS as administrator and add a new web site

clip_image004[5]

Step 2

In dialog box you need to provide below information

  1. Site name: Give any name of your choice
  2. Port : Choose any available port above 1024
  3. Host Name : Leave it empty
  4. Type : Http
  5. Check the check box start web site immediately.
  6. In Physical path, give the same location Encoded file is saved. In previous step while encoding media for streaming, I save file in location D:\StreamDEmo. So I am going to set Physical Path as D:\StreamDEmo.

 

image

Click Ok to create web site in IIS. So we created site StreamingMediaDemo1. Right click on that and select Manage Web Site and then browse.

image

On browsing most likely you will get forbidden error message as below,

image

Append Default.html in URL to play the media.

clip_image001[7]

Media will be played as below,

image

 

Now append wildlife.ism/manifest to the URL. This manifest file would be used in Windows Phone 7 and other clients to stream media over IIS.

image

Playing in Windows Phone 7

To Play media on Windows Phone 7 download below player from the CodePlex.

http://smf.codeplex.com/releases/view/63434#DownloadId=222617

After download extract the file on locally. You will have to add references of these dll in Windows Phone project. Since dll got downloaded from the web, so they would be locked. To use them in the project right click and unblock them.

Note : I would recommend to download msi file and install that to get all the required files.

Step 1

Create a Windows Phone Application

clip_image002

Choose target Windows Phone version 7.0

clip_image003[5]

Step 2

Right click and add the references. If you have run msi then you will get below references at the location,

C:\Program Files (x86)\Microsoft SDKs\Microsoft Silverlight Media Framework\v2.4\Silverlight For Phone\Bin

clip_image005

Step 3

You need to download IIS smooth client and install from below URL.

http://www.iis.net/download/smoothclient

Step 4

Right click on Windows Phone 7 project and add reference of Microsoft.web.media.smoothstreaming.dll

To locate this file on your local drive browse to C:\Program Files (x86)\Microsoft SDKs\IIS Smooth Streaming Client\v1.5\Windows Phone on 64 bit machine.

clip_image007

 

Step 5

Next we need to design Silverlight page. Open MainPage.xaml and add namespace,

image

 

And add a player on the page downloaded to play stream media as below,

clip_image001[9]

Eventually xaml will be as below with a textblock to display message and player

Mainpage.xaml

 

<phone:PhoneApplicationPage
    x:Class="Streaming.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:Core="clr-namespace:Microsoft.SilverlightMediaFramework.Core;assembly=Microsoft.SilverlightMediaFramework.Core.Phone"
    xmlns:Media="clr-namespace:Microsoft.SilverlightMediaFramework.Core.Media;assembly=Microsoft.SilverlightMediaFramework.Core.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:ssme="clr-namespace:Microsoft.Web.Media.SmoothStreaming;assembly=Microsoft.Web.Media.SmoothStreaming"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="728" d:DesignHeight="480"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="PortraitOrLandscape"  Orientation="Landscape"
    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="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="Streaming Media from IIS on Silverlight" Height="22" Width="266" FontSize="12" Foreground="Blue"/>
                <Core:SMFPlayer Name="strmPlayer"
                    HorizontalAlignment="Stretch"
                                 Margin="0"
                                 VerticalAlignment="Stretch"/>

            </StackPanel>
        </Grid>
    </Grid>

    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

Step 6

We need to write some code on page load to create play list of streamed media and play in the player.

Mainpage.xaml .cs


using System;
using Microsoft.Phone.Controls;
using Microsoft.SilverlightMediaFramework.Core.Media;


namespace Streaming
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            PlaylistItem item = new PlaylistItem();
            item.MediaSource = new Uri("http://localhost:9173/wildlife.ism/manifest");
            item.DeliveryMethod = Microsoft.SilverlightMediaFramework.Plugins.Primitives.DeliveryMethods.AdaptiveStreaming;
            strmPlayer.Playlist.Add(item);
            strmPlayer.Play();

        }


    }
}

Step 7

Press F5 to run the application.

imageimage

These were what all required to smooth stream media from IIS and play in Windows Phone 7 client. I hope this post was useful. I am looking very forward for your comments on the post. Thanks for reading  Smile

 

Changing Application Tile in Windows Phone 7

When you create a Windows Phone 7 application, by default newly created app will have

  • Title
  • Background Image
  • Icon

Value set to default as below ,

clip_image001

If you will notice by default Title would be the same as of name of the Windows Phone Application project.

On running you will get Application tile as below,

clip_image002

If you want to change the default values for Application Tiles, very easily you can do that. Follow the below steps

Step 1

Right click on the application in solution explorer and add an existing item. Select and image and upload it. I have added an image named OData-logo.png in the application.

Step 2

Right click on OData-logo.png and click on Properties

clip_image003

Change Build Action to Content from Resource.

clip_image001[5]

Step 3

Right click on the application in solution explorer and click on Properties .In properties windows select application tab and here you can change the default values. In drop down for Icon and background image, now you will get OData-logo.png image also to select from.

clip_image002[6]

I have changed value of title and chosen OData-logo.org as Icon image. Save the setting and run the application.

clip_image003[5]

Now you can see title and icon for the application have been changed.

I hope this post was useful. Thanks for reading Smile

Viewing Flickr Images on Windows 7.1 Phone or Mango Phone

In this post I will show you how you can create a Photo Viewer from images of the Flickr Service.

Flickr Service

Flickr expose a REST based feed to access images. You can find information about Flickr public feed at below link.

http://www.flickr.com/services/feeds/docs/photos_public/

Public images feed can be find at

http://api.flickr.com/services/feeds/photos_public.gne

Expected Output

imageimage

Approach

  1. Call Flickr Service
  2. Parse XML feed
  3. Bind it to List Box.

Create Windows Phone 7.1 Application

Create Windows 7 Phone Application and select Windows Phone 7.1 as target Windows Phone version.

clip_image002

clip_image003

Create Photo class

To bind images to the ListBox, let us create Photo class. Right click and add a class called Photo in the project. When we parse Flickr Image feeds, we will bind public Image URL here

Photo.cs

clip_image005

Parsing Image Feed of Flickr Service

When you open public feed URL of Flicker in browser; you can view the feeds in browser itself.

clip_image007

We are going to give value of link element from the feed in Image as source value.

We will have to make asynchronous calls as below,

image

Then in DonwnloadStringCompleted event, we will have to perform below tasks,

  1. Create a Observable collection of Photos
  2. Parse the Feed
  3. Iterate through all the public image url in feed and add to collection.

image

Parsing of feeds can be done as below,

  1. We are parsing Link URL.
  2. Fetching the value of href attribute in Link URL.
  3. There are two link elements and we are fetching value of link element having rel attribute value as enclosure

image

Design the Page

We are going to put a ListBox in content grid and inside ItemTemplate of ListBox , we will put Image control.

clip_image001

As source of the Image you need to bind PhotoSource property of Photo class.

For Reference full source codes are given below. Feel free to use for your purpose  Smile

MainPage.xaml


<phone:PhoneApplicationPage
    x:Class="FlickerImageFeed.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 Phone" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Flicker Images" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox x:Name="lstImage" Width="450" Margin="3,6">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding PhotoSource}"
                                   Width="425"
                                   Height="auto"
                                   Stretch="Uniform"
                                   HorizontalAlignment="Center" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Xml.Linq;

namespace FlickerImageFeed
{
    public partial class MainPage : PhoneApplicationPage
    {

        IEnumerable<List<string>> imageURL;
        List<string> lstImageURl;
        Photo P;
        ObservableCollection<Photo> photos;
        public MainPage()
        {
            InitializeComponent();
            GetAllPhotos();
        }

        private ImageSource GetImageSource(string fileName)
        {
            return new BitmapImage(new Uri(fileName, UriKind.Absolute));
        }
        private void  GetAllPhotos()
        {

            WebClient proxy = new WebClient();
            proxy.DownloadStringAsync(new Uri("http://api.flickr.com/services/feeds/photos_public.gne"));
            proxy.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);

        }

        void proxy_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            photos = new ObservableCollection<Photo>();
            lstImageURl = new List<string>();
            imageURL = ParseXML(e.Result);
            foreach (var r in imageURL)
            {
                foreach (var a in r)
                {
                    P = new Photo { PhotoSource = GetImageSource(a.ToString()) };
                    photos.Add(P);
                }
            }

            lstImage.ItemsSource = photos;

        }
        private IEnumerable<List<string>> ParseXML(string xmlData)
        {
            XNamespace ns = "http://www.w3.org/2005/Atom";
            XDocument doc = XDocument.Parse(xmlData);
            var photo = from r in doc.Descendants(ns + "entry")
                        select r.Elements(ns + "link")
                        .Where(f => (string)f.Attribute("rel") == "enclosure")
                        .Select(f => f.Attribute("href").Value).ToList();
            return photo;
        }
    }
}

Run the Application

Press F5 to run Photo viewer from images of Flicker service Smile

imageimage

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

Photo Viewer in Windows Phone 7.1 or Mango Phone

In this post I will show you how to create a simple Photo Viewer? Before I start, I would like to inform you about a gray part of this post that all the Images are attached as a resource in the phone application and this is not recommended. We should have either image in Isolated Storage or should be downloading from remote Server.

Expected Output

imageimage

Idea here is very simple,

  1. Create Observable collection of Images
  2. Bind it to List Box.

Create Windows Phone 7.1 Application

Create Windows 7 Phone Application  and select platform as Windows Phone 7.1

imageimage

Right click and add a folder called Images. We are going to upload all the images in this folder. So after uploading all the existing images solution explorer would look like below,

image

I know sometime these screen shorts may be annoying but I do it purposefully  for the beginners Smile

 

Create Photo class

To bind images to the ListBox , let us create Photo class. Right click and add a class called Photo in the project.

Photo.cs

clip_image002

 

We have added the photos and created a Photo class to represent the Photos.

Now add below namespaces on MainPage.Xaml.cs

 

clip_image001

 

To bind a photo (image) to Image control, we need to provide ImageSource. So let us write a function taking as input parameter filename and retuning BitmapImage of that file name. Here we will pass filename of images we uploaded in Images folder.

 

clip_image003

Next we need to create collection of Images. I am creating observable collection.

 

image

 

You need to set ItemSource of ListBOX as output of above function.

 

clip_image001[5]

Here lstImage is name of the ListBox.

Design the Page

We are going to put a ListBox in content grid and inside ItemTemplate of ListBox , we will put Image control.

 

clip_image001[7]

As source of the Image you need to bind PhotoSource property of Photo class.

For Reference full source codes are given below. Feel free to use for your purpose  Smile

 

MainPage.xaml

 


<phone:PhoneApplicationPage
    x:Class="ImageinMango.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">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text=" IClicked MVP OpenDays Photo on Mango" Style="{StaticResource PhoneTextNormalStyle}"/>
          </StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox x:Name="lstImage" Width="450" Margin="3,6">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding PhotoSource}"
                                   Width="425"
                                   Height="auto"
                                   Stretch="Uniform"
                                   HorizontalAlignment="Center" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>


 

MainPage.xaml.cs


using System;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel ;
using System.Windows.Media.Imaging ;

namespace ImageinMango
{
    public partial class MainPage : PhoneApplicationPage
    {

        public MainPage()
        {
            InitializeComponent();
            lstImage.ItemsSource = GetAllPhotos();
        }


        private ImageSource GetImageSource(string fileName)
        {
            return new BitmapImage(new Uri(fileName, UriKind.Relative));
        }

        private ObservableCollection<Photo> GetAllPhotos()
        {
            ObservableCollection<Photo> photos = new ObservableCollection<Photo>
                                                   {

                                                       new Photo{PhotoSource = GetImageSource("Images/AbhiM.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/AnandKH.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Harish.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/HarishV.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Abhi.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Suprotim.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/HarishVAlone.png")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Pinal.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Shaivi.jpg")},                                                       new Photo{PhotoSource = GetImageSource("Images/Shobhan.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Vikram.jpg")},
                                                       new Photo{PhotoSource = GetImageSource("Images/Host.jpg")}




                                                   };
            return photos;
        }
    }

}

 

Run the Application

Press F5 to run Photo viewer.  Smile

imageimg1

 

I hope this post was useful. Thanks for reading  Smile In further post , I will show you how to fetch Images from server instead of attaching them as resource.

Fetching Mobile Operator Name in Windows 7.1 Phone [Mango]

In this quick post I will show you,

How to fetch Mobile operator name in Windows 7 Phone?

Design the page

In content Grid, I have put a button. On click event of button, in message box we will display Mobile Operator Name

image

Write Code Behind

Add Namespace

clip_image001

On the click event of Button we will fetch operator name. Operator name can be fetched

clip_image003

Using calling CellularMobileOperator() function on DeviceNetworkInformation. After fetching , you can use it as string.

For your reference source code is as below,

MainPage.Xaml.cs


using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Net.NetworkInformation;

namespace MobileOperatorName
{
    public partial class MainPage : PhoneApplicationPage
    {

        public MainPage()
        {
            InitializeComponent();
            btnMobileOpeartor.Click += new RoutedEventHandler(btnMobileOpeartor_Click);
        }

        void btnMobileOpeartor_Click(object sender, RoutedEventArgs e)
        {
            string operatorName = "Mobile Opeartor : ";
            operatorName = operatorName + DeviceNetworkInformation.CellularMobileOperator.ToString();
            MessageBox.Show(operatorName);
        }

    }
}

Running the Application

Press F5 to run the application.

imageimage

I hope this post was useful. Thanks for reading Smile

Get Address from Contact in Windows Phone 7.1 [Mango]

In this post I will show you, how you could get Address from contact and Display it.

Expected Output

  1. On running of application you will get a button
  2. On click of button Contact list will be open
  3. On selection of a contact . address of that contact will be displayed in label.

imageimageimage

Design the page

I am going to put a very simple design. Design would have just one button and label.

On click event of the button, contact list would be open and on user selection of a contact, we will display address of that contact in label.  We are going to do very simple stuff . Don’t we ? Smile

Content Grid of MainPage.Xaml would be looking like below,

image

Write the Code

Add namespace

clip_image001

Globally defined a variable of type AddressChooserTask

 

clip_image002

 

In constructor of page create instance of AddressChooserTask and register completed event on that.

 

clip_image004

 

In the event, check whether TaskResult is equal to TaskResult enum OK. If yes then display name and address in label.

 

clip_image006

 

On click event of button, we will show the contact using addressChooserTask.Show

image

 

For you reference full source code of code behind is as below,

MainPage.Xaml.cs


using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;


namespace AddressChooser
{
    public partial class MainPage : PhoneApplicationPage
    {

        AddressChooserTask addressChooserTask;

        public MainPage()
        {
            InitializeComponent();
            addressChooserTask = new AddressChooserTask();
            addressChooserTask.Completed += new EventHandler<AddressResult>(addressChooserTask_Completed);

        }

        private void addressChooserButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                addressChooserTask.Show();
            }
            catch (System.InvalidOperationException ex)
            {

            }

        }

        void addressChooserTask_Completed(object sender, AddressResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                txtDisplay.Text = "The address for " + e.DisplayName + " is " + e.Address;
            }

        }
    }
}

Now when you run phone application you should get the expected output.

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.