Microsoft Silverlight 5: Building Rich Enterprise Dashboards Create, customize, and design rich enterprise dashboards with Microsoft Silverlight 5... 5 XAML as a declarative programming
Trang 2Microsoft Silverlight 5: Building
Rich Enterprise Dashboards
Create, customize, and design rich enterprise
dashboards with Microsoft Silverlight 5
Trang 3Enterprise Dashboards
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 published: January 2012
Trang 5About the Authors
Todd Snyder has been a Software Developer/Architect for over 17 years During that time, he has spent several years as a Consultant, providing technical guidance and leadership for the development of Enterprise Class Systems on the Microsoft Platform At Infragistics, he is a principal consultant who focuses on the design and construction of RIA and N-tier based applications Todd is the co-leader for the New Jersey NET user group (http://www.njdotnet.net/) and is a frequent speaker at trade shows, code camps, and Firestarters
Joel Eden, Ph.D. has been working in the area of user experience and design methods for over 10 years Currently a Senior Interaction Designer working on
UX Tools at Infragistics, he previously spent 3 years in the Infragistics UX Services group, consulting for external clients Prior to Infragistics, he worked at multiple design agencies in the Philadelphia area, as well as working at Lockheed Martin's Advanced Technology Labs He holds a B.S in Computer Science, and a PhD in Information Science, both from Drexel University
I would like to thank my wife Kathleen and my daughters Abigail
and Genevieve, for giving me reasons to design a better future
Trang 6Art Director at various agencies and studied Special Effects and Animation at NYU
A convert from Flash and Flex, he has been working with NET technologies for the past 2 years, specializing in WPF and Silverlight At Infragistics, he is an UX Visual Designer who focuses on the design, implementation, and User Experience You can view some of his work at http://www.thinksinkstudio.com
I would like to thank my friends, family, girlfriend, and colleagues
for providing support and inspiration
Matt Duffield is the Architect at emGovPower, a leading software provider for managing city and county governments With over 15 years of working in IT, he enjoys building rich user-centric applications Matt is very active in the community, speaking at user groups and code camps He is an INETA speaker member and has been a Microsoft MVP in Client Application Development He started working in NET as soon as it was available to the development community and was also an early adopter of both WPF and Silverlight He believes good business intelligence (BI) architecture is the formula for a successful software package that looks beyond just data and provides insightful information His blog can be found at http://mattduffield.wordpress.com You can follow him on Twitter at @mattduffield Matt currently lives in Charlotte, North Carolina with his wife and two sons
First of all, I would like to thank my family and colleagues who
have been instrumental in helping me work on this book It is their
encouragement and enthusiasm that has in turn been my drive
for writing I have always loved working in Silverlight, and I look
forward to many more years doing the same I would also like to
thank the team at Packt Publishing for allowing me to become a part
of this book and having the patience and wisdom to help me during
the writing process It has been a wonderful experience, and I look
forward to doing it again in the future
Trang 7About the Reviewers
Curtis Taylor is a Principal Consultant at Infragistics, Inc When he first started studying human interaction with products, objects and particularly software
interfaces, he noticed people often believed they were dumb when they did not understand an interface However, rather than fixing the problem, the industry standardized interfaces which lacked the ability to engage most users The
industry attempted to fix the user, rather than the interfaces Designing interface
is an interaction between user and developer Two things drew him to Software Development—the abstraction of writing code and the challenge of presenting that abstraction to human beings in a way they can understand
People are organic Computers are not So the work of making software interfaces more understandable, practical, and enjoyable became something he wanted to
do Software development is his connection to serving people People are more important than things Perhaps his message will be communicated in the interfaces
he creates, the code he writes, and the feedback, training, and team-work he offers to other developers
He loves WPF and Silverlight! So much so, Infragistics found and hired him to be a consultant and trainer At Infragistics he works directly with customers helping them solve technical and UI-related issues with WPF and Silverlight, he provides training
as a fellow software engineer, and he develops custom solutions for customers who wish to utilize their services a step beyond the capabilities of their products
Michael Crump is an MCPD who has been involved with computers in one way
or another for as long as he can remember, but started professionally in 2002 After spending years working as a System Administrator/Tech Support Analyst, Michael branched out and started developing internal utilities that automated repetitive tasks and freed up full-time employees From there, he was offered a job working at
Trang 8several other Silverlight publications He resides in Birmingham, AL with his wife Amanda and children Ridley and Adrienne.
He shares his findings in his personal blog: http://michaelcrump.net, and he also tweets at @mbcrump
Siddharth Mehta is a Business Intelligence professional with more than
nine years of experience, and presently works in the role of a Technology
Architect for Accenture Services Pvt Ltd (Mumbai, India), in the capacity of
an Associate Manager Prior to Accenture, he has worked at Capgemini with
clients including Walt Disney Pictures and Television, CitiBank, Transport for
London, and ABN AMRO
He started his career in 2002 with Visual Basic and SQL Server, and since then he has been majorly working with SQL Server, Business Intelligence, Data Warehousing, Dimensional Modeling, Information visualization design, and related technologies
He is known for his writing in the field of Microsoft Business Intelligence He has
authored a whitepaper for MSDN Library, titled Bulk Report generation using SSIS and SSRS 2008 R2 He continues authoring content on MS BI for community sites such as
MSSQLTips.com, SQLServerCentral.com, SQL-Server-Performance.com, and others
He has been the Technical Reviewer of the book Microsoft SQL Azure Enterprise Application Development.
He has won awards such as Microsoft Most Valuable Professional CY'11, Capgemini India Envoy FY'10, and others through the course of his career He shares his insights
on business intelligence through his blog: http://siddhumehta.blogspot.com He can be reached at siddhumehta_brain@yahoo.co.in
Through thick and thin, all I am today is the result of my parent's
(Divya Mehta and Kaushik Mehta) vision and my brother's (Rahul
Mehta) support to solve troubles before it reaches me I am grateful
to them for taking care of my responsibilities while I remained busy
reviewing this book
Trang 9Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.comwww.PacktPub.comwww.PacktPub.com for support 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.comservice@packtpub.comservice@packtpub.com for more details 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
• 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 atwww.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
Trang 10Table of Contents
What benefit does Silverlight bring to the table? 5
XAML as a declarative programming model 6Model-View-ViewModel (MVVM) 6
View First versus ViewModel First 9
Dependency Injection (DI) 11Silverlight as a Web technology 14Asynchronous programming in Silverlight 16Silverlight features 16
Client-side application development 21
Cross-browser development simplified 23
Current state of building dashboards 36 When good just isn't good enough 37
Visual Studio strengths and weaknesses 46
Trang 11Creating a Silverlight Dashboard Application 67
Setting up the Data Source 74
Defining the View-Model and Model classes 75
Laying out XAML and Data Binding 78
Different dashboards for different needs 88
Trang 12Focusing on needs, not technology 96
Representing and communicating user experience 97User-centered design 99
Scenario-based requirements and design 102
Example scenarios for dashboard design 105
Interaction aesthetics versus visual aesthetics 109
Pre-attentive processing 111
Applying pre-attentive processing to dashboard design 111 Warnings about using pre-attentive attributes 113
Scenario-based design of our dashboard 114
Our initial overall dashboard wireframe 115
Design View (Artboard) 130
Trang 13Results 134
Referencing resources 136Implementing resources 136
Exploring a Button's Control Template 137 Adding Visual States (Visual State Manager) 144 Converting Brushes to Resources 152 Creating Resource Dictionaries 155
Getting started with styling our Dashboard 157
Creating a custom User Control in Blend 157Styling the Grid and Chart 160
Describing an N-Tier application design 166Sample project structure 168
Reviewing the database schema 173Stored procedures 174
spTopUsInternetProducts 175 spTopUsInternetCustomers 176
Domain Model (Shared Between Client
Data Access Layer 187Building the WCF service 194
Defining the presentation layer 197
View and controls 197
Service Layer 209
Core networking classes 214
Trang 14Understanding network security 219 Building services with Windows Communication Foundation 221
Working with WCF 223
The data access layer 224
Building a SOAP service 227Building a REST service 230
Building an OData service 235Consuming an external service 238
Chapter 10: Building Dashboards in SharePoint and Silverlight 241
Setting up SharePoint 242
Building a Silverlight web part 244
Using the Client Object Model 248
Building a SharePoint Silverlight dashboard 252
Setting up our data source 252Building our dashboard 253
SharePoint Data Access Strategies 259
Trang 16Welcome, to the exciting world of building Rich Enterprise Dashboards with
Silverlight Throughout this book, you will learn how to harness the power of the Silverlight 5.0 platform to build amazing Dashboards This book goes beyond just showing the nuts and bolts of learning Silverlight and showcases how to create amazing dashboards that offer the best user experience and visual design that will impress your end users and peers
What this book covers
Chapter 1, The Silverlight Technology, is an overview of the Silverlight 5.0 Platform and
teaches you how to build Silverlight applications
Chapter 2, Overview of Dashboards and Silverlight, answers why you should use
Silverlight 5.0 to build dashboards and compares the use of Silverlight and HTML for building dashboards
Chapter 3, Silverlight Design and Development Tools, is an overview of the different
tools you will need to build a dashboard applications
Chapter 4, Building a Basic Dashboard, is a walkthrough of how to build a simple
Silverlight dashboard application
Chapter 5, Dashboard Types and User Needs, outlines the three main types of
dashboards: Strategic, Operational, and Analytical By the end of this chapter, you will understand how to choose the right dashboard for your project depending upon your needs
Chapter 6, Designing for Insight, throws light on designing concepts of bringing the
end-user's attention to certain information Using these concepts, we will design a dashboard that supports the scenario we have already created
Trang 17Chapter 7, Designing your Dashboard, covers the basics of styling a Silverlight
dashboard with Microsoft Expression Blend Through this chapter you will
understand the key styling terminology, learn how to reference resources, and edit basic control templates
Chapter 8, Building an End-to-End Solution, is an overview of building a real-world
Silverlight dashboard application that uses the Microsoft SQL Server Adventure Works sample database Through this chapter you will explore how to use the N-Tier application model to build out the AdventureWorks dashboard application
Chapter 9, Data Access Strategies, outlines the different data access strategies and
technologies you can use when building your Silverlight dashboard application
Chapter 10, Building Dashboards in SharePoint and Silverlight, covers how to build
a SharePoint web part for hosting a Silverlight dashboard, and how to use the
SharePoint Client Object Model to access data hosted in SharePoint
What you need for this book
To build the samples in this book, you will need to have the following available:
• Visual Studio 2010 Express or Professional Edition
• SQL Server 2008 R2 Express or Developer Edition
• Silverlight 5.0 SDK
• Silverlight 5.0 Toolkit
• Microsoft Expression Blend 4.0 (with Updates for Silverlight 5.0)
• Share Point 2010 Foundations (Optional only required for Chapter 10, Building Dashboards in SharePoint and Silverlight)
Who this book is for
If you are a NET developer who wants to create, customize, and design rich
enterprise dashboards with Silverlight, then this book is for you You should have
an intermediate understanding of NET development, with a working knowledge of Microsoft Silverlight
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
Trang 18Code words in text are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
<Button x:Name="btnSaveCustomers" Content="Save Customers"
Click="btnSaveCustomers_Click" />
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
<endpointaddress="" binding="customBinding"
bindingConfiguration="DashboardCustomBinding0"
contract="Chapter8.Web.Services.IDashboardService" />
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: "When the
dialog is displayed, click on the Discover button, and select the IDashboardService
service contract."
Warnings or important notes appear in a box like this
Tips and tricks appear like this
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 via the subject of your message
If there is a book that you need and would like to see us publish, please send
us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail
suggest@packtpub.com
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
Trang 19Customer 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 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
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 on our website, or added to any list
of existing errata, under the Errata section of that title Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support
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
Please contact us at copyright@packtpub.com with a link to the suspected
pirated material
We appreciate your help in protecting our authors, and our ability to bring you valuable content
Questions
Trang 20The Silverlight Technology
Silverlight as a technology has come a long way We now have Silverlight 5 close
to being released or already released with the publication of this book We see Silverlight as the technology choice for Windows Phone 7 We see it as being a core part of Windows 8 Silverlight has become the standard technology for corporate Line of Business (LOB) applications Because it is a plug-in technology, you don't have to worry about how it will render on disparate browsers or if it will look the same in Mac and Windows
In this chapter, we will take a look at what it means to develop Silverlight
applications and ultimately dashboards We will identify the advantages to using Silverlight as the platform of choice We will cover the following topics:
• What benefits does Silverlight bring to the table
• Client-side application development
• Reduced server load
• Client-side state
• Cross-browser development simplified
• Putting all the pieces together
What benefit does Silverlight bring to the table?
Whether or not you are building enterprise applications, Silverlight can really make your applications look sharp with very little effort Let's dig in and see what Silverlight as a technology brings to the table We will also go over some of the new advancements that Silverlight 5 gives us
Trang 21First, let's discuss what it means to build a Silverlight application The following are some of the areas of Silverlight that we will discuss:
• XAML as a declarative programming model
• Model-View-ViewModel (MVVM)
• Dependency Injection (DI)
• Silverlight as a web technology
• Asynchronous programming in Silverlight
• Silverlight features
XAML as a declarative programming model
Silverlight shares the same power of Windows Presentation Foundation (WPF)
and gives us a rich declarative user interface programming model This helps
facilitate better separation of the user interface and the code that reacts to the user interface Because of this declarative programming model and the rich data-binding
that is inherent in XAML, we can easily put our code in a ViewModel class instead
of the code-behind for the user control Perhaps the biggest benefit for using this model is testing It is a lot easier to write mock tests when we don't have to re-create the user interface, and all we are concerned with are the business rules Another advantage to this model is the ability to reuse our ViewModels across Views This means that we could have two views implemented and use the same ViewModel class For example, one view would be a read-only screen, and the other would be
an edit screen When using a dependency injection (DI) container in your application, MVVM can also be very beneficial to you You can inject all of the dependent services
in your ViewModel, and use them as if you had created them in your own class The beauty of DI is that you are making your code less coupled to other classes You are coding to a contract instead of to an implementation All the tedious ceremony of creating these objects is now the responsibility of the DI container This makes your code easier to test and helps you follow the DRY principle: "Don't Repeat Yourself."
By removing all the calls to create new instances of the dependencies we need, we are in effect reducing redundancy in our code Using a DI container is a little more difficult if you are developing your applications using the View First approach Most major frameworks that currently exist support or allow you to use View First or ViewModel First Let's back up and discuss some of these concepts so, that we are all speaking the same semantic
Model-View-ViewModel (MVVM)
Before we go further, we need to be sure that we are all on the same page with the
Trang 22Data binding
As we can see, we have your user interface defined in the View object This is our XAML markup In Silverlight, these are typically UserControl or Page objects Because XAML has a rich data-binding model, it is easy for us to do our entire markup in XAML and have all the properties that are bound to reside in the ViewModel
The ViewModel acts like a controller This is very similar to the popular ASP
NET MVC programming model that is currently available for web development The ViewModel takes advantage of the rich data-binding model in XAML The ViewModel typically becomes the DataContext of the View It is this magic that allows us to redirect all of your logic from the code-behind of the View to the
ViewModel itself This is very powerful, and data-binding in XAML is flexible enough to allow for multiple levels of ViewModels to be bound on a given page
A typical ViewModel will control the references to any of the backend models and either expose the Model as a single property, or if it needs higher granularity of control around the model, it can expose the Model properties in the ViewModel itself
by using wrapper properties
The Model typically is your data transfer object (DTO) In some models, you may choose to have your models implement the INotifyPropertyChanged (INPC)
interface If you are using the Entity Framework or Linq2SQL , then your models will already have this interface implemented The View has no direct reference to the Model It is only through data-binding that the View is aware of the ViewModel; in this case, the ViewModel is the DataContext of the View
Data Transfer Object (DTO) – A DTO is typically a simple representation
of an item from your database storage The most common correlation
is a DTO representing a table from your database The DTO will have
properties that either map directly to the columns exposed on a table or
a subset of columns The DTO is meant to be kept very light without any business logic You can use DTO to pass data across your layers in your n-tier architecture For example, you would pass a DTO from your data access layer to the business layer In Silverlight, we can either expose
the DTO properties in our ViewModel, or simply have a property on the ViewModel that represents the DTO
Trang 23The following is a sample DTO that also implements INPC:
namespace Dashboard.Models
{
public class ModelBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged =
private string _firstName;
public string FirstName
Trang 24private string _lastname;
public string LastName
to implement the interface, as well as one that uses some extra trickery to allow us
to get an implementation that gives us compile time validation that we have the correct property name One of the issues with the traditional way of implementing this interface is that it uses magic strings, which can really be a problem if you accidentally type in the wrong name for the property We have provided both implementations, but we think you will agree with us once you start using the compile-friendly version
Magic strings – are a hard item to debug, as they require you to perform
testing at runtime What we would like to do is avoid these string
representations as much as possible If we could come up with a way
to represent the name of a property without using a string, we could
potentially avoid running into issues of misspellings and typing errors
Luckily, there are some clever examples that allow us to use lambda
expressions to represent the property name The previous code sample
provides such an example This is nice, as it gives us compile-time checking
as well as supports refactoring of our code; otherwise, we would have to
do some sort of search and replace step if we wanted to rename a property
View First versus ViewModel First
Whenever you start discussing MVVM, you will hear opinions on whether
developing your applications View First or ViewModel First We are not going to settle the debate, but rather introduce you to some of the arguments of each side and let you choose which you like for yourself
Trang 25View First goes on the premise that your Views are created first and then, usually through a locater, the corresponding ViewModel is created If you don't use a
locater to find the corresponding ViewModel, and you use XAML to instantiate your ViewModel, you are limited to the limitations of XAML In order for XAML to work, you must have a default constructor This implies that XAML will only call the empty constructor, and that is probably not what we want to happen if we choose to use any type of dependency injection container To get around this, most developers, using View First, will create a ViewModelLocater class This is typically a class that exposes all of the available ViewModels for the module you are developing as static properties The implementation of the static properties allows you to use your dependency injection container to resolve any dependencies like a logging service Another aspect that makes View First favorable is that it is considered "Blendable", meaning that it is Microsoft Expression Blend friendly
ViewModel First goes on the premise that your ViewModels are created first If you are using Prism, you can inject the View in through your constructor and set the DataContext of the View to the ViewModel itself In Caliburn.Micro, you simply use
a naming convention, and the View for the corresponding ViewModel is resolved automatically Views can become "Blendable" in ViewModel First, but it takes a little extra work to get everything set up correctly When we use the term "Blendable", we are saying that Microsoft Expression Blend supports the ability to see real data from our ViewModel in our XAML while we are designing the UI without ever needing to run the application This is a great time saver and productivity enhancer
Prism – The Patterns and Practices team from Microsoft has done a
great job creating guidance when building componentized enterprise
applications in Silverlight, WPF, and Windows Phone 7 This guidance
provides sample examples and answers a lot of common questions when building enterprise applications Some patterns that Prism solves are
MVVM, event aggregation, dependency injection, and screen navigation Their latest version is Prism 4.0
Trang 26Caliburn.Micro is a small, yet powerful framework designed for
WPF, Silverlight, and WP7 It implements a variety of UI patterns for
solving real-world problems Patterns that are highlighted include
MVVM, event aggregation, dependency injection, and convention over
configuration One of the things that makes Caliburn.Micro stand out
from other frameworks is convention over configuration This powerful concept allows us to create certain conventions to remove the ceremony involved in setting the right configuration By using conventions, this
framework allows to create our XAML with very little markup If we
wanted to expose a TextBox in our XAML, and we named the control
"FirstName", the framework would then look for a String property in the ViewModel with the same name If you had a button that you named
"Save", then the framework would again look for a method with the same name and bind the click event to this method so that it would be called at runtime These are very powerful features, and this is just the tip of the
iceberg when dealing with convention over configuration in Caliburn
Micro The latest version of Caliburn.Micro is 1.2
Dependency Injection (DI)
If we look at most of the popular frameworks or guidelines available for Silverlight,
a very powerful concept becomes evident Silverlight is not the first technology to use dependency injection, and it will not be the last When we talk about DI, we are trying to ensure that we reduce the amount of coupling that happens as we develop our applications When our code is tightly coupled, it becomes very brittle and cannot be changed or refactored Typically, the reason that our code becomes coupled is when we start introducing dependencies, and we code to the concrete implementation of these dependencies We can remove such coupling by coding to the contract instead of the concrete implementation This implies that we code to
an interface Say, for example, you are writing an enterprise application that you want to provide a logging service for logging messages You have several projects that make up your application and several developers working on each model independently This could cause some problems if each developer decided to define their own application programming interface (API) for the logging service It would
be better to create an interface that defines the contract with which you use the logging service Next, instead of using a concrete implementation of the service, you create a reference to the interface you just defined Then, you either inject this interface in via a constructor or a property depending on how you want to do this
Trang 27There are many frameworks that already support this The Microsoft Patterns and Practices team has a guidance named Prism Prism 4.0 is the current version It allows you to use any DI container that you want, but provides out of the box support for Unity and the Managed Extensible Framework (MEF) Another great framework is Caliburn.Micro by Rob Eisenberg It allows you to wire up whatever container you want or use MEF as well It is nice, in that it also promotes a concept of convention over configuration This can really make your XAML markup be very minimal and can speed up your development process Another great framework is MVVM Light
by Laurent Bugnion It is a light framework that allows you to get your applications
up and running using MVVM and also provides means for using DI as well
Using the previous example, the following is the Person class with the constructor setup to receive an object of type ILoggingService:
public class Person : ModelBase
private ILoggingService _loggingService;
public ILoggingService LoggingService
{
get { return _loggingService; }
set { _loggingService = value; }
}
private string _firstName;
public string FirstName
private string _lastname;
public string LastName
{
get { return _lastname;}
set
Trang 28Again, the principle behind DI is that you do not construct or build your own
objects Basically, you never call the "new" keyword; instead, you use a container that "resolves" your objects for you, and during the process, the container provides all the necessary dependencies the class needs This means that the container
instantiates or get a reference to an existing instance of the object you are requesting and also provides all of the dependency objects by supplying them to the constructor
of the object during instantiation
Another example uses MEF to inject a property:
get { return _loggingService;}
set { _loggingService = value;}
}
private string _firstName;
public string FirstName
private string _lastname;
public string LastName
Trang 29Through MEF, we can accomplish the same thing as with Unity or any other
container Both of these containers can provide the same effect, but they differ
in what is required to get everything working MEF requires you to use special attributes for your object composition This means that you must have the ability
to mark up any library that you want to use as part of your dependency injection scenario If you don't have control of a third-party library, you may need to
use another approach, such as Unity In Unity, you are not required to add any attributes If you want to code to contracts, you will need to register your interfaces with the Unity container Unlike MEF, Unity only supports a single implementation
of any interface to be registered If you have multiple implementations with
which you wish to work, you can use a special property on the attribute in MEF to expose named solutions If you are interested in knowing if dependency injection framework is best for you, you should evaluate your core requirements, and then try and pick the one best-suited to your needs If extensibility is key goal to your application, you may consider MEF being the better solution, as it was created to provide an easy way for extending applications where you have full control Unity,
on the other hand, is designed more just to support dependency injection There are many more ways that you can use these features, but becoming aware of them and getting familiar is our main task for now
Silverlight as a Web technology
If you recall developing Visual Basic 6 applications or Windows applications in C++, you probably remember a common term, "DLL Hell." When you installed any application on your Windows computer, the installation process would need to register any DLLs that it needed The problem with this type of registration is that you could have already installed a previous application that used an earlier version
of the same DLL, and now you have just overwritten the registry entry with a new version Next, when you try to access your earlier application, it would give you an error, not being able to find your DLL If you ever wanted to remove an application from your system, you had to be careful that the uninstall process did not remove any DLLs on which other applications depended
Trang 30Another side effect of deploying Windows applications was that it required
installations on every client machine This could become an administrative
nightmare, especially if the product goes through several versions; each version requiring you to perform an installation on the client machine
With NET, we were introduced the concept of "XCopy", and how you could
deploy your applications without ever needing to register your DLLs This
made life a lot better but still required installations of the NET Framework,
and then your application assemblies You still needed to create an installation package, and then require your clients to download or use an installation device
to get the application installed on their machine Silverlight really simplified this paradigm, in that you only had to install your application on a web server, and then all clients could browse to your Silverlight and run your application Silverlight is a plug-in technology and it runs in and out of the browser When you first try to run
a Silverlight application, it performs a check to make sure that the targeted version
of Silverlight is installed in the browser If the browser contains the latest version, then your application is loaded If you need the plug-in, you can click on the link provided and get redirected to Microsoft's Silverlight page for installing the plug-in
A nice thing about Silverlight is that when you need a new version, it will prompt the user and allow the user to install the latest, and then run the application Also, the deployment model for Silverlight is pretty much just like what it would be for deploying a website Silverlight also provides you a rich API that allows you to manage updates to your application You can either automatically check for updates
or provide the user with an on-demand check This really improves the deployment model and gets us very close to the web deployment model
Silverlight is a "stateful" technology Unlike typical web applications where they are "stateless", you don't have to write a lot of extra logic to maintain the "state" of your application Just like programming in Windows Forms or WPF, we can keep the "state" of our application in memory In our data-binding scenarios, we can use our "state" management to provide undo/redo scenarios We can save the "state" of individual user settings and ensure that the settings are applied the next time the user accesses the application
Trang 31Asynchronous programming in Silverlight
Silverlight is designed to keep the UI thread from blocking This means that it doesn't allow us to make server-side calls that could potentially take a long time Even showing dialog boxes in Silverlight happens asynchronously This is actually good from our perspective, in that we never want to write code that would make the user interface appear not to be working properly When we have code that either calls
a web service or opens a dialog box, we need to either provide a callback method that will get fired when the process is complete or wire up an event If we want to open up a dialog box that asks the user to confirm closing a screen, we would need
to first fire off code that would show the dialog box and then, either in our callback
or event, we would check what the user responded and program accordingly This programming model can make your code more complex, in that you can no longer write your logic in a synchronous manner Your logic will be spread across several methods and that can sometimes be hard to follow, especially if you need to enforce
a specific set of workflow actions Microsoft is currently working on making this programming model easier The next version of the NET Framework will more than likely contain the full version of the Visual Studio Async CTP (SP1 Refresh) This programming model allows us to pretty much write asynchronous code as if it were synchronous using a couple of new keywords Async and Await This will help streamline asynchronous programming regardless of whether we are doing this in Silverlight or any other technology
Once you get used to using callbacks or event handlers, you will pretty much have
a good handle on writing asynchronous code that communicates with any backend server or service The next trick is keeping your code clean and readable
Silverlight features
Let's now take a look at what we get out of the box when building rich enterprise application using Silverlight By the time this book is published, Silverlight 5 would have been released or pretty close to being released We will cover the major pieces
of Silverlight 5
Trang 32Silverlight is a subset of Windows Presentation Foundation (WPF) Unlike WPF, you can't run Silverlight as a fully trusted Windows application It has the concept
of elevated permissions to allow us to access local assets on a computer, but it is still sandboxed and will not allow you to run malicious code, just like any other web application running in the browser The same is true for any Silverlight application that is running out of the browser The difference between in and out of the browser becomes even harder to distinguish with Silverlight 5 Previously, if you were running your Silverlight application out of the browser, you could request your application to become a "trusted application." This provided you with several enhancements Here is a short list of some of the features of a "trusted application":
• Ability to host a browser control in your application
• Direct access to the My Documents folder directly without any prompting
of the user
• Full keyboard support in full-screen mode
• COM Automation is fully supported allowing you to launch other
applications on the computer
• Access to USB components, e.g., a bar-code reader
• Calling unmanaged code directly using PInvoke
All of the features are now available to you in the browser with Silverlight 5
The following is a sample application that Microsoft introduced to demonstrate a
"trusted application" using COM to access a Blood Glucose monitor:
Trang 33Here is another example demonstrating an out of browser "trusted application":
If you are looking to writing a rich media application, then Silverlight 5 definitely delivers great capabilities
• You now have the ability to use the GPU to render high-definition video and improve the overall performance of your application This is especially important with the rise of tablets and Netbooks being used
• TrickPlay allows you to play your video at different speeds, including performing fast-forward and rewind You can even use audio pitch
correction for up to twice the speed of normal allowing users to still watch their video without losing the audio quality
• User can now control media playback using remote-control support
• Digital rights management enhancements now allow you to switch
seamlessly between media sources
If you are trying to build rich enterprise line of business applications, the following improvements will definitely be a factor in wanting to use Silverlight 5:
• Multi-column text and linked text container allow you to control the flow of text across multiple columns
• Character spacing in the form of tracking/leading for precise text layout
Trang 34• Support for Postscript vector printing for creating reports and documents, even creating virtual previews.
• Support for double-clicking
• Type-ahead support in the ComboBox (Type-ahead means that you can now type a letter in the ComboBox, and it will find the first match that starts with that character)
The following screenshot shows some of the improvements of text in Silverlight 5:
Probably one of the biggest areas of improvement with Silverlight 5 is its rich data binding and MVVM support Here is a list of some of the improvements:
• Ability to now add breakpoints in your XAML on your data bindings
Hopefully, this feature will also be added to WPF in the next release of NET
• Implicit DataTemplates is a welcome addition that now allows the runtime to choose the correct DataTemplate based on type
• Ancestor RelativeSource allows us to walk the VisualTree and bind to parent
or child controls based on their hierarchical relationship
• Styles now have the ability to have bindings in their setters for referencing other properties
• DataContext will now notify us when it is being changed through a new event, "DataContextChanged."
• Markup extensions used in XAML allow us to have code run during the parsing of both properties and event handlers
Some of the performance and graphics enhancements with Silverlight 5 include the following:
• Support for 64-bit operating systems
• Network latency is reduced by utilizing a background thread for networking
Trang 35• XAML parser improvements that have increased runtime performance
and startup
• Graphics Processing Unit (GPU) accelerated 3-D application programming
interface (API) allows for building rich visualizations
• Ability to render directly to the GPU using an immediate mode graphics API
• Internet Explorer 9-provided hardware acceleration is enabled in
windowless mode
The following is a screenshot of a sample application from Microsoft demonstrating
the 3D capabilities of Silverlight 5:
Another cool feature in Silverlight 5 is the enhanced Window Previously, Silverlight
didn't support multiple top-level windows and if you wanted to have a popup,
it always was bound by the physical constraints of the parent window Now, you
can use the Window class and have multiple top-level windows This only works
for Silverlight applications that are running out of the browser, but this gives you
a lot of power and control when writing applications that can take advantage of
multiple monitors
Trang 36Client-side application development
When developing Silverlight applications, it is important to remember that Silverlight runs on the client This means that if you need any information from the server, you need to asynchronously make a call back to the server with your request An advantage of client-side development is the fact that we can do some powerful
things in Silverlight without ever needing to run client-side JavaScript or any other technology Silverlight allows us to run Storyboards and other Behaviors and Triggers
to make our application focus on a great user experience We have seen some of the new capabilities and features of Silverlight 5 and how we can now tap into the power
of the client GPU for some really nice graphics and animations We also have the ability to interact with other Microsoft Office applications and make it look like Office
is just an extension to our application; for example, creating emails, opening Word documents, or even building an Excel WorkSheet with charts and everything
When we build our rich enterprise application, we want to ensure that the user experience is truly engaging and allows the user to work in a quick and efficient manner Part of that delivery is the ability to design and develop applications that act and respond behaviorally as we would expect anything in the real world If we start
to compare the paradigm of a user doing their job manually using documents and files, we can start to provide the same and hopefully better experience by providing sleek animations when certain behaviors are expected We want a fluid user interface that reacts and displays information and prompts just as we would do in the real world We don't mean that we should just take what the user did in real life and recreate it without thought or creativity; rather, we are saying that we believe that
by following the natural physics of the real world and applying user intuitive effects, the application will get quicker buy-in and acceptance than just building a legacy battleship-gray forms application
Reduced server load
When we run Silverlight applications, a typical XAP file gets downloaded on to the client machine The application is then executed either in or out of the browser If the application has been developed to support an out of browser experience, you can choose to run it out of the browser Because Silverlight runs on the client, we don't have the same issues like that of a traditional web application Typical web applications put all the stress on the web server, unless you are using something like client-side JavaScript The processing power to run and render our applications now falls to the client machine This is an advantage in that we can have some really powerful applications running without relying on a super web server that is required
to do all the processing
Trang 37Silverlight is still a web technology Even though Silverlight applications run on the client machine, it is deployed to a web application server This really helps remove the added maintenance when dealing with WPF or Windows Forms applications that require some form of installation.
When building Silverlight applications, you will still have a need for a server
presence One good example is that of data access You can use technologies like Windows Communication Foundation (WCF) There are many flavors of WCF; you can use WCF RIA Services, WCF Data Services, plain old WCF operations, and OData
Client-side state
Probably one central aspect that makes web development complicated is the lack
of state Most websites are designed to be stateless, and it makes sense when you realize that if we tried to maintain state for all concurrent users accessing and using the application, your server would be overloaded Sure, we need to provide caching and optimizations on the server regardless of what style of architecture that we are using but when we develop Silverlight applications, we get the added benefit
of being able to use the client's memory and storage just like any other desktop application You may be thinking that this is also possible with current technologies
as well Yes, you are right, but with Silverlight you can do all this in the exact same technology and language of choice without ever needing to import or download a library to let you work on the client What we are saying here is that you have a lot
of inherent efficiencies when you develop applications with Silverlight You can still gain this momentum and inertia with web development as well, but there are a lot more moving parts and pieces that need to be put together as well as testing your code across all the target browsers you wish to support
In Silverlight, we have the ability to access local storage in the My Documents location on Windows and the Documents location on the Mac This gives us the ability to create occasionally connected applications that can even run when our Internet connection is lost and then sync any changes that were made from our local storage back to a server
Trang 38Cross-browser development simplified
Probably one of the most frustrating aspects of web development is the need to
be sure that your code renders the same across all browsers If you use Microsoft Expression Web, you can use the Super Preview feature that allows you to preview your code in various browsers This helps a lot, but it is unfortunate that each
browser potentially renders your hard work in a way that was not intended We want our applications to be cross platform, because we want our users to be able to run our application from Windows or Mac, or any browser and have the same user experience This is hard to do when just developing web applications that depend on independent browsers Each browser can potentially render our application slightly different from the other
With Silverlight, because it is a plug-in technology, you don't need to worry about whether or not your application is going to look right using Internet Explorer or Google Chrome; we can be assured that it will just work We can pretty much be assured the same experience between Windows and Mac operating systems as well There are some things that we need to take when we are developing an application that is to run on both Windows and Mac OS Silverlight has some advanced features that have been tailored to work with the Windows operating system If you want to your application to run on the Mac as well, you need to take care not to use certain features, like Toast Notifications or COM Automation
Overall, Silverlight makes perfect sense if you are getting ready to build an
enterprise line-business application
Putting the pieces together
Now that we've established that Silverlight is a premium platform for creating web applications and dashboards, let's see what it takes to get your environment set up for using Silverlight The following list should get you started with building rich Silverlight applications:
• Visual Studio Requirement
° Microsoft Visual Web Developer 2010 Express
Trang 39• Microsoft WCF RIA Services V1.0 SP2 Preview (optional)
• Microsoft Expression Blend Preview for Silverlight 5 (optional)
• Microsoft Expression Blend 4 (optional)
• NuGet (optional)
• Microsoft Silverlight Toolkit
We will be using Microsoft Visual Studio 2010 with Service Pack 1 for our
development If you want to use Microsoft WCF RIA Services, you can install the latest service pack that is compatible with Silverlight 5 Sometimes, it is easier to do our design work with Microsoft Expression Blend You ought to either use the latest version that is compatible with Silverlight 5, or use their current released version that works with Silverlight 4
A tool that will really help you as you develop your solutions is the new tool
NuGet NuGet is a Visual Studio extension that allows you to install and update open source libraries and tools If you have NuGet installed, you can then install the Microsoft Silverlight Toolkit or other packages, like Prism, Caliburn.Micro, Entity Framework 4, and so on
Summary
In this chapter, we took a look at the benefits of what Silverlight brings to the table
We reviewed the latest features on what Silverlight 5 will contain We discussed the advantages of doing client-side development, and where it makes your development much easier by allowing to you to develop the whole application lifecycle without depending or using another technology We discussed the reduced server load, even though Silverlight is a web-based technology State management is simpler due to the fact that you are basically developing your application just like you
would a Windows Forms or WPF application When using elevated permissions, you can have direct access to the user's documents folder and transparently manage documents without needing to prompt the user We then finished by examining how developing Silverlight applications really simplified the whole issue with cross-browser support Because Silverlight is a plug-in technology, you don't have to worry about whether your application will behave or look correctly across browsers
In the next chapter, our focus will be looking at how building dashboards fit in with Silverlight
Trang 40and what is contained in certain aisles All of these signs and indicators are great examples of providing information to the user at the right time.
Dashboards are part of a larger unit within technology named, Business Intelligence (BI) Business intelligence tries to sift through the wealth of data that resides in an
organization and render it to the end user in the most appropriate medium possible Reporting, spreadsheets, and OLAP cubes are some of the ways BI is accomplished within an organization Dashboards typically are the first thing executives and
managers see when they start work in the morning, and most likely the last thing they look at before leaving for the day Providing good business intelligence is a very hard target to hit It requires a coordinated effort across multiple departments and domains and can cause a lot of confusion Good business intelligence can put
an organization in a position where it can dominate in its demographic What
dashboards try to do is present pertinent information to the business user at the right moment and level as to where the business user can make actionable decisions based
on that information We stress the word information, because it is not just raw data
that is being presented to the business Many hours of investigation and discovery goes into identifying what is the correct level of information to be composed into the right dashboard element
Dashboards have come a long way since they were first introduced