Xem mẫu

  1. Microsoft Silverlight 5 Data and Services Cookbook Download from Wow! eBook Over 100 practical recipes for creating rich, data-driven, business applications in Silverlight 5 Gill Cleeren Kevin Dockx BIRMINGHAM - MUMBAI
  2. Microsoft Silverlight 5 Data and Services Cookbook Copyright © 2012 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 authors, 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 Edition: April 2010 Second Edition: April 2012 Production Reference: 2130412 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84968-350-0 www.packtpub.com Cover Image by David Gimenez (bilbaorocker@yahoo.co.uk)
  3. Credits Authors Project Coordinator Gill Cleeren Vishal Bodwani Kevin Dockx Proofreaders Chris Smith Reviewers Josh Toth Mario Van Hissenhoven Evan Hutnick Indexers Kris van der Mast Tejal Daruwale Dennis Miscoria Monica Ajmera Mehta Graphics Acquisition Editor Manu Joseph Kerry George Lead Technical Editor Production Coordinator Hyacintha D'Souza Nilesh Mohite Technical Editors Cover Work Ankita Shashi Nilesh Mohite Manasi Poonthottam Sakina Kaydawala
  4. About the Authors Gill Cleeren is a Microsoft Regional Director, Silverlight MVP (former ASP.NET MVP), and Telerik MVP. He lives in Belgium where he works as .NET architect at Ordina. Passionate about .NET, he's always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts, and trainings on new as well as existing technologies, such as Silverlight, ASP.NET, and WPF at conferences including TechEd Europe, TechDays Belgium—Switzerland—Sweden, DevDays NL, NDC Oslo Norway, Silverlight Roadshow in Sweden, Telerik RoadShow UK, and so on. He organizes the yearly Community Day event in Belgium and leads Visug, the largest .NET user group in Belgium. You can find his blog at www.snowball.be and on Twitter, you can follow him via @gillcleeren. Gill published his first book, Silverlight 4 Data and Services Cookbook, with Packt Publishing. He also authored a chapter for Real World .NET, C#, and Silverlight: Indispensible Experiences from 15 MVPs and also authored numerous articles and eBooks for SilverlightShow.net. After the publication of my first book with Packt, I was very happy with its success. It quickly got a lot of positive reviews on blogs and sites such as Amazon. This was for me the trigger to start writing again. What you're holding here is another year's work of two devoted people who love developing applications with Silverlight and want to share that love with you. Reading it will certainly help you figure out complex problems that you may encounter in your life as a Silverlight developer. Or maybe more generally as an XAML developer, since most of the content can be used in all places where XAML is used as the development language. Of course, this book is not the work of only the authors. Without the team at Packt and the reviewers, it wouldn't even be possible to complete such a project. And of course, without the patience and love of my girlfriend (and wife-to-be from September 2012) and my mother, I wouldn't be able to walk into a bookstore and be able to hold my work in my hands!
  5. Kevin Dockx lives in Belgium and works at RealDolmen, one of Belgium's biggest ICT companies, where he is a 30-year old technical specialist/project leader on .NET web applications, mainly Silverlight, and a solution manager for Rich Applications (Silverlight, Windows Phone 7, WPF, Surface, HTML5). His main focus lies on all things Silverlight, but he still keeps an eye on the new developments concerning other products from the Microsoft .NET (Web) Stack. As a Silverlight enthusiast, he's a regular speaker at various national and international events, like Microsoft DevDays in The Netherlands, Microsoft Techdays in Portugal, BESUG events (the Belgian Silverlight User Group), Simplicity Day, Community Day, and so on. Next to that, he also writes articles for various Silverlight-related sites. His blog, which contains various tidbits on Silverlight, .NET, and the occasional rambling, can be found at http://blog.kevindockx.com/, and you can contact him on Twitter via @KevinDockx. He has worked on other books like Silverlight 4 Data and Services Cookbook (Packt Publishing). He has also worked on various articles and ebooks for SilverlightShow.net and other Silverlight-related sites. I could come up with a long list of people I'd like to thank, and with a bunch of reasons to write this book. But I guess it all boils down to one thing: passion. Passion for technology. Passion to share knowledge. And passion for the next big thing. So I'm going to keep this short: one quote, that's all there is to it: "Wandering along the lines of another next big thing, remember: there's always room for more ice cream."
  6. About the Reviewers Mario Van Hissenhoven is a certified Microsoft SQL Server Professional with more than 10 years of experience. His specialties are development in transact SQL. Mario also has extended his knowledge to the .NET framework 2.0, 3.0, and 3.5 during the last 5 years. His interest has always been to be on top of the new Microsoft technologies such as Silverlight, WCF, and SQLCLR. Nowadays, Mario is focusing on SQL Server 2008R2 Development and the Beta features of SQL Server 2012. I would like to thank my wife and kids for the time spent on reviewing this book while I should have been spending time with them. And I promise I will make it up to them. Evan Hutnick is a Developer Evangelist working for Telerik in the XAML space covering Silverlight, WPF, Windows Phone, and the up-and-coming WinRT platform. Evan is also a Silverlight MVP and recognized throughout the community for his contributions on best practices, designer/developer concepts, as well as general architecture guidance. While focusing on XAML technologies, Evan often specializes in enterprise development scenarios and best practices for solution structure and architecture. I thank my wife Jennifer and my daughter Keira for tolerating my insane love of technology and for putting up with the long hours and late nights, I couldn't do it without them.
  7. Kris van der Mast is a Microsoft MVP since 2007, Microsoft ASP Insider, and a respected member and moderator on the official ASP.NET forums where he ranks at the number one position. After he became an engineer he followed an extensive path into the magical world of web. Besides his work, Kris plays a very active role in the community by delivering articles for magazines, being a board member of the Belgian Windows Azure user group (www.azug.be), presenting or teaching about the latest (web) technologies. More recently Kris became a part of MEET (Microsoft Extended Experts Team). You can follow him on Twitter via @KvdM or his blog at http://blog.krisvandermast. com to find out about Windows Azure, ASP.NET (MVC), WebMatrix, jQuery, Orchard CMS, and so on. Dennis Miscoria is an enthusiastic .NET developer living in Belgium. Over the past six years, he has built up an extensive knowledge in the mobile world starting from the Compact Framework up to the latest Windows Phone and Silverlight technology. Dennis is currently working for the Belgian consultancy company Ordina (www.ordina.be) as senior .NET engineer. Due to his mobile background, he is also in charge of the .NET Mobile Competence Center.
  8. 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. 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 f Copy and paste, print and bookmark content f On demand and accessible via web browser f 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. Instant Updates on New Packt Books Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.
  9. Table of Contents Preface 1 Download from Wow! eBook Chapter 1: Learning the Nuts and Bolts of Silverlight 5 7 Introduction 7 Getting our environment ready to start building Silverlight applications 8 Creating our first service-enabled and data-driven Silverlight 5 application using Visual Studio 2010 10 Using the workflow between Visual Studio 2010 and Blend 5 20 Using source control in Visual Studio 2010 and Blend 5 29 Deploying a Silverlight application on the server 32 Chapter 2: An Introduction to Data Binding 37 Introduction 37 Displaying data in Silverlight applications 40 Creating dynamic bindings 49 Binding data to another UI element 52 Binding collections to UI elements 56 Enabling a Silverlight application to automatically update its UI 60 Obtaining data from any UI element it is bound to 68 Using the different modes of data binding to allow persisting data 73 Debugging data binding expressions in Visual Studio 77 Data binding from Expression Blend 5 81 Using Expression Blend 5 for sample data generation 84 Chapter 3: Advanced Data Binding 87 Introduction 87 Hooking into the data binding process 88 Replacing converters with Silverlight 5 BindingBase properties 93 Validating data-bound input 97 Validating data input using attributes 101
  10. Table of Contents Validating using IDataErrorInfo and INotifyDataErrorInfo 104 Using templates to customize the way data is shown by controls 109 Using implicit data templates 1 15 Using the Ancestor RelativeSource binding 119 Creating custom markup extensions 123 Building a change-aware collection type 127 Combining converters, data binding, and DataContext into a custom DataTemplate 130 Chapter 4: The Data Grid 139 Introduction 139 Displaying data in a customized DataGrid 140 Inserting, updating, and deleting data in a DataGrid 146 Sorting and grouping data in a DataGrid 151 Filtering and paging data in a DataGrid 156 Using custom columns in the DataGrid 160 Implementing master-detail in the DataGrid 167 Validating the DataGrid 171 Chapter 5: Working with Local Data 175 Introduction 175 Reading data from and storing data in the isolated storage 176 Working with IsolatedStorageSettings 186 Caching data between different Silverlight applications using isolated storage 190 Using the Sterling database 192 Chapter 6: MVVM 205 Introduction 205 Creating a basic MVVM application 206 Using MVVM Light to enable MVVM applications 214 Connecting a View to a ViewModel using a ViewModelLocator 219 Connecting a View to a ViewModel using MEF 224 Using commands to pass your events to the ViewModel 229 Communicating between different ViewModels 235 Leveraging a messenger to wrap application-wide messages 239 Chapter 7: Working with Services 243 Introduction 243 Connecting and reading from a standardized service 244 Persisting data using a standardized service 250 Configuring cross-domain calls 254 ii
  11. Table of Contents Working cross-domain from a trusted Silverlight application 262 Reading XML using HttpWebRequest 265 Reading out an RSS feed 271 Accessing a database in the cloud 274 Accessing a service in the cloud 279 Running a Silverlight application from the cloud 284 Using socket communication in Silverlight 288 Chapter 8: Talking to WCF and ASMX Services 301 Introduction 301 Invoking a service that exposes data 302 Invoking a service such as Bing.com 312 Optimizing performance using binary XML 315 Debugging a service in Silverlight 318 Using ASP.NET Authentication in Silverlight 325 Uploading files to a WCF service 332 Displaying images as a stream from a WCF service 338 Chapter 9: Talking to WCF and ASMX Services—One Step Beyond 345 Introduction 345 Using duplex communication over HTTP 346 Using duplex communication with the WCF net.tcp binding 355 Ensuring data is encrypted 363 Securing service communication using message-based security 369 Integrating Windows Identity Foundation in Silverlight 374 Calling a WCF service from Silverlight using ChannelFactory 383 Chapter 10: Talking to REST and WCF Data Services 387 Introduction 388 Reading data from a REST service 389 Parsing REST results with LINQ To XML 395 Persisting data using a REST service 399 Working with the ClientHttp stack 406 Communicating with a REST service using JSON 408 Using WCF Data Services with Silverlight 411 Reading data using WCF Data Services 416 Persisting data using WCF Data Services 421 Talking to Flickr 426 Talking to Twitter over REST 434 Passing credentials and cross-domain access to Twitter from a trusted Silverlight application 439 iii
  12. Table of Contents Chapter 11: Using WCF RIA Services 451 Introduction 451 Setting up a data solution to work with WCF RIA Services 452 Using a WCF RIA Services class library 455 Getting data on the client 460 Using LoadBehavior to control what happens to your data once it's sent to the client 472 Controlling the server-side query from the client 476 Sorting and filtering data on the server 481 Paging through your data 485 Persisting a change set/unit of work 490 Working with concurrency and transactions 496 Chapter 12: Advanced WCF RIA Services 503 Introduction 504 Tracking a user's identity – default Windows authentication 504 Tracking a user's identity – a custom authentication service 507 Integrating Windows Identity Foundation with WCF RIA Services 513 Controlling a user's access to services and service methods 517 Validating data: using data annotations 521 Validating data: writing a custom validator 524 Validating data: server-side validation with client-side feedback 532 Validating data: triggering validation when needed 536 Validating data: using the ValidationContext 541 Handling errors on the server 545 Using SQL Azure with WCF RIA Services 548 Exposing WCF RIA Domain Services as OData endpoints 550 Exposing WCF RIA Domain Services for other technologies 553 Chapter 13: Windows Phone 7 557 Introduction 557 Getting our environment ready to start building Windows Phone 7 applications 562 Building your first data-driven Windows Phone 7 application 562 Getting data on your Windows Phone 7 using WCF 578 Accessing REST services from Windows Phone 7 using XML 587 Accessing REST services from Windows Phone 7 using JSON 591 Working with push notifications using the cloud 597 Storing data in a local SQL CE database 609 Using the background transfer service 616 iv
  13. Table of Contents Appendix 623 Creating a REST service from WCF 623 Installing an SQL Server database 625 Working with Fiddler 625 Working with the Silverlight control toolkit 626 Working with WIF 627 Installing the WCF RIA Services Toolkit 627 Installing and using NuGet 627 Index 629 v
  14. Preface About 2 years ago, in the spring of 2010, Microsoft released Silverlight 4. Silverlight 4 proved to be a platform ready for Line-of-Business application development. Numerous developers learned how to build great apps with it, which can run both within the browser and as a stand-alone application on the user's machine. Silverlight 5 was the logical successor and extended the platform again with an extensive list of new features. Soon after the launch of the Silverlight 4, the first edition of this book was released. Its success convinced us to write an updated version that focuses on Silverlight 5. While all existing content is updated to match the new version, a lot of new content is added. This can be found in recipes covering Silverlight 5-specific features as well as complete new chapters, covering other aspects of working with data such as MVVM (Model-View-ViewModel) or even from Windows Phone 7. In this practical cookbook, you'll learn how to build data-rich business applications with Silverlight that draw on multiple sources of data. Although the book focuses on Silverlight 5, many of the recipes will work on Silverlight 4 projects as well. A large number will also work in Silverlight 3. This is indicated for each recipe. Packed with reusable, real-world recipes, the book begins by introducing you to general principles for programming Silverlight. It then dives deep into the world of data services, covering all the options available to access data and communicate with services to make the most out of data in your Silverlight business applications, whilst at the same time providing a rich user experience. Chapters cover data binding, data controls, concepts of talking to services, communicating with WCF, ASMX, REST services, and much more. The chapter on accessing data and services from Windows Phone 7 applications discusses how to leverage your knowledge on the mobile platform. By following the practical recipes in this book, which are of varying difficulty levels, you will learn concepts for creating data-rich business applications—from the creation of a Silverlight application, to displaying data in the Silverlight application and upgrading your existing applications to use Silverlight. Each recipe will cover a data services topic, starting from the description of the problem, covering a conceptual solution and a solution containing sample code.
  15. Preface What this book covers Chapter 1, Learning the Nuts and Bolts of Silverlight 5, will get you up and running with Silverlight. While this book is aimed at developers who already have a basic knowledge of Silverlight, this chapter can act as a refresher. We'll also look at getting your environment correctly set up so that you enjoy developing Silverlight applications. Chapter 2, An Introduction to Data Binding, will explore how data binding works. We'll start by building a small data-driven application that contains the most important data binding features, to get a grip of the general concepts. We'll also see that data binding isn't tied to just binding single objects to an interface; binding an entire collection of objects is supported as well. We'll also be looking at the binding modes. They allow us to specify how the data will flow (from source to target, target to source, or both). Visual Studio enables debugging data binding statements in version 5, which we'll dive into, and we'll finish this chapter by looking at the support that Blend 5 provides to build applications that use data binding features. In the next chapter, we'll be looking at the more advanced concepts of data binding. Chapter 3, Advanced Data Binding, teaches you advanced data binding concepts that can be used for customization, validations, and applying templates to data bound controls. New Silverlight 5 features such as custom markup extensions, Ancestor Relative Source binding, and implicit data templates are discussed in this chapter as well. We also have a look at converters, which can be seen as hooks in the data binding process. Chapter 4, The Data Grid, covers recipes on how to work with the DataGrid. This is an essential control for applications that rely on (collections of) data. Chapter 5, Working with Local Data, covers storing data locally. The concept of local data is essential in many scenarios, varying from saving local user settings to entire blocks of data. Silverlight has always included the concept of Isolated Storage; we'll see how to use that. Chapter 6, MVVM, explains all you need to get started with the Model-View-ViewModel design pattern, the de facto standard for XAML-based applications. Using this pattern to build Silverlight applications will result in better separation of concerns, code that's easier to test and maintain, and it ensures you leverage the true power of XAML. Chapter 7, Working with Services, talks about the rich set of options that Silverlight provides to communicate with services. We'll see also how Silverlight and Azure can be used together for more powerful solutions. Chapter 8, Talking to WCF and ASMX Services, discovers Silverlight's built-in support for communicating with Windows Communication Foundation (WCF) and classic ASMX web services. Integration with the ASP.NET Membership API as well as uploading and downloading files is covered in this chapter as well. 2
  16. Preface Chapter 9, Talking to WCF and ASMX Services—One Step Beyond, takes us on a tour of more complex WCF problems and their solutions. Perform unidirectional as well as bidirectional communication with much better performance using net.tcp binding in WCF using the recipes in this chapter. Security is vital when working with services and is explained as well through several recipes. Chapter 10, Talking to REST and WCF Data Services, takes advantage of REST, which can be significant in the case of Silverlight. We will also look at how we can work with WCF Data Services. You will abstract away a lot of plumbing code with the use of the client-side library that is available for use with Silverlight. Chapter 11, Using WCF RIA Services, is all about the framework built by Microsoft, to simplify and reduce development time for Line-of-Business RIA development. In this chapter, we look into the basics: how it works behind the scenes, how to fetch data, how to sort, filter, and page through your data, how to submit data, and how to structure your project. Chapter 12, Advanced WCF RIA Services, tackles the more advanced techniques concerning WCF RIA Services: you'll learn all about authentication (Windows, Forms, and through WIF), various validation scenarios, error handling, and how you can expose your domain services for use with other technologies. Chapter 13, Windows Phone 7, explains how Windows Phone 7 applications, which are by default built with Silverlight, can communicate with services and get access to server-side. In this chapter, recipes can be found which cover connecting to services that communicate with XML and JSON as well as SOAP over WCF. We'll also take a look at working with a local SQL CE database. Finally, a recipe on push notifications explains how a cloud service can connect with an application on a device, opening push-like scenarios. The Appendix talks about creating a REST service from WCF, installing a SQL Server database, working with Fiddler and the Silverlight control toolkit, WCF RIA Services and WIF. What you need for this book To work with the recipes in this book, you should have Visual Studio installed. This book targets Silverlight 5, for which you need Visual Studio 2010 (or later). Many of the recipes in the book will also work in Silverlight 3 and 4, so for these recipes, you have the choice of Visual Studio 2008 (for Silverlight 3) or 2010 (Silverlight 3 and 4). We do recommend using Visual Studio 2010, as it features a lot of enhancements for developing with Silverlight. In both cases, you'll of course need to install the Silverlight Tools, which will update your Visual Studio instance to work with Silverlight. Some recipes also require Blend 5 to be installed on your machine (again, if working with Silverlight 3, Blend 3 will suffice here as well; Silverlight 4 applications can be built using Blend 4). For the Windows Phone recipes, you could use the specific phone-enabling Express edition of Visual Studio, which is bundled with the Windows Phone SDK & Tools. 3
  17. Preface The first recipe of Chapter 1, Getting our environment ready to start developing Silverlight applications, explains in detail how to get these tools and how to install them. Who this book is for If you are a .NET developer who wants to build professional data-driven applications with Silverlight, then this book is for you. Basic Silverlight experience and familiarity with accessing data using ADO.NET in regular .NET applications is required. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "Finally, the DataReader and connection are closed and the StoreDTO object is returned." A block of code is set as follows: When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: Any command-line input or output is written as follows: xmlns:controlsToolkit="clr-namespace:System.Windows. Controls;assembly=System.Windows.Controls.Toolkit" New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "Do this by right-clicking, selecting Add New Item, and then selecting LINQ TO SQL Classes." Warnings or important notes appear in a box like this. Tips and tricks appear like this. 4
  18. Preface Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title through the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files for this book you have purchased from your account at http://www.packtpub.com/ files/code/3500_Code.zip. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code— we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. 5
nguon tai.lieu . vn