•
•
•
•
•
Windows Phone
Recipes
A Problem-Solution Approach
Fabio Claudio Ferracchiati
|
Emanuele Garofalo
Avoid the common pitfalls of Windows Phone programming
with this concise recipe collection written specifically for the busy developer
SECOND EDITION
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
WindowsPhoneRecipes
AProblem-SolutionApproach
FabioClaudioFerracchiati
EmanueleGarofalo
ToSimonaandClaudia,womenofmine —Fabio
Tomymommyanddaddy,mylighthouseinthefog— Emanuele
Contents at a Glance
AbouttheAuthors... xxi
AbouttheTechnicalReviewer ... xxii
Acknowledgments ... xxiii
AboutThisBook... xxiv
Chapter1:IntroductiontoWindowsPhoneApplicationDevelopment ...1
Chapter2:WindowsPhoneExecutionModelAndMultitasking ...43
Chapter3:UserInterface...97
Chapter4:UserInterfacewithExpressionBlend ...179
Chapter5:Gestures ...201
Chapter6:Sensors ...223
Chapter7:MediaManagement...265
Chapter8:IsolatedStorage ...329
Chapter9:IntheCloud ...379
Chapter10:TestingWindowsPhoneApplications ...417
Contents
AbouttheAuthor... xxi
AbouttheTechnicalReviewer ... xxii
Acknowledgments ... xxiii
AboutThisBook... xxiv
Chapter1:IntroductiontoWindowsPhoneApplicationDevelopment ...1
1-1.ExaminingWindowsPhone ...1
Problem ... 1
Solution ... 1
1-2.UnderstandingtheDevelopmentTools ...4
Problem ... 4
Solution ... 4
HowItWorks ... 4
1-3.CreatingaSimpleSilverlightWindowsPhoneApplication ...6
Problem ... 6
Solution ... 6
HowItWorks ... 6
Usage... 12
1-4.CreatingaSimpleXNAWindowsPhoneApplication...13
Problem ... 13
Solution ... 13
CONTENTS
Usage... 17
1-5.CreatingaSimpleXNAandSilverlightMixedApplication...18
Problem ... 18
Solution ... 18
HowItWorks ... 18
Usage... 23
1-6.DeployingtheApplicationtotheWindowsPhoneEmulator ...24
Problem ... 24
Solution ... 24
Usage... 25
1-7.DeployingtheWindowsPhoneApplicationontheDevice ...28
Problem ... 28
Solution ... 28
HowItWorks ... 28
Usage... 29
1-8.SendingaWindowsPhoneApplicationtotheMarketplace...31
Problem ... 31
Solution ... 31
HowItWorks ... 31
1-9.CreatingaTrialWindowsPhoneApplication ...32
Problem ... 32
Solution ... 32
HowItWorks ... 33
Usage... 39
Chapter2:WindowsPhoneExecutionModelAndMultitasking ...43
2-1.NavigatingBetweenPages ...43
Problem ... 43
CONTENTS
HowItWorks ... 43
TheCode... 45
Usage... 47
2-2.PassingDataThroughPages ...48
Problem ... 48
Solution ... 48
HowItWorks ... 48
TheCode... 49
Usage... 50
2-3.NavigatingBetweenPagesUsingGlobalApplicationVariables...52
Problem ... 52
Solution ... 52
HowItWorks ... 53
TheCode... 53
Usage... 54
2-4.NavigatingBetweenPageswithState ...56
Problem ... 56
Solution ... 56
HowItWorks ... 56
TheCode... 57
Usage... 61
2-5.ManagingTombstoninginWindowsPhoneSilverlightApplications...65
Problem ... 65
Solution ... 65
HowItWorks ... 65
TheCode... 66
Usage... 71
CONTENTS
Problem ... 75
Solution ... 75
HowItWorks ... 76
TheCode... 76
Usage... 78
2-7.ImplementingMultitasking ...79
Problem ... 79
Solution ... 80
HowItWorks ... 80
TheCode... 81
Usage... 86
2-8.SchedulingAlarmsandReminders ...88
Problem ... 88
Solution ... 88
HowItWorks ... 89
TheCode... 89
Usage... 90
2-9.ManagingObscuredandUnobscuredEvents...93
Problem ... 93
Solution ... 94
HowItWorks ... 94
TheCode... 95
Usage... 96
Chapter3:UserInterface...97
3-1.CreatinganAnimatedSplashScreen...98
Problem ... 98
Solution ... 98
CONTENTS
TheCode... 98
Usage... 100
3-2.UsingtheApplicationBarControl ...102
Problem ... 102
Solution ... 102
HowItWorks ... 103
TheCode... 104
Usage... 106
3-3.DetectingChangesintheThemeTemplate ...108
Problem ... 108
Solution ... 109
HowItWorks ... 109
TheCode... 109
Usage... 110
3-4.CustomizingtheSoftInputPanelKeyboardtoAcceptOnlyNumbers ...112
Problem ... 112
Solution ... 113
HowItWorks ... 113
TheCode... 114
Usage... 115
3-5.UsingtheWindowsPhonePredefinedStyles...116
Problem ... 116
Solution ... 117
HowItWorks ... 117
TheCode... 118
Usage... 123
3-6.LocalizingYourApplication ...124
CONTENTS
Solution ... 124
HowItWorks ... 124
TheCode... 126
Usage... 128
3-7.UsingPanoramaandPivotControls ...131
Problem ... 131
Solution ... 131
HowItWorks ... 131
TheCode... 131
Usage... 137
3-8.SpicingUptheUserInterfacewiththeSilverlightToolkit...138
Problem ... 138
Solution ... 138
HowItWorks ... 138
TheCode... 140
Usage... 153
3-9.UsingLaunchersandChoosers...155
Problem ... 155
Solution ... 155
HowItWorks ... 155
TheCode... 157
Usage... 166
3-10.AccessingtotheContactsLibrary...170
Problem ... 170
Solution ... 170
HowItWorks ... 170
TheCode... 170
CONTENTS
3-11.AddingAdvertisingtoYourApplication...173
Problem ... 173
Solution ... 174
HowItWorks ... 174
TheCode... 175
Usage... 176
Chapter4:UserInterfacewithExpressionBlend ...179
4-1.GettingReadyforLightandDark ...179
Problem ... 179
Solution ... 180
HowItWorks ... 180
TheCode... 180
Usage... 185
4-2.ChangingtheSkinofYourApp...185
Problem ... 185
Solution ... 185
HowItWorks ... 185
Usage... 190
4-3.CreatingSomeCoolAnimation...190
Problem ... 190
Solution ... 190
HowItWorks ... 190
TheCode... 190
Usage... 194
4-4.CustomizingaControl ...195
Problem ... 195
Solution ... 195
CONTENTS
TheCode... 195
Usage... 199
Chapter5:Gestures ...201
5-1.ManagingGesturesinaSilverlightWindowsPhoneApplication ...201
Problem ... 201
Solution ... 201
HowItWorks ... 202
TheCode... 204
Usage... 205
5-2.AddingGesturesManagementtoClick-lessSilverlightControls ...207
Problem ... 207
Solution ... 207
HowItWorks ... 208
TheCode... 208
Usage... 211
5-3.HandlingGesturesinaGraphicalContext,SuchasaGameMenu ...212
Problem ... 212
Solution ... 212
HowItWorks ... 213
TheCode... 214
Usage... 216
5-4.ManagingGesturesfromtheSilverlightforWindowsPhoneToolkit...217
Problem ... 217
Solution ... 217
HowItWorks ... 217
TheCode... 217
CONTENTS
Chapter6:Sensors ...223
6-1.ResettingaFormbyShakingthePhone ...224
Problem ... 224
Solution ... 224
HowItWorks ... 224
TheCode... 225
Usage... 228
6-2.CreatingaSeismograph...229
Problem ... 229
Solution ... 230
HowItWorks ... 230
TheCode... 230
Usage... 235
6-3.IndicatingtheUser’sPositiononaMap...235
Problem ... 235
Solution ... 235
HowItWorks ... 236
TheCode... 236
Usage... 241
6-4.DisplayingSunsetandSunrise...241
Problem ... 241
Solution ... 241
HowItWorks ... 241
TheCode... 242
Usage... 242
6-5.IndicatingtheUser’sPositionviaCoordinates...243
Problem ... 243
CONTENTS
HowItWorks ... 243
TheCode... 243
Usage... 247
6-6.UsingtheRadio ...247
Problem ... 247
Solution ... 247
HowItWorks ... 248
TheCode... 248
Usage... 253
6-7.BuildinganAugmentedRealityApplication ...253
Problem ... 253
Solution ... 253
HowItWorks ... 254
TheCode... 254
Usage... 262
Chapter7:MediaManagement...265
7-1.TakingaPhotofromYourPhoneCamera ...265
Problem ... 265
Solution ... 265
HowItWorks ... 266
TheCode... 266
Usage... 270
7-2.CapturingPhotoCameraVideoFrames...274
Problem ... 274
Solution ... 275
HowItWorks ... 275
TheCode... 277
CONTENTS
7-3.PickingaPhotofromYourMediaLibrary...284
Problem ... 284
Solution ... 285
HowItWorks ... 285
TheCode... 285
Usage... 287
7-4.AddIntegrationBetweenYourApplicationandWindowsPhone ...289
Problem ... 289
Solution ... 289
HowItWorks ... 289
TheCode... 289
Usage... 291
7-5.UsingMediaPlayertoShuffleSongsinYourMediaLibrary ...294
Problem ... 294
Solution ... 294
HowItWorks ... 295
TheCode... 295
Usage... 302
7-6.PlayingMusicStreamedfromSkyDrive...304
Problem ... 304
Solution ... 304
HowItWorks ... 304
TheCode... 305
Usage... 309
7-7.UsingtheMicrophoneintheFunnyRepeaterApplication ...312
Problem ... 312
Solution ... 312
CONTENTS
TheCode... 313
Usage... 315
7-8.UsingtheMediaElementControltoPlayBothMusicandVideo ...316
Problem ... 316
Solution ... 316
HowItWorks ... 316
TheCode... 317
Usage... 320
7-9.AddingIntegrationwiththeMusic-VideosHub...320
Problem ... 320
Solution ... 320
HowItWorks ... 321
TheCode... 322
Usage... 325
Chapter8:IsolatedStorage ...329
8-1.SavingandLoadingaFileinIsolatedStorage ...330
Problem ... 330
Solution ... 330
HowItWorks ... 330
TheCode... 331
Usage... 334
8-2.SavingSerializedData ...337
Problem ... 337
Solution ... 338
HowItWorks ... 338
TheCode... 338
Usage... 340
CONTENTS
Problem ... 340
Solution ... 340
HowItWorks ... 340
TheCode... 342
Usage... 351
8-4.ModifyingtheSettingsofYourApplication ...351
Problem ... 351
Solution ... 351
HowItWorks ... 351
TheCode... 351
Usage... 355
8-5.SavingaPhotoinIsolatedStorage ...355
Problem ... 355
Solution ... 355
HowItWorks ... 355
TheCode... 355
Usage... 361
8-6.UsingIsolatedStorageExplorer ...364
Problem ... 364
Solution ... 365
HowItWorks ... 365
TheCode... 365
Usage... 366
8-7.ImplementingBackgroundFileTransfer...366
Problem ... 366
Solution ... 366
HowItWorks ... 367
CONTENTS
Usage... 377
Chapter9:IntheCloud ...379
9-1.InteractingwithWCF...379
Problem ... 379
Solution ... 379
HowItWorks ... 379
TheCode... 380
Usage... 385
9-2.AccessingODataServices...385
Problem ... 385
Solution ... 385
HowItWorks ... 385
TheCode... 387
Usage... 390
9-3.CreatingaFeedReader...391
Problem ... 391
Solution ... 391
HowItWorks ... 391
TheCode... 392
Usage... 398
9-4.CreatingaGoogleAPI–basedTranslator...398
Problem ... 398
Solution ... 398
HowItWorks ... 398
TheCode... 398
Usage... 402
9-5.PushingYourNotification...402
CONTENTS
Solution ... 402
HowItWorks ... 402
TheCode... 406
Usage... 414
Chapter10:TestingWindowsPhoneApplications ...417
10-1.ImplementingMVVMonWindowsPhoneUsingMVVMLight...418
Problem ... 418
Solution ... 418
HowItWorks ... 418
TheCode... 420
Usage... 429
10-2.ImplementingMVVMonWindowsPhoneUsingPrism...429
Problem ... 429
Solution ... 429
HowItWorks ... 430
TheCode... 430
Usage... 438
10-3.UsingMVVMandPerformingUnitTesting...440
Problem ... 440
Solution ... 440
HowItWorks ... 441
TheCode... 441
Usage... 443
10-4.UsingApplicationProfiling ...444
Problem ... 444
Solution ... 445
HowItWorks ... 445
CONTENTS
Usage... 445
10-5.FollowingCertificationTestSteps...450
Problem ... 450
Solution ... 450
HowItWorks ... 450
TheCode... 450
Usage... 450
About the Authors
FabioClaudioFerracchiatiisaprolificwriterandtechnicalrevieweroncutting-edgetechnologies.He hascontributedtomanybookson.NET,C#,VisualBasic,SQLServer,Silverlight,andASP.NET.Heisa .NETMicrosoftCertifiedSolutionDeveloper(MCSD)andlivesinRome,Italy.HeisemployedbyBrain Force.
EmanueleGarofalowasbornatTorredelGreco(Naples),Italy,andnowlivesinRome.Heisanactive
memberoftheDotNetCampaniacommunity,andworkswithWindowsPresentationFoundation(WPF), Silverlight,WindowsCommunicationFoundation(WCF),Asp.Net,andLanguageIntegratedQuery (LINQ)asprincipaltechnologies.HeisemployedbyBCSoft.
About the Technical Reviewer
SimonaNasettiisanexpertMicrosoftDynamicsCRMandMicrosoftSQLServerBusinessIntelligence consultant.ShegraduatedwithamathematicsdegreeandworksatAgicTechnology(www.agic.it)in Rome,Italy,whereshecreatesverticalsolutionsandreportsforthecompany’sclients.
Acknowledgments
Firstofall,I’dliketothankEwanBuckingham.Duringtheseyearswehadworkingexperiencestogether andhehasbeenalwayspatient,kind,andhelpful.I’dalsoliketothankEmanueleforthegreatjobhe didworkingwithmetocompletethisbook.Moreover,theApressguys,eachofyouhavebeengreat.So, thankstoJessicaBelanger,DominicShakeshaft,ChristineRicketts,andSharonWilkey.Finally,mywife Simonaforhereffortsespeciallytryingtoquietmydaughter’sscreamswhileIwaswritingthebook.
—FabioClaudioFerracchiati
ThankstoAlessandraforherpatienceduringthewritingofthisbook,toFabiofortheopportunityto writewithhim,toEwan,Jessica,Sharon,andallthestaffofApressfortheirsupport,andtoMichele AponteandalltheDotNetCampaniacommunityforthemotivationtostudynewtechnologieswiththe spiritofknowledge-sharing.
About This Book
AreyouinterestedinWindowsPhoneconfigurationanddevelopment?Learntobuild,configure,and distributeyourapplicationsthroughawidevarietyofstep-by-steprecipes.Thisbookcontainsextensive codesamplesanddetailedwalk-throughs.Moreover,thebookhasbeenupdatedfortheWindows Phone7.1SDKversionandtheWindowsPhone7.5operatingsystem.
Thissecondeditioncoversallthenewfeatures—multitasking,networking,creatinganimated LiveTiles,andmuchmore.Also,therecipeshavebeenupdatedtoshowwhatyouhavetodotoupdate yourapplicationssothattheyworkonthislatestoperatingsystem.
C H A P T E R 1
Introduction to Windows Phone
Application Development
ThischapterintroducesWindowsPhone,includingitsdevicehardwarecharacteristicsandsoftware developmenttools.Afterthisintroduction,youwilllearnhowtocreatesimpleapplicationsandhowto deploythem.Finally,youaregoingtolookattheapplication’sdistributionviaWindowsPhone Marketplace.Therecipesinthischapterdescribehowtodothefollowing:
• 1-1:ExamineWindowsPhonehardware
• 1-2:ExamineWindowsPhonedevelopmenttools
• 1-3and1-4:CreateasimpleWindowsPhoneSilverlightandXNAapplication
• 1-5:CreateasimpleSilverlightandXNAmixedapplication
• 1-6and1-7:DeployaWindowsPhoneapplicationonboththeemulatorand device
• 1-8:PutaWindowsPhoneapplicationintoWindowsPhoneMarketplace
• 1-9:CreateaWindowsPhonetrialapplication
1-1.ExaminingWindowsPhone
Problem
YouhavejustboughtyournewWindowsPhone7deviceandwouldliketostartdevelopingapplications. Youneedtoknowthedevice’shardwarecharacteristics,suchasscreenresolutionandmemory
capability,butalsowhichsensorsandservicesitprovides.Finally,youneedtounderstandwhatthe WindowsPhoneoperatingsystemprovidesinordertointegrateyourapplicationinthebestway.
Solution
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Tomakeanoperatingsystemthatisreliableandfastandhashighperformance,Microsofthas dictatedhardwarerequirements.So,everyWindowsPhone–compatiblephoneonthemarketrightnow andinthefuturehas(orwillhave)atleastminimumcommonhardwarecharacteristics.Forusas developers,thisisgreatnews,becausewecanwritecodehavingsomecertaintyofwhatthesmartphone provides.
TheWindowsPhonedeviceprovidesascreenresolutionof480×800pixelsinportraitorientation.In thefuture,mobilevendorsplantoreleasesmartphoneswithsmallerscreenshavingaresolutionof 320×480pixels.Havingthisinmind,youcancreateagameanddrawyourspritesknowingthatyour gamewillbeplayedonascreenwiththatresolution—sonoscaleoperations,screentextadaptation,and soforthwillbenecessary.Butevenforclassicapplicationsshowing,forexample,textboxesandbuttons, thisresolutionisusefulfordrawingrichuserinterfaces.
Everyphoneprovidesthreehardwarebuttons,usuallyatthebottomofthescreen,asshownin Figure1-1.TheyaretheBackbutton,theStartbutton,andtheSearchbutton.Theleftmostbuttonis usedtogobacktothepreviousapplication(justliketheBackbuttononanInternetbrowser).Moreover, holdingtheBackbuttonforonesecond,WindowsPhoneshowstheapplicationsthatcanberesumed (moreonthisinChapter2).Themiddlebuttonisusedtoclosethecurrentapplicationandtoshowthe Startmenusothattheusercanopenanotherapplication.HoldingtheStartbuttonyoucanusethe WindowsPhonevoicerecognitiontoretrieveandcallacontact,startanapplicationordictateanSMS message.Therightmostbuttonisusedtoaccessthestartscreenandstartasearch.Youcandosimple textsearchingusingBingsiteorsearchsong’sinformationlettingWindowsPhonehearingthesong. Moreover,youcanusetheWindowsPhonecameratoretrieveinformationonitemseitherreadingtheir barcodeorlettingWindowsPhonereadtextanduseMicrosoftTagservice.
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
aroundthislimitation—let’ssaybyinjectingsomeIntermediateLanguage(IL)codeatruntime—you stillhavetorememberthateveryapplicationwillbedistributedbyWindowsPhoneMarketplace.And,of course,beforeuserscanfindyourapplicationonMarketplace,thatapplicationhastogothrough differentapprovalsteps,andyoucanbesurethatanynon-.NETapplicationwouldnotpassthe certificationprocess.
Youcancreatethreekindsofapplications:SilverlightforWindowsPhone,XNAforWindowsPhone, andcombiningbothtechnologiestogether.ThefirstusesacustomSilverlight4versioninwhich Microsofthasaddedsomespecificfeatures.ThesecondusesXNAlibrariesandistargetedatcreating videogames.ThethirdusesaSilverlightandXNAcombination.Usuallythisisgreatsolutionforgames wherethemenuandInternetaccessforscoressharingisaccomplishedbySilverlightcontrolsandthe gameenginewithanimations,music,etc.isdonebyXNA.
Note
IfyouplantoreleaseanapplicationfortheoldWindowsPhone7operatingsystemyouhavetoknowthat
youcancombineSilverlightandXNAtechnologiesinyourapplication,withtheonlylimitationbeingtheuser
interface;youcan’tdrawcontrolsbyusingSilverlightanduseXNAtodrawspritesatthesametime.Ontheother
hand,youcanuseSilverlightfortheuserinterfaceandXNAlibrariestoprovidefullaccesstomediastorageonthe
phone,tocaptureaudio,andmore.
YoucanuseeitherC#orVisualBasictowriteyourWindowsPhoneapplication.
Tostartdeveloping,youfirsthavetodownloadtheWindowsPhoneDeveloperToolsfrom
http://create.msdn.com/en-us/home/getting_started.ThissetupincludesVisualStudio2010Express forWindowsPhone,WindowsPhoneEmulator,SilverlightTools,XNA4,WCFDataServicesClientfor WindowPhone,MicrosoftAdvertisingSDKforWindowsPhone,andMicrosoftExpressionBlendfor WindowsPhone.IfyoualreadyhaveVisualStudio2010installedonyourmachine,thesetupwillinstall onlythenecessaryfilesandyouwillseenewprojecttemplatesthenexttimeyoustartthedevelopment tool.
Let’sseethenecessarystepstoinstalltheMicrosoftWindowsPhoneDeveloperTools:
1. Launchtheinstaller(vm_web.exe)afterhavingdownloadedit.
2. Acceptthelicenseagreement.
3. Optionally,choosetheCustomizedinstallationsoyoucanselectafolderin whichtoinstallthetools.
4. WaitfortheinstallertodownloadallthenecessaryfilesfromtheInternet.The numberoffilesdownloadeddependsonwhattheinstallerfindsalreadyin youroperatingsystem.
5. Ifyouhavetoinstallthedevelopertoolsonmachinesnotconnectedtothe Internet,youcanusetheISOversionfrom
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
1-3.CreatingaSimpleSilverlightWindowsPhoneApplication
Problem
YouhavetocreateaWindowsPhoneapplicationbyusingSilverlight.
Solution
UseVisualStudio2010(eithertheExpress,Professional,orsuperioredition).UsetheWindowsPhone Applicationprojecttemplate.
HowItWorks
AfteropeningVisualStudio2010,youhavetocreateanewproject.FromtheFilemenu,chooseNew ItemProjectitem(orpressCtrl+Shift+N).Figure1-2showsthedialogboxthatappearsafterlaunching theNewProjectcommand.
Figure1-2.VisualStudio2010NewProjectdialogbox
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
• WindowsPhoneApplicationcreatesaskeletoncodeforagenericphone application;nocontrolsorotherstuffareadded.
• WindowsPhoneDataboundApplicationcreatesaWindowsPhoneapplication, addingListandNavigationcontrols.
• WindowsPhoneClassLibrarycreatesaskeletoncodeforanexternalassembly specifictoWindowsPhone.
• WindowsPhonePanoramaApplicationcreatesanapplicationincludingthe Panoramacontrol(seemoreonthatinChapter3,Recipe3-7).
• WindowsPhonePivotApplicationcreatesanapplicationincludingthePivot control(seemoreonthatinChapter3,Recipe3-7).
• WindowsPhoneSilverlightandXNAApplicationcreatesanapplicationthatuses bothSilverlightandXNAtechnologies(seemoreonthatinRecipe1-5).
• WindowsPhoneAudioPlaybackAgentcreatesaclasslibrarywithabackground agenttoplaymusicinbackground(seemoreonthatinChapter8,Recipe8-6).WindowsPhoneAudioStreamingAgentcreatesaclasslibrarywitha backgroundagenttostreamaudio(seemoreonthatinChapter8,Recipe8-6).
• WindowsPhoneScheduledTaskAgentcreatesaclasslibrarywithabackground agenttoperformscheduledtasks(seemoreonthatinChapter2,Recipes2-8,2-9, 2-10).
SelecttheWindowsPhoneApplicationprojecttemplateandtypeSimpleSilverlightApplication intheproject’sNametextbox.ChooseaLocationwhereyouwanttosavetheprojectandthenclickthe OKbutton.
VisualStudio2010willaskyoutoselectthetargetplatformforyournewWindowsPhone application.SelecttheWindowsPhoneOS7.1itemfromthedialogboxandclicktheOKbutton(see Figure1-3).
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Note
VisualStudio2010offersthemulti-targetingfunctionalitythatallowsdevelopertocreateeitherold
WindowsPhone7applicationorthenewWindowsPhone7.1application.Ifyouplantodevelopanapplicationthat
doesn’tusenewfeaturessuchasnetworking,livetiles,etc.,youcanselecttheolderWindowsPhoneOS7.0
versioninordertohaveassurancethatyourapplicationwillrunoneveryphonemountingboththeolderand
neweroperatingsystem.
WaitwhileVisualStudio2010writeseveryfileandfolder,andafterafewsecondsyoushouldhave
MainPage.xamlopenedintheintegrateddevelopmentenvironment(IDE)ofVisualStudio2010(see Figure1-4).
Figure1-4.MainPage.xamlreadytobeedited
TheCode
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
particularphonefeature.Forexample,ifyouwanttousethephonemicrophoneinyourapplication, youhavetoaddtheID_CAP_MICROPHONEcapability.Thefilecomeswithmorethantencapabilitiesalready definedinit;youshouldremovetheonesyoudon’tuse.
Figure1-5.TheclassdiagramfortheAppandMainPageclasses
Let’sfocusourattentiononthemaintwofiles.TheMainPage.xamlfilecontainstheExtensible ApplicationMarkupLanguage(XAML)markupsthatdefinethemainpage.Atthebeginningofthecode, allthenamespacesusedbytheapplicationaredeclared.
<phone:PhoneApplicationPage
x:Class="SimpleSilverlightApplication.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"
….
TheroottagisPhoneApplicationPage,whichistheclassfromwhichourapplicationderives.The prefixphone:isnecessarybecausethePhoneApplicationPagenameisdefinedinthenamespace clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Thex:Classattributestatesthatthe
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
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">
Thenthecodeincludesagridwithtworows.Inthefirstrowisastackpanelwithtwotextblocks, andinthesecondrowisacontentpanelwhereyoucanaddyourcontrols.
<!--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"></Grid> </Grid>
TheotherimportantfileisApp.xamlanditsrelatedcode-behindApp.xaml.csfile.TheApplication roottagrepresentstheclassfromwhichourAppclassderives.Again,thex:Classattributecontainsthe nameofourclassandthenamespaceinwhichitiscontained.Thenamespacesarethesameasthose youhaveseenbefore.The<Application.Resources>markupisusedtoaddcustomresourcestothe application.Butthemostimportantcodesectionistheoneincludedin<Application.
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
<Application
x:Class="SimpleSilverlightApplication.App"
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">
<!--Application Resources--> <Application.Resources> </Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application--> <shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/> </Application.ApplicationLifetimeObjects>
</Application> private void Application_Launching(object sender, LaunchingEventArgs e) {
}
// Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e) {
}
// Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e) {
}
// Code to execute when the application is closing (e.g., user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) {
}
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
IntheInitializePhoneApplicationmethod,RootFrameiscreated.Frameisthetopmostcontrolthat containsphonepages.Itallowspagenavigation,managesorientation,andreservesspaceforthesystem barandapplicationbar.TheNavigatedeventisusedtounderstandwhentheapplicationhascompleted theinitialization.Untilthen,asplashscreenisshown.TheSplashScreenImage.jpgimagewillbeusedas asplashscreen,butyoucancustomizeitorreplaceitwithanotheroneyouprefer.
private void InitializePhoneApplication() {
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again phoneApplicationInitialized = true; }
Finally,intheCompleteInitializePhoneApplicationeventhandler,theRootVisualpropertyissetto
RootFrame.RootVisualisthemainapplicationuserinterface.
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Usage
PressCtrl+F5 (orchooseDebugStartWithoutDebuggingfromthemenu).AfterVisualStudio2010 compilesthecode,theapplicationwillstart.VisualStudio2010willlaunchtheWindowsPhone
Emulatorapplication(unlessyouchangedthetargetfromtherelatedcomboboxthatisWindowsPhone Emulatorbydefault),andyouwillbeabletoseeyourapplicationrunningintheemulator,asshownin Figure1-6.
Figure1-6.SimpleSilverlightforWindowsPhoneapplicationrunningintheemulator
1-4.CreatingaSimpleXNAWindowsPhoneApplication
Problem
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Solution
UseVisualStudio2010(eitherExpress,Professional,orsuperioredition).UsetheWindowsPhoneGame (4.0)projecttemplate.
HowItWorks
PressCtrl+Shift+NafteropeningVisualStudio2010.ThisbringsuptheNewProjectdialogbox.Select theXNAGameStudio4.0templatefromtheInstalledTemplatesontheleftandselecttheWindows PhoneGame(4.0)projecttemplate(seeFigure1-7).TypeSimpleXNAApplicationintheprojectName textboxandthenclicktheOKbutton.
Figure1-7.CreateanewXNAWindowsPhoneapplicationbyusingtheWindowsPhoneGame(4.0) projecttemplate.
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
TheCode
ThemainfileintheprojectisGame1.cs;itcontainsthecodetocreateagameinWindowsPhoneusing theGame1classderivedfromtheGameclass(Figure1-8showsitsownclassdiagram).Theproject templatedoesnothingrelevantotherthancreatingthecodetopaintthescreenwiththeCornflowerBlue color.ButitisworthnotingtheclassstructureanditsmethodstounderstandhowtheXNAgameworks.
Figure1-8.TheGame1andGameclassesdiagram
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
public Game1() {
graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333);
// Extend battery life under lock.
InactiveSleepTime = TimeSpan.FromSeconds(1); }
TheInitializemethodiswhereyouhavetoputthecodetoinitializeyourobjects.
protected override void Initialize() {
// TODO: Add your initialization logic here
base.Initialize(); }
ThenextmethodthatiscalledbytheXNAframeworkisLoadContent.Inthismethod,youhaveto loadthecontentpreviouslyaddedtotheContentprojectinthesolution.Youcanaddimages,sounds, sprites,3Dmodels,andallyourgameresources.
protected override void LoadContent() {
// Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here }
Finally,theXNAgameframeworkentersintoaloopinwhichtwomethodsareautomaticallycalled onebyone—firsttheUpdatemethodandthentheDrawmethod.IntheUpdatemethod,youhavetoadd thecodethatmanagesthegame’slogic,thesprites’movement,acollisionalgorithm,andsoon.The
Drawmethodiswhereyoudrawthegameobjectsandyouhavetobefastertodoit.Yourgamecode shouldn’tupdateandcheckobjectsintheDrawmethod.
protected override void Update(GameTime gameTime) {
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit();
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
base.Update(gameTime); }
protected override void Draw(GameTime gameTime) {
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime); }
Thereisanothermethoddefinedinthecodethatisusedtounloadthecontentwhenthegameis closed.
protected override void UnloadContent() {
// TODO: Unload any non ContentManager content here }
Note
Inthisbook,youwillfindXNAcodeusedtoprovideaccesstoWindowsPhonefeaturessuchasthemedia
libraryandaudiofiles.IfyouareinterestedinWindowsPhonegamedevelopment,takealookat
WindowsPhone7
GameDevelopment
byAdamDawes(Apress,2010).
Usage
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Figure1-9.SimpleXNAApplicationrunningontheWindowsPhoneEmulator
1-5.CreatingaSimpleXNAandSilverlightMixedApplication
Problem
YouneedtocreateanapplicationthatusesbothXNAandSilverlighttechnologiestomanagevisuals.For example,youcouldcreateagamewheremenusandthescoreboardaredonewithSilverlightcontrols andthegameengineandsprites’renderingareaccomplishedbyXNA.
Solution
YoucanusetheVisualStudio2010’sWindowsPhoneSilverlightandXNAApplicationtemplatethat createsacodeskeletonwhereisimplementedtheSharedGraphicsDeviceManagerclass.Thisclass providesstaticmethodsusefultoretrieveareferencetothegraphicdeviceandsotoaccesstoits methodsandproperties.
HowItWorks
AfteropeningVisualStudio2010,youhavetocreateanewproject.FromtheFilemenu,chooseNew ItemProjectitem(orpressCtrl+Shift+N).AsillustratedinFigure1-10,selecttheWindowsPhone SilverlightandXNAApplicationtemplatefromtheNewProjectdialogbox.Specifythe
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Figure1-10.CreateamixedXNAandSilverlightWindowsPhoneapplication.
TheprojectcontentissimilartoaWindowsPhonewithSilverlightprojectbutwithsomeadditions. Firstofall,theprojectcontainsothertwoprojects.OneprojectistheXNAContentprojectusefultostore images,music,sprites,etc.TheotheroneisaWindowsPhoneLibrarythatreferencestheXNAContent library.
ThemainprojectcontainstheApp.xamlandMainPage.xamlpagesasusualbutitcontainseventhe GamePage.xamlpage.TheGamePage.xamlpageiswhereyouhavetoinsertthegamecodeusingthe XNAlibrary.Finally,themainprojectcontainstheAppServiceProvider.csfilewherethe
AppServiceProviderclassisdefined.ThisclassimplementstheIServiceProviderinterfaceandisusefulto addtheIGraphicsDeviceServiceinterfacetotheapplication.
TheCode
ToletaWindowsPhonewithSilverlightapplicationtoaccesstotheXNAgraphicdeviceandtheContent library,wheregraphicandmusicarestored,theAppclasshastoimplementtheIServiceProvider interface.AnobjectthatimplementsthisinterfaceisrequiredbytheContentManagerclassconstructor. TheAppclassprovidestheContentpropertythathastobesetwithanobjectcreatedfromthe
ContentManagerclass.
TheAppServiceProviderclasscontainedintheAppServiceProvider.csfileistheclassthat implementstheIServiceProviderinterface:
public class AppServiceProvider : IServiceProvider {
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
public void AddService(Type serviceType, object service) {
public void RemoveService(Type serviceType) {
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
. . .
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the
<xna:SharedGraphicsDeviceManager />
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
// for certain functionality such as SoundEffect playback. private void FrameworkDispatcherFrameAction(object sender, EventArgs e)
public partial class GamePage : PhoneApplicationPage {
protected override void OnNavigatedTo(NavigationEventArgs e) {
// Set the sharing mode of the graphics device to turn on XNA // rendering
SharedGraphicsDeviceManager.Current.GraphicsDevice. SetSharingMode(true);
// Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new
SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
// Start the timer timer.Start();
base.OnNavigatedTo(e); }
private void OnDraw(object sender, GameTimerEventArgs e) {
SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear( Color.CornflowerBlue);
// TODO: Add your drawing code here }
Finally,theOnNavigatedFrommethodisaddedtothecodeinordertostopthetimerandsetthe SetSharingModeoftheSharedGraphicsDeviceManagertofalse.TheOnNavigatedFrommethodisthe idealplacetospecifythiskindofcodebecausethismethodiscalledjustbeforethepageisbecoming inactive.Indeed,thereisnoneedtohaveaccesstotheXNAgraphicdevicewhenthereisnothingto draw!
protected override void OnNavigatedFrom(NavigationEventArgs e) {
// Stop the timer timer.Stop();
// Set the sharing mode of the graphics device to turn off XNA // rendering
SharedGraphicsDeviceManager.Current.GraphicsDevice. SetSharingMode(false);
base.OnNavigatedFrom(e); }
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Usage
PressCtrl+F5orchooseDebugStartWithoutDebugging.Ifyourcodebuildscorrectly,youwillseeyour applicationrunningintheWindowsPhoneEmulator(seeFigure1-11).
Figure1-11.TheSimpleMixedXNASIApplicationMainPage
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Figure1-12.TheGamePage.xamlpagethatusesXNAtorenderitsowngraphics
1-6.DeployingtheApplicationtotheWindowsPhoneEmulator
Problem
Youhavedevelopedyourapplicationandwanttorunit,butyoudon’thavethephysicaldevice.
Solution
FromVisualStudio2010—withyourphoneprojectloaded—selectWindowsPhoneEmulatorfromthe targetcombobox(seeFigure1-13).
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Usage
PressCtrl+F5orchooseDebugStartWithoutDebugging.Ifyourcodebuildscorrectly,youwillseeyour applicationrunningintheWindowsPhoneEmulator(seeFigure1-14).
Figure1-14.WindowsPhoneEmulator
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Figure1-15.TheAdditionalToolswindow
TheAdditionalToolswindowprovidesthreetabs:Accelerometer,Location,andScreenshot.The accelerometertoolallowsdeveloperstosimulatetheaccelerometersensor.WiththeRecordedData functionalityyoucansimulatephonemovementssuchasthephone’sshake.TheOrientationcombo boxallowsdeveloperstochoosetheinitialphone’sorientation.Bymovingthepinkdotinthemiddleof the3Dphonemodelyoucanrotatethephoneinthe3Dspace.
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Figure1-16.TheLocationtabfromtheAdditionalToolswindow
YoucansearchforalocationbyusingtheSearchtextboxandthenzoominginandoutbyusinglens iconstorefinetheresearch.Clickinginthemapyousetthecurrentlocationandtherelatedwindow’s areaCurrentLocationandPtLatitude/Longitudewillbeupdatedaccordingly.Youcancontinuetoclick onthemaptoaddpointscreatingasortofpaththatcanbesavedonafileandusedinasecondmoment byloadingitwiththeLoad…buttonintheRecordedDatawindow’sarea.
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Note
TheMulti-TouchVistalibraryfromCodePlexenablesuserstousemultiplemicetosimulatefingers.After
installingthismulti-touchdriver,youcantestyourmulti-touchWindowsPhoneapplicationintheemulator.
Downloadthedriverfrom
http://multitouchvista.codeplex.com.
Afterlaunchingtheemulatorforthefirsttime,itisconvenienttonotcloseit.Everychangeyou maketoyourcodeanddeploytotheopenedemulatorwillthenbevisibleandtestable.Withnoneedto reruntheemulator,thedeploymentismuchfaster.
TheemulatorcontainstheworkingversionofInternetExplorer9plustheSettingsapplicationused tochangethephonebackgroundandstyles.
InFigure1-14,youcanseenexttotheemulatoralittlefloatingrectanglewithsomeicons.These buttonsareusedtoclosetheemulator,minimizeit,rotateit,zoomit,andrunadditionaltools.Ifyou choosea100%zoomlevel,youwillseealargeWindowsPhoneemulatoronyourmonitor.That’s becausetheWindowsoperatingsystemassumesthatyourmonitoris96dpi,whiletheWindowsPhone displayhas262DPI.Toenableyoutoseeallthepixelsinyourmonitor,theemulatorshowsaverylarge screen.
1-7.DeployingtheWindowsPhoneApplicationontheDevice
Problem
YouwanttodeployyourapplicationtotheWindowsPhonedevicebecauseyouhavetotestthesensors’ functionalities.
Solution
Youhavetwowaystodeployyourapplicationtothephone:usingeitherVisualStudio2010orthe ApplicationDeploymenttool.
HowItWorks
Inbothcases,youhavetodownloadandinstallthelatestversionofZunesoftwarefrom
www.zune.net/en-US/.Zuneisanentertainmentdevice—initiallyavailableonlyintheUnitedStates— anditisMicrosoft’sresponsetoApple’siPodfamilyofdevices.Youcantransferyourmusicandvideos byusingtheZunesoftware,butyoucanuseittodeployyoursoftware,too.
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Figure1-17.TheWindowsPhoneDeveloperRegistrationtoolusedtounlockyourphoneanddeploy applications
Note
AsyoucanseeinFigure1-17,ZunesoftwareisrequiredtounlocktheWindowsPhone7device.
Okay,aftercompletingthesemandatorysteps,yourdeviceisreadytoreceiveyourapplication. FromVisualStudio2010,yousimplyhavetochangethetargetcomboboxfromWindowsPhone EmulatortoWindowsPhoneDevice.
Usage
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
Note
TheWindowsPhoneDeveloperToolsincludesthe
WPConnect.exeprogram.Whenyourapplicationuses
theWindowsPhonemedialibraryorplaysasong,itwillfindthoseresourceslockedbyZunesoftware.Youhaveto
closeZunesoftwareafterhavingconnectedthephoneandthenrun
WPConnect.exe.Thedevicewillremain
connected,butnowyouhavefullaccesstothephonedevice.
ThesecondmethodtodeployyourapplicationontheWindowsPhonedeviceistorunthe ApplicationDeploymenttool(seeFigure1-18).
Figure1-18.TheApplicationDeploymenttoolusedtodeployyourapplicationwithoutVisualStudio2010
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
• Theapplicationmustshowthefirstscreenwithin5seconds.Asyouhaveseenin Recipe1-3,theSilverlightWindowsPhoneapplicationprovidesasplashscreen,so youmightthinkthatthisruleisalwayssatisfied.Sadly,itisnot,becausethesplash screenmustdisappearwithin5seconds,andthemainpagehastoberendered.If yourapplicationtakeslonger,youcanimplementasplashscreenwithaprogress bar,asshowninChapter3,Recipe3-1.Theusermustuseyourapplicationwithin 20seconds.
• Theapplicationmustrespondcorrectlytoexecutionmodelevents.Whentheuser pressestheStartbutton,theWindowsPhoneapplicationshouldbedeactivated; whentheuserpressestheBackbuttonandcomesbacktoyourapplication,it shouldbeactivatedandshouldshowthesamescreeninformationthatitwas runninginthebackground.Chapter2iscompletelydedicatedtotheexecution modelandapplicationtombstoning.
• Theapplicationmustbeusablewiththephone’stemplates,darkandlight.Soif youhaveimagesorothergraphicseffectsworkingwellinonetemplate,youhave toimplementanalgorithmtoreplacethemiftheuserchangesthephone’s template.
Note
Thereisaninterestingarticleat
http://blogs.msdn.com/b/devfish/archive/2010/10/06/ben-s-big-ten-for-wp7-marketplace-acceptance.aspxthathighlightsthetenmostimportantrulesthatyouhaveto
satisfysothatyourapplicationpassestheacceptanceprocess.
VisualStudio2010providestheMarketplaceTestkitthatallowsdevelopertotesttheapplicationin thesamewaytheMarketplaceacceptancephaseanalyzestheapplicationaftertheapplication
submitting.SeemoreonthisinChapter11,Recipe11-5.
1-9.CreatingaTrialWindowsPhoneApplication
Problem
Youwanttodistributeanapplicationthatprovidesatrialversion.Also,youwantyourapplicationto reminduserstobuythefullversion.
Solution
YouhavetousetheGuideclassfromtheGamerServicesnamespace,whichprovidespropertiesand methodsenablingyoutocheckwhetheryourapplicationisrunningintrialversionmode.Moreover,the
CHAPTER1INTRODUCTIONTOWINDOWSPHONEAPPLICATIONDEVELOPMENT
HowItWorks
Microsoftagainhelpsdevelopers:Marketplaceimplementsafeatureenablinguserstochoosebetweena trialversionandafullversionofyourapplication.Asadeveloper,youdon’thavetoprovidetwoversions ofyoursoftware,butsimplycheckyourcodetoseewhethertheapplicationisrunningintrialmode.In fact,whentheuserchoosestoinstallthetrialversionofyourapplication,Marketplaceaddsatrial licensefiletothedirectorywheretheapplicationisinstalled.Iftheuserdecidestobuytheapplication afterhavingtriedit,Marketplacereplacesthetriallicensewithafulllicense.
Dependingontheframeworkchosentowriteyourapplication,eitherXNAorSilverlight,thereare differentwaystocheckwhethertheapplicationisrunningintrialmode.TheXNAframeworkprovides theGuideclasscontainedintheGamerServicesnamespace(seeFigure1-19fortheGuideclassdiagram). TheSilverlightframeworkprovidestheLicenseInformationsealedclasswiththeIsTrialmethod.
Figure1-19.TheGuideclassdiagram