47,99 €
Microsoft Silverlight is a powerful development platform for creating engaging, interactive applications for many screens across the Web, desktop, and mobile devices. Silverlight is also a great (and growing) Line-Of-Business platform and is increasingly being used to build data-driven business applications. Silverlight is based on familiar .NET languages such as C# which enables existing .NET developers to get started developing rich internet applications almost immediately. "MCTS: Microsoft Silverlight 4 Development (70-506) Certification Guide" will show you how to prepare for and pass the (70-506): TS: Microsoft Silverlight 4 Development exam.Packed with practical examples and Q&As, MCTS: Microsoft Silverlight 4 Development (70-506) Certification Guide starts by showing you how to lay out a user interface, enhance the user interface, implement application logic, work with data and interact with a host platform amongst others.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 344
Veröffentlichungsjahr: 2012
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 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: June 2012
Production Reference: 1180612
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84968-466-8
www.packtpub.com
Cover Image by Artie Ng ( <[email protected]>)
Author
Johnny Tordgeman
Reviewers
Kunal Chowdhury
Evan Hutnick
Acquisition Editor
Kerry George
Development Editor
Susmita Panda
Technical Editor
Devdutt Kulkarni
Project Coordinator
Vishal Bodwani
Proofreader
Linda Morris
Indexer
Rekha Nair
Production Coordinator
Melwyn D'sa
Cover Work
Melwyn D'sa
Johnny Tordgeman is a professional SharePoint, FAST, and frontend developer and trainer, who has over six years of experience in the development of web applications.
Johnny serves as the CTO at E4D Solutions where he specializes in building enterprise applications based on SharePoint and Silverlight, for the telecom, financial, and government industries.
Johnny is a frequent speaker at user groups and conferences on SharePoint and client-side technologies.
First, I would like to thank everyone at Packt Publishing, and especially Vishal Bodwani, for making this book a reality. Secondly, I would like to dedicate this book to my amazing wife Ayelet , my dear parents Itzik and Varda, my brothers Shirley and Yuval, and my friends Yossi, Idan, Leon, Niv, Itzik, Tal, and Zvi for believing in me in every step of the way..
Last, but not least, I would like to thank my academic mentor, Dr. Amnon Dekel, for giving me the confidence to know that even when things go wrong, someone is there for you.
Kunal Chowdhury is a Microsoft MVP (Silverlight), Telerik MVP, Codeproject MVP, and Mentor, and also a frequent speaker at various Microsoft events. Apart from being an author and passionate blogger, he is a software engineer by profession. He is very passionate about Silverlight, WP7, WPF, Windows 8 Metro UI, and LightSwitch. Kunal shares his findings at his technical blog—http://www.kunal-chowdhury.com/. He has also worked as a technical reviewer for the book, Fun with Silverlight 4.
He is the owner of http://www.silverlight-zone.com/. If you wish, you can follow him on Twitter (@kunal2383), or you can connect with him on his Facebook page—facebook.com/blog.kunal2383.
Evan Hutnick works as a Developer Evangelist and Solutions Consultant for Telerik, empowering customers to make the most out of the XAML platforms, as well as offering best practices, mentoring, and custom development services. Evan has previously provided a technical review for the Silverlight 5 Data and Services Cookbook, and also hosts a brand new XAML-based site named http://xamlwatch.com/, designed to deliver fresh and interesting content covering all of the XAML platforms.
Last, but certainly not least, I would like to thank my wonderful wife and daughter, for supporting me in my development pursuits, and allowing me to geek it up on nights and weekends.
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 <[email protected]>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.
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.
Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.
Microsoft Silverlight offers a robust development environment for rich, cross-browser, cross-operation system businesses, and rich, interactive media experiences. Microsoft's Silverlight MCTS exam is intended for developers, who wish to create these types of applications using the knowledge they already have as .NET developers.
This book will give you the essential knowledge to master the Silverlight MCTS exam, by first introducing you to the core concepts of developing with Silverlight, and gradually moving towards more advanced Silverlight concepts and techniques.
The book uses an example-driven approach that is easy to understand, and helps you master the material covered, by actually doing, and not only reading.
Each chapter contains sample practice questions at the end, based on actual exam questions, so you can test your knowledge, and get a feel for the actual exam, before taking it.
Chapter 1, Overview of Silverlight, is an introductory chapter to Silverlight that covers core concepts of the framework.
Chapter 2, Laying out Our User Interface, gives you an introduction to building user interfaces in Silverlight. The chapter covers core concepts, such as panels, navigation framework, and playing media files.
Chapter 3, Enhancing the User Interface, builds upon the foundations learned in the previous chapter, and arms you with advanced techniques, such as animations and behaviors, for building a better and richer user interface.
Chapter 4, Implementing Application Logic, deals mainly with adding logic to your UI. You will learn all about concepts, such as consuming services, and building dependency properties, which will help you make your application more than just a pretty face.
Chapter 5, Working with Data, introduces you to the world of handling data in Silverlight. You will learn all about binding, formatting, validating, and conversion of data.
Chapter 6, Interacting with the Host Platform, guides you through how to use the host of your Silverlight application to perform tasks, such as printing, copy/pasting, and more.
Chapter 7, Structuring Applications, covers how to make your code look cleaner, and behave better.
Chapter 8, Deploying Applications, packs things up by diving deep into configuring the Silverlight plugin, and reducing its size by dynamically loading resources.
For this book, you will need Visual Studio 2010. In addition, you will need the Silverlight development tools, which can be downloaded from http://www.silverlight.net/getting-started for free, and a copy of Microsoft Expression Blend 4, which has a 60-day free trial version available at http://www.microsoft.com/expression/try-it/.
This book is for anyone who wishes to learn the essential skills needed to pass the Microsoft Silverlight MCTS exam, and use these skills to build rich interactive applications using the Silverlight platform.
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: " We have already seen the Inline properties when we declared our Button control—Width, Height, Content, and x:Name are all Inline properties."
A block of code is set as follows:
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 the text like this: " Open Visual Studio 2010, click on New Project..., select Silverlight from the Installed Templates list on the left-hand side of the window, and click on Silverlight Application."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 <[email protected]>, 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.
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.
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. 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.
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 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.
Please contact us at <[email protected]>with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]>if you are having a problem with any aspect of the book, and we will do our best to address it.
Just like everything in life, we start things off with an overview. If you have picked up this book on purpose, then I'm sure you have at least some idea what Silverlight is. But, if you just picked this book because the cover looked inviting, fear not, as this chapter will provide all the basics you'll need in your journey to become a certified Silverlight guru.
As Confucius once said, "A journey of a thousand miles begins with a single step", so let's take the first step now and get to know all the basics of Silverlight.
In this chapter we will cover the following topics:
Silverlight is Microsoft's cross-platform, cross-browser, and a .NET-based framework for building in and out-of-browser Rich Internet Applications (RIAs). In simple words, you can write Silverlight applications using a language you already know (be it C# or VB), and run it on all major operating systems (such as OSX, Windows, and Linux) and browsers (such as Internet Explorer, Chrome, Firefox, and Safari).
It's worth noting that the Linux variation of Silverlight is not developed or maintained by Microsoft. Moonlight, which is the name of the Linux variation, is developed by the Mono project with aid from Microsoft and Novell, and is primarily targeted for Linux and other Unix/X11-based operating systems. In addition, your Silverlight application doesn't have to stay inside the browser. Using the out-of-browser capabilities of Silverlight, you can take your application out of the browser and into the desktop, but we will learn more on that later.
Using Silverlight you can build just about anything—from a simple media player that streams movies from your server, to a complex line of business (LOB) application that fetches data from a database and uses some business logic to transform that data into a visually stunning executive dashboard with interactive charts and gauges.
Many companies nowadays are using Silverlight to enrich their applications. Take a look at Seesmic Desktop 2 for example (http://www.seesmic.com/products/desktop), which is a social media tool for Windows and Mac built entirely in Silverlight.
The main competition to Silverlight comes from Adobe Flash. Both are browser plugins targeting rich media applications. While not a direct competitor, HTML5 can also be considered as an alternative in some cases. While Silverlight has matured into a rich line of business platform that is getting increasingly popular for creating intranet applications, HTML5 offers greater reach, as it can be viewed on more devices. But, it is also much harder to develop the same level of business applications using HTML5 instead of Silverlight.
In addition, the HTML5 specifications are not finalized yet and, thus, not all the browsers implement it evenly. For example, while some browsers fully support the Canvas control, others support just some of its features, making it difficult to use the "code once, run everywhere" approach.
Whether you are an ASP.NET developer trying to decide if Silverlight is the right technology for your next project or you are a part of a development team in a big enterprise, here are some reasons to use Silverlight over other technologies:
The adoption rate of Silverlight has recently reached the 70 percent milestone (http://www.riastats.com/), which means that almost every three out of four PCs already have Silverlight installed! With the rise in the adaptation rate comes the rise in the need for developers. A leading job-hunting site—http://www.dice.com/—has recently found that Silverlight-related jobs experienced a 12.6 percent growth in demand over the last three months, while Adobe Flash-related jobs experienced just 2.2 percent growth over the same period of time (http://www.readwriteweb.com/enterprise/2011/05/it-hiring-and-salaries-up---wh.php). In addition, Silverlight is the language of choice to develop applications for Microsoft's newest mobile phone system—Windows Phone 7, which means that if you know Silverlight, you are not only a web and desktop developer, you are also a mobile developer!
If I have to sum up the last paragraph in simple words, I would say that you couldn't have picked a better time to become a certified Silverlight developer.
Now that you know what Silverlight is, what it can do, and why you should use it, let's move on to set up your development environment. Your development environment requires the following hardware and software components:
Setting up your development environment is as easy as it can get. The process consists of three downloads (two are mandatory and one is optional) and the installation of those components.
The first thing you need is Visual Studio 2010. If you have Visual Studio 2008 or an earlier version, you will need to upgrade it, as the Silverlight 4 developer tools don't support these versions. You can download a free version of Visual Studio 2010 from the Microsoft website at http://www.microsoft.com/express/Downloads/.
Once you have Visual Studio 2010 installed, you will need the Silverlight 4 developer tools. These tools add the support for developing and designing Silverlight 4 applications in Visual Studio 2010. If you have Service Pack 1 for Visual Studio 2010 installed, you already have the tools; if not, you can get them either by using the installed Microsoft/web platform located at http://www.microsoft.com/web/gallery/install.aspx?appid=silverlight4tools;silverlight4toolkit;riaservicestoolkit or downloading the Microsoft Silverlight 4 Tools for Visual Studio 2010 directly from http://go.microsoft.com/fwlink/?LinkID=177428.
The last thing you should download and install is the Silverlight 4 Toolkit from CodePlex. This toolkit adds new components and functionality to the developer tools, and it is highly recommended that you install it. This toolkit can be downloaded from http://silverlight.codeplex.com/releases/view/43528.
While it is completely possible to develop Silverlight 4 applications without the Silverlight 4 Toolkit, it is highly recommended that you download it as it adds many frequently used components, such as an auto-complete box, to the arsenal of components that you can use in your applications.
Now you have a fully equipped development environment for Silverlight. With this accomplishment, we can move on and talk about the first major concept of working with Silverlight—XAML.
A Silverlight application, once compiled, will end up as a XAP (pronounced as zap) file. That XAP file, which is actually a ZIP file renamed, will contain your compiled code in the form of a DLL file, which is a manifest file named AppManifest.xaml that describes your application to the Silverlight runtime engine and possibly some resources such as images, web service connection information, or any other type of content your application might need.
Due to the fact that a XAP file contains more than just compiled code, there may be times when we need to edit its content, which is where knowing the fact that "the XAP files are basically the ZIP files" comes in handy.
Consider the following scenario:
You are developing a Silverlight application that needs to access a database in order to display data from it. To access the database, you will connect to a WCF web service that grabs the data and sends it back to your application in the XML format. In most cases, the WCF web service won't be hosted on the same machine in both development and production environments and, thus, will have a different IP address on each. As we have mentioned earlier, the XAP file contains, among other things, the web service connection information for our application inside a file called ServiceReferences.ClientConfig. So, before we move our application from a development to a production environment we need to edit this file and change the address of the WCF web service from a testing environment address to the production address.
In order to run our Silverlight application, the browser will download our XAP file to the client computer, which means file size may be an issue for users with limited bandwidth or a slower connection. We may try to reduce the size of our XAP file by re-zipping it using a stronger compression rate. But, this will come at the expense of slower decompression of the XAP file on older machines, and the slower the decompression rate is, the longer it will take for your application to start running.
A better method to decrease the size of your XAP file would be using the "application library caching" option. The application library caching, also known as assembly caching, is a packing method, which avoids packing the DLL files into your XAP file, and instead zips them into individual files alongside it. Using assembly caching may greatly reduce the size of your XAP file, providing faster initial loading time for your application.
To use assembly caching, right-click on the project name in Visual Studio 2010 and select Properties. In the new dialog box, select the Reduce XAP size by using application library caching option, as shown in the following screenshot:
You cannot use assembly caching if you are building an out-of-browser application. We will discuss the out-of-browser applications later on in this chapter.
You may be wondering at this point how the Silverlight runtime engine knows that we used the assembly caching option, and that it needs to download a list of external DLL files. The answer to this question is simpler than you might imagine—the AppManifest.xaml file.
We have mentioned the AppManifest.xaml file earlier when we discussed the content of a XAP file and now we can elaborate more about it. The AppManifest.xaml file has one important role—it is responsible for describing our application to the Silverlight runtime engine. Whenever you create a new Silverlight project, Visual Studio 2010 creates this file as part of the project and updates it throughout the project lifetime if necessary. As Visual Studio is responsible for updating this file, it would be rare that we need to update this file by hand ourselves.
Visual Studio 2010 will generate the content of the file, once you compile your Silverlight project. Let's take a look at a basic example of an AppManifest.xaml file:
As can be seen from the preceding code snippet, the Deployment element has three attributes as follows:
Under Deployment lies the Parts section. This section houses one or more AssemblyPart entries, each of which point to a DLL file that our application is using. The first entry is usually our compiled Silverlight application, which also contains the entry point class that was specified under the EntryPointType attribute of the parent Deployment tag.
Other than Parts, the Deployment element may also contain an ExternalParts section. This section will be visible only if we have used the application caching option. This section tells the Silverlight runtime engine which files it needs to download, other than the XAP file, in order to run the application. The ExternalParts section will contain one or more ExtentionPart entries, each of which point to an external ZIP file.
An example of the ExternalParts section may look like the following code snippet:
In our sample, the Silverlight runtime engine will have to download two external files to get the application running.
Now that we know how the Silverlight application model works, let's see how Silverlight interacts and integrates with HTML to actually display the application to the user.
There are two ways to add a Silverlight application to your HTML page as follows:
The object tag method is the easiest way to add a Silverlight application to your page. Using this method, you won't need to use any external JavaScript files for adding a Silverlight application to your page. This method is also supported by all the browsers that are supported by Silverlight. A basic Silverlight object tag will look as follows:
The object tag has four mandatory attributes as follows:
Inside the object tag we have several param entries, as listed in the following table:
Name
Description
Required
Default
source
This specifies the URI to the XAP file. It can be a relative or absolute URI.
Yes
None
onError
This specifies a JavaScript function to call when an error occurs while loading the Silverlight application.
No
None
background
This specifies the background color for the object tag rectangular area that displays the Silverlight application. It can accept color names (such as Red) or hexadecimal values with or without alpha (#ff000000 or #000000).
No
white
minRuntimeVersion
This specifies the earliest Silverlight version required to run the application.
No
Currently installed version
autoUpgrade
This specifies whether or not to automatically update to the specified version in the minRuntimeVersion attribute if the currently installed version is an older version.
No
true
initParams
This specifies user-defined initialization parameters using comma-separated key-value pairs, for example, UserName=JohnnyT
No
None
There are many more parameters you can use with your Silverlight object tag, and you can read more about them at Microsoft's MSDN web page—http://msdn.microsoft.com/en-us/library/cc838259(v=vs.95).aspx.
If the browser fails to render the Silverlight application, it will fall back to the content inside of the object tag. The default content of a Silverlight object tag will look like the following screenshot:
You can always change the content of the object tag to your liking by simply removing all the content the object tag currently has (remember, don't delete the param entries!) and writing your own HTML code instead.
If you need greater control on the object tag or the installing/upgrading process, you can use the JavaScript method.
The JavaScript method makes use of a helper file called Silverlight.js, which can be found in the Tools directory under the Silverlight SDK folder usually located at C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Tools.
Once referenced, the Silverlight.js file creates a class called Silverlight, which will provide you with different methods and properties related to Silverlight, such as Silverlight.CreateObject, Silverlight.IsInstalled, and more.
Adding Silverlight using JavaScript is out of the scope of this book, but you can find all the information you need for it on MSDN at http://msdn.microsoft.com/en-us/library/cc265155(v=vs.95).aspx.
Silverlight's interaction with JavaScript certainly doesn't end here. In Chapter 6, Interacting with the Host Platform, we will discuss many features of Silverlight-JavaScript-HTML integration, such as calling a JavaScript method from Silverlight, calling a Silverlight method from JavaScript, manipulating the Document Object Model (DOM) from Silverlight, accessing cookies, and more.
As you might recall, we have mentioned earlier in this chapter that Silverlight isn't limited to running inside the browser anymore. This new concept, called out-of-browser applications, was introduced back in Silverlight 3 and got heavily enhanced in Silverlight 4, so introducing it now would be the perfect way to finish off this chapter.
