Page Stack in Windows Phone

In your application there may be many pages and you will come across requirement to navigate between pages. Windows Phone navigation model allows you to navigate between pages. Windows Phone navigation model is same as web based page navigation model. Even though name suggests in Windows Phone, pages are not windows. In your application, you can navigate between many pages and Windows Phone operating system stores those pages on stack. At any given time you have navigation history stored in the page stack. Windows phone operating system pushes all the pages on the stack and popped out pages with back key. When only one page left on page stack on clicking of hardware back button application gets terminated.

Page stack can be understand with below diagram,

You navigated from Page 1 to Page2 then page stack will be as below,

clip_image001

You navigated from Page2 to Page3. Now Page 3 has been pushed to Page Stack.

clip_image002

On Page 3 you pressed hardware back button so Page 3 has been popped out from the Page Stack.

clip_image003

Now on Page 2 you pressed hardware back button so Page 2 has been popped out from the Page Stack.

clip_image004

In last you have navigated back to start page of the application. And only one page is left on the Page Stack. Now if you press hardware back button you will come out of the application.

You can iterate the Page Stack by calling BackStack property of NavigationService class.

clip_image005

BackStack property is having only getter and not setter. So you can read all the pages from the stack but cannot manipulate that.

clip_image006

You can read Uri of all the pages in PageStack as below,

clip_image007

In this way you can work with Page Stack in Windows Phone. I hope this post is useful. Thanks for reading.

 

Code to send game invite to multiple user in Windows Phone

You can send game invite to multiple users in Windows Phone using GameInviteTask chooser.

GameInviteTask chooser is used to send invitation to other users in multi-player game. It provides an invite screen to user where they can configure Email address of other users to send game invitation. Invitation will be sent by GameInviteTask chooser is in asynchronous manner.

GameInviteTask will launch invite screen and when user will complete configuring Email address of other user then complete event will get fired.

To work with GameInviteTask, you need to follow below steps

Very first you need to declare variable globally on the page as below,

image

Then Create instance of GameInviteTask and attach completed event in the constructor of the page as below,

image

Next you need to call the show method to launch invite screen application as per your business requirement. It may be on click event of a button. Session Id is string identifying particular network session.

image

In completed event handle user action. On selection of user shown appropriate message as below,

image

User will configure Email Id as below,

image

On user selection cancel, message will be shown in message box as below.

image

For your reference full source code is as below,



public partial class MainPage : PhoneApplicationPage
{
GameInviteTask gameInviteTask;

public MainPage()
{
InitializeComponent();
gameInviteTask = new GameInviteTask();
gameInviteTask.Completed += new EventHandler<TaskEventArgs>(gameInviteTask_Completed);

}

private void Button_Click(object sender, RoutedEventArgs e)
{
gameInviteTask.SessionId = "your session id of the game";


}

void gameInviteTask_Completed(object sender, TaskEventArgs e)
{
switch (e.TaskResult)
{

case TaskResult.OK:
MessageBox.Show("Sent");
break;

case TaskResult.Cancel:
MessageBox.Show("Cancel");
break;

case TaskResult.None:
MessageBox.Show("Failed");
break;
}
}
}


In this way you can send game invitation to multiple users. I hope this post is useful. Thanks for reading.

WebBrowserTask and MediaPlayerLauncher in Windows Phone

In this post, we will see WebBrowserTask launcher and MediaPlayer launcher.

WebBrowserTask launcher launches web browser application and display specified URL. This is defined as below,

image

You can set target URL either as string or as Uri. User will be asked for the confirmation. You can navigate to a URL as below,



WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://debugmode.net", UriKind.Absolute);
webBrowserTask.Show();

On running you will be navigated to given URL as below,

image

MediaPlayerLauncher is used to launch media player application and play the video from specified URL. This class is defined as below,

image

You can set desired controls of media player to be shown to user. Available media player controls are as below.

image

If you want to show more than one control to the user then you need to append them using OR operator and set them as value of control property.

image

You can also specify location of the media file in MediaLocationType property. MediaLocationType takes one of three values.

 

image

 

Install represents application installation directory, Data represents isolated storage and None value need to be set for external media.

You can play media with file from isolated storage as below,



MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();

mediaPlayerLauncher.Media = new Uri("SongVideo.wmv", UriKind.Relative);
mediaPlayerLauncher.Location = MediaLocationType.Data;
mediaPlayerLauncher.Controls = MediaPlaybackControls.Pause |
MediaPlaybackControls.Stop|
MediaPlaybackControls.FastForward;
mediaPlayerLauncher.Orientation = MediaPlayerOrientation.Landscape;

