Windows phone 8 application development essentials

118 70 0
Windows phone 8 application development essentials

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info Windows Phone Application Development Essentials A practical guide to creating a Windows Phone application using C#, XAML, and MVVM Tomasz Szostak BIRMINGHAM - MUMBAI www.it-ebooks.info Windows Phone Application Development Essentials Copyright © 2013 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information First published: October 2013 Production Reference: 1101013 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-84969-676-0 www.packtpub.com Cover Image by Jarosław Blaminsky (milak6@wp.pl) www.it-ebooks.info Credits Author Project Coordinator Tomasz Szostak Joel Goveya Reviewers Proofreader Deep Shah Stephen Copestake Melania Andrişan (Danciu) Production Coordinator Waldemar Sudoł Conidon Miranda Acquisition Editor Cover Work Saleem Ahmed Conidon Miranda Commissioning Editors Maria D'souza Llewellyn F Rozario Technical Editors Vrinda Nitesh Bhosale Amit Shetty Copy Editors Lavina Pereira Mradula Hegde Brandt D’Mello Gladson Monteiro www.it-ebooks.info About the Author Tomasz Szostak is a Senior Software Developer in an international corporation On a daily basis, he delivers software for nuclear facilities; however, in his spare time, he becomes a mobile-application-fascinated developer He is in love with the best practices in creating software He has been working on the development of Windows Phone application since the very first version of WP SDK was released He is the author of tens of Windows Phone market applications with some successes; he runs a dev blog and actively works on self-development I would like to thank my wife Monika for the patience and support she showed while I was writing this book www.it-ebooks.info About the Reviewers Deep Shah is a cofounder and director at InformationWorks (www.informationworks.in) He received his B.E in Computer Engineering from Pune University, Pune, in 2008 and his M.S in Information Management from Syracuse University, New York, in 2011 He was also a research assistant to Prof Kevin Crowston on the Flossmole project (http://flossmole.org/) and has taught enterprise technologies, such as Mainframes, as a teaching assistant at Syracuse University Deep is a passionate web and mobile app developer During his stay in the United States, he had interned and worked as a web developer for the likes of J.P Morgan Chase, Sidearm Sport (http://www.sidearmsports.com/), Think60 (http://www think60.net/), and so on He is now a cofounder at InformationWorks and is the lead developer of Android and iOS app: • CATapp (https://play.google.com/store/apps/details?id=in informationworks.app.CATapp) • Vedic Math India (https://play.google.com/store/apps/ details?id=in.informationworks.app.vedicmath) • What’s The Word (https://play.google.com/store/apps/ details?id=in.informationworks.app.WTW) Deep has been a NET developer for more than five years and has worked on various NET technologies such as WPF, XAML, LINQ, WinForms, ASP.NET, and so on He actively follows the Windows Phone development technologies and is in the process of developing all their existing applications for Windows Phone www.it-ebooks.info Melania has worked using Microsoft technologies since being a student in college and with mobile products since the introduction of Windows Phone to the market She worked on many projects as part of the product development and architecture teams for some large companies in Europe Since being in college, she’s started activating in the community having presented at some of the best known regional conferences: DevReach, DevSum, and ITCamp Waldemar Sudoł is a senior software developer running his own business and cooperating with international corporations He develops software for many OSes in NET technology, mostly specialized in mobile and web solutions He develops apps for Windows Phone application from the beginning of the platform He is the author of tens of Windows Phone market applications He also developed the Windows Store apps He’s interested in Net technologies and Windows Store apps www.it-ebooks.info www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library Here, you can access, read and search across Packt’s entire library of books Why Subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books Simply use your login credentials for immediate access www.it-ebooks.info www.it-ebooks.info Table of Contents Preface 1 Chapter 1: XAML in Windows Phone Types of XAML objects Navigation 6 PhoneApplicationFrame 6 PhoneApplicationPage 7 Containers 7 Canvas 7 Border 7 Grid 7 Panorama 7 Pivot 8 ScrollViewer 8 StackPanel 8 List controls Common controls ListBox 8 LongListSelector 8 ApplicationBar 9 Button 9 CheckBox 9 HyperlinkButton 9 Image 9 MediaElement 10 MultiScaleImage 10 PasswordBox 10 Popup 10 MessageBox 10 RadioButton 10 RichTextBox 10 Slider 11 TextBlock 11 TextBox 11 www.it-ebooks.info Chapter When you are done with configuring the Twitter application, get the consumer key and consumer secret key that you should put in your application to get the access token from Twitter [ 91 ] www.it-ebooks.info Integrating with Twitter and Facebook Once we have the consumer key and consumer secret key, we can create static variables that will keep these values in the application—we are going to use that in our Twitter communication The Twitter API uses the OAUTH standard (http:// oauth.net/) The next thing to is to download and reference TweetSharp in our project; for this, we have to execute the following Nuget console line: PM> Install-Package TweetSharp Once we reference the TweetSharp project, we can proceed with creating functionality for logging in and getting profile information Of course, there are many more features available in TweetSharp, which are listed as follows: • Getting direct messages • Getting followers • Getting tweets • Sending tweets The implementation of these features is demonstrated next Before we start with creating the new application page to log in to Twitter, we should create additional fields in our ViewModel class, such as TwitterUserName and myTwitterPhoto in MainViewModel These variables will keep information about our account Other fields that should be added are static fields that will be used to manage calls to the Twitter service This is demonstrated in the following code snippet: public static readonly string "YourConsumerSecret"; public static readonly string "YourSecretKey"; public static readonly string "YourCallbackUrl"; public static readonly string "TwitterSession"; TwitterConsumerKey = TwitterSecretKey = TwitterCallbackUrl = TwiterSessionObjectKey = The Twitter session static key will be used to read and save the Twitter authentication token to log in to the application once and use this session First of all, we need to add a new application page in the Views folder; we need to handle Twitter logging in in the WebBrowser control (this allows us to display HTML and browse the Internet) and handle events in the code behind; so it will make our clean code a bit ugly Our new page should inherit from ApplicationPageBase to support sending and receiving messages In page constructor, we will call the LoginToTwitter method: private void LoginToTwitter() { [ 92 ] www.it-ebooks.info Chapter twitterService = new TwitterService( Statics.TwitterConsumerKey, Statics.TwitterSecretKey); twitterService.GetRequestToken( Statics.TwitterCallbackUrl, CallBackToken); } This is why we need static fields that keep Twitter settings, so that we can check it in the Twitter application The GetRequestToken method requests authentication using the CallBackToken method, which navigates the WebBrowser control to the authentication URI private void CallBackToken(OAuthRequestToken rt, TwitterResponse response) { if (response.StatusCode == HttpStatusCode.Unauthorized) { return; } Uri uri = twitterService.GetAuthorizationUri(rt); requestToken = rt; webBrowser.Dispatcher.BeginInvoke(() => webBrowser.Navigate(uri)); } Execution of the preceding code causes it to display the login page in the WebBrowser control The login page contains a list of rights that will be required to use applications—these rights should be set in the Twitter for the developers' part while defining or editing applications Usually, Twitter authentication works in the following way: Enter username and password If the authentication succeeds, the page with the verification key will be displayed The user copies the verification key and goes back to application to authenticate We want to create as simple a mechanism as possible, without forcing the user to enter any code We can it in the following way: Enter the username and password If the authentication succeeds, a callback URL with the verification code is captured and parsed [ 93 ] www.it-ebooks.info Integrating with Twitter and Facebook We get the access token To implement the preceding approach, we should handle the OnNavigating WebBrowser event as shown in the following code snippet: private void WebBrowser_OnNavigating( object sender, NavigatingEventArgs e) { if (e.Uri.ToString().Contains( Statics.TwitterCallbackUrl + "?oauth_token")) { var cb = new Action(CallBackVerifiedResponse); var values = ParseQueryString(e.Uri.AbsoluteUri); string verifier = values["oauth_verifier"]; twitterService.GetAccessToken( requestToken, verifier, CallBackVerifiedResponse); } } [ 94 ] www.it-ebooks.info Chapter The preceding code captures all URLs that are passed through the WebBrowser control and looks for the authentication code If it finds the verification code, it passes it to the GetAccessToken method When the method execution is completed, it fires the CallBackVerifiedResponse method, which takes the authentication token and the response object private void CallBackVerifiedResponse( OAuthAccessToken at, TwitterResponse response) { if (at != null) { AccessToken = at.Token; if (string.IsNullOrEmpty(AccessToken)) { //failed return; } AccessTokenSecret = at.TokenSecret; DispatcherHelper.UIDispatcher.BeginInvoke(() => { SaveTwitterSessionObject(at,new StorageSettingsProvider()); var msg = new TwitterAuthenticationMessage(); msg.IsAuthenticated = true; Messenger.Default.Send(msg); Messenger.Default.Send(new Uri("/MainPage.xaml", UriKind.Relative), "NavigationRequest"); }); } } The CallBackVerifiedResponse method saves the authentication token to settings storage for later use The next message informs MainViewModel that the authentication succeeded and the page is redirected to MainPage The MainViewModel class receives the message that the authentication is done, and gets information about our profile from Twitter As you can see in the following code, having the authentication token work with TweetSharp becomes very easy: private void updateTwitterUserInfo (OAuthAccessToken TwitterToken) { var service = new TwitterService( Statics.TwitterConsumerKey, Statics.TwitterSecretKey); [ 95 ] www.it-ebooks.info Integrating with Twitter and Facebook service.AuthenticateWith(TwitterToken.Token, TwitterToken.TokenSecret); service.GetUserProfile(new GetUserProfileOptions() { IncludeEntities = false, SkipStatus = false }, (user, reponse) => DispatcherHelper.UIDispatcher.BeginInvoke( ()=> { TwitterUserName = user.Name; myTwitterPhoto = new BitmapImage( new Uri(user.ProfileImageUrl)); })); } The main part of the preceding code is the GetUserProfile method that enables us to get our Twitter profile information, and then the return data that can be set to appropriate fields The preceding example shows us how to use the lambda expression (http://msdn.microsoft.com/en-us/library/vstudio/bb397687 aspx) instead of creating a new method that handles the callback Getting other information from Twitter and sending tweets can be implemented similarly The code available for this chapter creates foundations for the application that can be submitted to the app hub Summary In this chapter, we have taken our first steps towards enabling social media in our application We learned how to create a Facebook application and use its Graph API, how to implement TweetSharp in our application, and how to register a Twitter application The code samples available for this chapter will explore the basic tasks in social portal usage [ 96 ] www.it-ebooks.info Index Symbols [TestClass] attribute 67 [TestMethod] attribute 67 A Add method 73 Address chooser 82 API settings 73, 74 Application_Activated method 38 application bar 25, 26 ApplicationBar Application_Launching handler method 38 application tile updating, from code 77, 78 async keyword 75 await keyword 75 B background agent about 78-80 PeriodicTask 78 Resource-intensive agent 79 BackgroundTaskManager class 80 binding about 39, 44 commands, exposing 50 data templates 52, 53 direct method calls 51 model 44, 45 model/property changes, wrapping 48, 49 MVVM communication 47, 48 View 46, 47 ViewModel 45, 46 binding expressions 13, 14 binding modes about 15 OneTime 15 OneWay 15 TwoWay 15 Border btnCount button 58 Button 9, 30 C CallBackToken method 93 CallBackVerifiedResponse method 95 CanExecute method 50 Canvas CheckBox 9, 30 choosers about 82, 83 Address chooser 82 E-mail address chooser 82 Gallery photo chooser 83 ChosenPhoto property 83 code application tile, updating from 77, 78 CodePlex URL 12 Command object 50 CommandParameter attribute 50 Containers Border Canvas Grid Panorama Pivot ScrollViewer StackPanel www.it-ebooks.info Contains method 73 Content property context menus 26 controls ApplicationBar Button CheckBox HyperlinkButton Image MediaElement 10 MessageBox 10 MultiScaleImage 10 PasswordBox 10 Popup 10 RadioButton 10 RichTextBox 10 Slider 11 TextBlock 11 TextBox 11 ToggleButton 11 WebBrowser 11 Convert 15 ConvertBack 15 CreateFileAsync 75 CreateFolderAsync 75 CurrentUser property 46 CycleTileData 77 D data working with 13 DataContext property 14, 39 DataContract attribute 76 DataContractSerializer class 77 DataMember attribute 76 data templates about 52, 53 value converters 54-56 Deep Zoom 10 DeleteAsync 74 Description property 80 details, navigation 22 developer account creating, URL 85 direct method calls 51 E elememt size guidelines 27 ElementName property 14 element-to-element data binding 14 E-mail address chooser 82 E-mail composing 81 Execute method 50 Extensible Application Markup Language See  XAML F Facebook Graph API, using 86, 87 SDK integration 87-90 FacebookClient class 87 FacebookClient object 88 Fail 66 file reading 75 writing 76 file API about 74 file, reading 75 file, writing 76 folder, creating 76 serializable classes, reading 76, 77 serializable classes, writing 76, 77 FindMessagesThatContain method 66 flat navigation 20 FlipTileData 77 folder creating 76 folder structure 39 fonts, UI/UX 33 G Gallery photo chooser 83 GetAccessToken method 95 GetCompleted event handler 88 GetRequestToken method 93 GetTaskAsync method 88 GetUserProfile method 96 [ 98 ] www.it-ebooks.info golden circle 18 GotoSettingsPage command 63 Graph API used, in Facebook 86, 87 Grid grid system, UI/UX 29 H hierarchical navigation 21, 22 hyperlink sharing 82 HyperlinkButton 9, 30 I IconicTileData 78 Image Image control size 30 INotifyPropertyChanged 15 IsLoading property 41, 49 IsoCode property 14 Isolated storage 72 IsOpen property 10 K key-value pair 73 L launchers about 81, 82 E-mail composing 81 hyperlink, sharing 82 Maps task 81 Phone call 81 Review 82 SMS composing 81 Web browser task 82 LayoutMode property list binding 16 ListBox 8, 30 list controls ListBox LongListSelector LoginAsync method 88 LoginToTwitter method 92 LongListSelector 8, 32 M MainPage class 62 MainViewModel class 87, 95 MainViewModel property 64 Maps task 81 MediaElement 10, 30 me/feed command 86 MessageBase class 60 MessageBox 10 MessageBox object 51 messaging 59-61 Model 40, 41 Model class 40, 44, 45, 90 model/property changes wrapping 48, 49 MultiScaleImage 10 MVVM about 12 disadvantage 57 page, navigating with 61-63 MVVM communication 47, 48 MVVM Light Toolkit about 56 messaging 59-61 obtaining 56-58 unit testing 65-68 URL 56 ViewModel locator 63, 64 MyFriendsList property 53 N Navigate method Navigation details 22 flat navigation 20 hierarchical navigation 21, 22 Panorama 24 PhoneApplicationFrame PhoneApplicationPage pivot navigation 22, 23 notifications, UI/UX 34, 35 [ 99 ] www.it-ebooks.info O S OAUTH standard URL 92 Observable class 41 OneTime 15 OneWay 15 OnFbOnGetCompleted method 88 OnInvoke method 79 OnPropertyChanged method 49 OpenStreamForReadAsync 75 OpenStreamForWriteAsync 75 Orientation property SampleModel class 43 Save button 60 Save method 73, 74 ScheduledAgent class 79 ScrollViewer 8, 32 selectedItem property 49 serializable classes reading 76, 77 writing 76, 77 settings method 73 SettingsViewModel class 60 ShellToast object 81 ShowMessage method 51 Show() method 82, 83 Slide 27 Slider 11 Slider control 32 SMS composing 81 SociAgg creating 69 SocialBL class 89 Source property 11 StackPanel StandardTileData 78 Summary object 90 Sum property 58 swipe for application commands 27 P Panorama 7, 24 Panorama control 31 Pass 65 PasswordBox 10 PeriodicTask 78 PhoneApplicationFrame PhoneApplicationPage Phone call 81 Pivot 8, 31 pivot navigation 22, 23 Play button 65 Popup 10 Press-and-hold on item 26 ProgressBar 32 project structure 38, 39 PropertyChanged event 41 R RadioButton 10 RadioButton control 32 RaisePropertyChange method 58 ReadTextFile() 75 RelayCommand class 57 RelayCommand object 58 Remove method 73 RenameAsync 74 Resource-intensive agent 79 Review in marketplace 82 RichTextBox 10 RunPeriodicTask method 80 T Tap on item 26 TED (Technology, Entertainment, Design) 18 TextBlock 11 TextBlock control 32 TextBox 11, 32 Text property 14 Third-party controls Windows Phone Toolkit 12 tiles notification application tile, updating from code 77, 78 implementing 77 tiles, UI/UX 34 tile templates 35 Toast notifications 81 [ 100 ] www.it-ebooks.info W ToggleButton 11 touch events Press-and-hold on item 26 Slide 27 swipe 27 Tap on item 26 Twitter integration 90-96 TwoWay 15 WebBrowser 11 Web browser task 82 Windows Phone application elememt size 27 gestures 26, 27 touch 26, 27 Windows Phone application branding in 27, 28 Windows Phone Toolkit 12 U UI/UX, principles fast and fluid 28 fonts 33 grid system 29 notifications 34, 35 tiles 34, 35 UnhaltedException event 39 unit testing 65-68 UpdateFlipTile method 78 User controls 11, 12 UserModel class 45 X XAML 5, XAML objects common controls Containers list controls Navigation Third-party controls 12 User controls 11 V Z value converters 15, 54-56 value parameter 55 view 39, 46, 47 ViewModel 41-46 ViewModel class 59, 89 ViewModel locator 63, 64 ViewModeLocator class 63 ViewModel property 47, 54 View's Model (VM) See  ViewModel Visibility property 56 ZIndex property [ 99 ] www.it-ebooks.info www.it-ebooks.info Thank you for buying Windows Phone Application Development Essentials About Packt Publishing Packt, pronounced 'packed', published its first book "Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks Our solution based books give you the knowledge and power to customize the software and technologies you're using to get the job done Packt books are more specific and less general than the IT books you have seen in the past Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't Packt is a modern, yet unique publishing company, which focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike For more information, please visit our website: www.packtpub.com Writing for Packt We welcome all inquiries from people who are interested in authoring Book proposals should be sent to author@packtpub.com If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, contact us; one of our commissioning editors will get in touch with you We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise www.it-ebooks.info Developing Windows Store Apps with HTML5 and JavaScript ISBN: 978-1-849687-10-2 Paperback: 184 pages Learn the key concepts of developing Windows Store apps using HTML5 and JavaScript Learn about the powerful new features in HTML5 and CSS3 Quick start a JavaScript app from scratch Get your app into the store and learn how to add authentication Microsoft Windows PowerShell 3.0 First Look ISBN: 978-1-849686-44-0 Paperback: 200 pages A quick, succinct guide to the new and exciting features in PowerShell 3.0 Explore and experience the new features found in PowerShell 3.0 Understand the changes to the language and the reasons why they were implemented Discover new cmdlets and modules available in Windows and Server Quickly get up to date with the latest version of Powershell with concise descriptions and simple examples Please check www.PacktPub.com for information on our titles www.it-ebooks.info Mastering Windows C++ App Development ISBN: 978-1-849695-02-2 Paperback: 304 pages A practical guide to developing Windows Store apps with C++ and XAML Details the most important features of C++, XAML, and WinRT for building fantastic Windows Store apps Full of detailed and engaging code samples that can be used as a basis for your own projects Provides a clear overview of Windows Runtime and C++/CX Microsoft NET Framework 4.5 Quickstart Cookbook ISBN: 978-1-849686-98-3 Paperback: 226 pages Get up to date with the exciting new features in NET 4.5 Framework with these simple but incredibly effective recipes Designed for the fastest jump into NET 4.5, with a clearly designed roadmap of progressive chapters and detailed examples A great and efficient way to get into NET 4.5 and not only understand its features but clearly know how to use them, when, how, and why Covers Windows XAML development, NET Core (with Async/Await and reflection improvements), EF Code First and Migrations, ASP.NET, WF, and WPF Please check www.PacktPub.com for information on our titles www.it-ebooks.info .. .Windows Phone Application Development Essentials A practical guide to creating a Windows Phone application using C#, XAML, and MVVM Tomasz Szostak BIRMINGHAM - MUMBAI www.it-ebooks.info Windows. .. XAML in Windows Phone Types of XAML objects Navigation 6 PhoneApplicationFrame 6 PhoneApplicationPage 7 Containers 7 Canvas 7 Border 7 Grid 7 Panorama 7 Pivot 8 ScrollViewer 8 StackPanel 8 List... Touch in the Windows Phone application 26 Touch and gestures 26 Target size guidelines 27 Branding in the Windows Phone application 27 Simplicity is not bad! 28 Principles for UI/UX 28 Being fast

Ngày đăng: 12/03/2019, 14:59

Mục lục

  • Cover

  • Copyright

  • Credits

  • About the Author

  • About the Reviewers

  • www.PacktPub.com

  • Table of Contents

  • Preface

  • Chapter 1: XAML in Windows Phone

    • Navigation

      • PhoneApplicationFrame

        • PhoneApplicationPage

        • Containers

          • Canvas

          • Border

          • Grid

          • Panorama

          • Pivot

          • ScrollViewer

          • StackPanel

          • List controls

            • ListBox

            • LongListSelector

            • Common controls

              • ApplicationBar

              • Button

Tài liệu cùng người dùng

Tài liệu liên quan