mediaPlayerLauncher.Show();

In this way you can work with MediaPlayerLauncher.

In this post we discussed on WebBrowserTask and MediaPlayerLauncher. You may need to call these native applications from your app. I hope this post is useful. Thanks for reading.

MarketPlaceSearchTask in Windows Phone

MarketPlaceSearch Task launcher is used to launch Marketplace client application with the searched result set in the criteria. It helps to search to marketplace from the application.

MarketPLaceSearchTask is defined as below,

image

You can see in the definition that, you can set MarketplaceContentType and SearchTerms. MarketPlaceContentType is defined as below,

image

So it can take either Application or Music as value. Now if you want to search music in market place then you can do that as below,


MarketplaceSearchTask task = new MarketplaceSearchTask();
task.ContentType = MarketplaceContentType.Music;
task.SearchTerms = "Waiting for Tonight";
task.Show();


You will get Market place search application launched as below,

image

If you want to search any application like debugmode , you can search as below,


MarketplaceSearchTask task = new MarketplaceSearchTask();
task.ContentType = MarketplaceContentType.Applications;
task.SearchTerms = "debugmode";
task.Show();


You will get Market place search application launched as below,

clip_image001[6]

In this way you can use MarketPlaceSearchTask. I hope this post is useful. Thanks for reading.

 

Code to Share Status or Links on Social Media sites in Windows Phone

While creating application for Windows Phone you may come across requirement to share certain message from your application on social media sites configured on user device. You can do it using ShareStaus Task. ShareStausTask class is defined as below. It is inherited from ShareTaskBase class.

image

 

ShareStatus Task Launcher allows an application to launch a dialog that allows user to share status message on social network site.

A status message can be shared as below,


ShareStatusTask shareStatusTask = new ShareStatusTask();
shareStatusTask.Status = "Hey I am Shared By DebugMode";
shareStatusTask.Show();


You may come across other scenario where you may need to share HyperLink across Social Media sites from your application. You can do that using launcher ShareLinkTask.

ShareLinkTask class is defined as below,

image

ShareLink Task Launcher allows an application to launch a dialog that allows user to share links on social network site.

A link can be shared as below,



ShareLinkTask shareLinkTask = new ShareLinkTask();
shareLinkTask.Title = "DebugMode";
shareLinkTask.LinkUri = new Uri("http://debugmode.net", UriKind.Absolute);
shareLinkTask.Message = "Post of DebugMode.";
shareLinkTask.Show();

These launchers will be launched only if user has configured social media sites on their device. I hope this post is useful. Thanks for reading.

How to Use the ConnectionSettings Task for Windows Phone

ConnectionSettings Task allows user to set and adjust device network settings. ConnectionSettings task is defined in Microsoft.Phone.Tasks namespace as below,

image

User can set device network setting to any of the following

image

If you want to set Network connection setting to WiFi, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.WiFi;
connectionSettingsTask.Show();

image

If you want to set Network connection setting to Bluetooth, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
connectionSettingsTask.Show();

image

If you want to set Network connection setting to Cellular, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Cellular;
connectionSettingsTask.Show();

image

If you want to set Network connection setting to Airplane mode, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.AirplaneMode;
connectionSettingsTask.Show();


image

In this way you can set the network setting of device using ConnectionSettings task. I hope this post is useful. Thanks for reading

Learn and Win Windows Phone: A great event by Pune User Group and I Unlock Joy Program

imageimage

Pune user group along with Microsoft I unlock joy program brings a Learn and Win Windows Phone event in Pune.

Read about Pune User Group here and I Unlock Joy Program here

This is a great opportunity for developers to learn development of Windows Phone from veterans like Mayur Tendulkar and Amol Vaidya. This program will run on four consecutive Saturday starting from 28th January 2012.

You can register for program here

You can find important information at below given links,

 

About Program

http://iunlockjoy.cloudapp.net/

Speakers

http://iunlockjoy.cloudapp.net/Speakers

Agenda

http://iunlockjoy.cloudapp.net/Agenda

Venue

http://iunlockjoy.cloudapp.net/Venue

FAQ

http://iunlockjoy.cloudapp.net/FAQ

I hope to see you there and wish very good luck for Windows Phone.

 

Data from Cloud on Windows Phone

Data from cloud on the phone “, it may appear as a buzzing sentence to you. In this post, I try to minimize complexity of accessing data from cloud to be specific from SQL Azure in Windows Phone. In this post I will walkthrough step by step accessing data from SQL Azure in Windows Phone.

image

I have divided task in three parts.

image

We will expose all the operation on Student database residing in SQL Azure as WCF REST Service. In this case REST is working on JSON data.

Setting up project

Very first let us set up the project. We want to expose operation as WCF Service hosted in Windows Azure. So to do that, you need to create WCF Service Role.

image

Creating Data Model

We are going to create DataModel using LINQ to SQL Class. To create DataModel right click on project then select add new item and choose LINQ to SQL Class form Data tab.

clip_image002

Next you need to choose the option Server explorer and add a new connection. In Add new connection windows provide database information for SQL Azure.

clip_image003

From drop down you choose database of your choice. In this case I am going to select Student database. After selecting database on the designer, I am dragging and dropping table Person. On the designer (dbml) you should have Person class .As of now we have created DataModel. In solution explorer you will find dbml and dbml.cs file has been created.

Creating Service

Data Transfer Object class represents entity from Data Model we want to expose as part of service contract. We need to create Data Transfer Object class. This class will act as Data Contract between Service and Client. To add a Data Transfer Object class go ahead and add a new class to project as below.

PersonDTO.cs


using System.Runtime.Serialization;

namespace RESTJSONStudentsData
{
[DataContract]
public class PersonDTO
{
[DataMember]
public string StudentId { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }

}
}


We have created Data Contract. Now we need to create Service Contract. Service Contract must be attributed to behave as WCF REST Service. I have set request and response format as JSON.

IService1.cs


using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace RESTJSONStudentsData
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate="/Persons",
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json]
List<PersonDTO> GetPersons();
}
}

Now we need to implement the service. In Service implementation, I am querying Person table of Student database using LINQ and constructing List of PersonDTO.

Service1.svc.cs


using System.Collections.Generic;
using System.Linq;

namespace RESTJSONStudentsData
{

public class Service1 : IService1
{

public List<PersonDTO> GetPersons()
{
DataClasses1DataContext context = new DataClasses1DataContext();
List<PersonDTO> result = (from r in context.Persons
select new PersonDTO
{
FirstName = r.FirstName,
LastName = r.LastName,
StudentId = r.PersonID.ToString()
}).ToList<PersonDTO>();
return result;

}
}
}

Next in this section we need to configure service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below changes.

Web.Config


<system.serviceModel>

<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name ="RESTJSONStudentsData.Service1" behaviorConfiguration="servicebehavior" >
<endpoint name ="RESTEndPoint"
contract ="RESTJSONStudentsData.IService1"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>

</service>
</services>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>


After configuring, Service ready for hosting. We need to host it in Windows Azure Portal. For that right click on Windows Azure project and select Package and Upload this package to one of the hosted service. Up to this step we have created and hosted WCF REST Service returning JSON.

Consuming Service in Windows Phone

To consume REST Service in Windows Phone 7 and then parse JSON, you need to add below references in Windows Phone 7 project.

clip_image001

We need a class to represent PersonDTO class .For that makes a class called Person at client side.

Person.cs


namespace PhoneApp11
{
public class Person
{
public string StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

}
}

As the design of the page I have put a ListBox. Data returned from cloud table will get bind to this ListBox.

MainPage.xaml



<phone:PhoneApplicationPage
x:Class="PhoneApp11.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"
Loaded="PhoneApplicationPage_Loaded">

<!--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="data from SQL Azure" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="students" 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="lstPerson" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding LastName}" Style="{StaticResource PhoneTextTitle1Style}" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding StudentId}" Style="{StaticResource PhoneTextGroupHeaderStyle}" />
<TextBlock Text="{Binding FirstName}" Style="{StaticResource PhoneTextTitle2Style}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

</Grid>
</Grid>

</phone:PhoneApplicationPage>


We need to make a call to the service and on download of JSON data as string; we need to parse JSON using System.RunTime.Serlization.JSON

MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace PhoneApp11
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{


WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://debugmodesqlazurejson.cloudapp.net/Service1.svc/rest/Persons"));


}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Person>));
List<Person> result = (List < Person >) obj.ReadObject(stream);
lstPerson.ItemsSource = result;
}

}
}


In above code we are creating DataContractJsonSerializer object and passing List of Person to deseriliaze because service is returning list of PersonDTO. And as mentioned earlier Person class is representing PersonDTO class. Now go ahead and press F5 to run the application. You should be getting details of Person table from School database residing on SQL Azure.

clip_image002[7]

In later post we will explore further to perform other CRUD operations. I hope this post is useful. Thanks for reading.