Building Enterprise Applications with Windows Presentation Foundation and the Model View ViewModel Pattern

Size: px
Start display at page:

Download "Building Enterprise Applications with Windows Presentation Foundation and the Model View ViewModel Pattern"

Transcription

1

2 Buildig Eterprise Applicatios with Widows Presetatio Foudatio ad the Model View ViewModel Patter Raffaele Garofalo

3 Published with the authorizatio of Microsoft Corporatio by: O Reilly Media, Ic Gravestei Highway North Sebastopol, Califoria Copyright 2011 Raffaele Garofalo. Complyig with all applicable copyright laws is the resposibility of the user. All rights reserved. Without limitig the rights uder copyright, o part of this documet may be reproduced, stored i or itroduced ito a retrieval system, or trasmitted i ay form or by ay meas (electroic, mechaical, photocopyig, recordig, or otherwise), or for ay purpose, without express writte permissio of O Reilly Media, Ic. Prited ad boud i the Uited States of America LSI Microsoft Press titles may be purchased for educatioal, busiess or sales promotioal use. Olie editios are also available for most titles ( For more iformatio, cotact our corporate/istitutioal sales departmet: (800) or corporate@oreilly.com. Visit our website at microsoftpress.oreilly.com. Sed commets to mspiput@microsoft.com. Microsoft, Microsoft Press, ActiveX, Excel, FrotPage, Iteret Explorer, PowerPoit, SharePoit, Webdigs, Widows, ad Widows 7 are either registered trademarks or trademarks of Microsoft Corporatio i the Uited States ad/or other coutries. Other product ad compay ames metioed herei may be the trademarks of their respective owers. Uless otherwise oted, the example compaies, orgaizatios, products, domai ames, addresses, logos, people, places, ad evets depicted herei are fictitious, ad o associatio with ay real compay, orgaizatio, product, domai ame, address, logo, perso, place, or evet is iteded or should be iferred. This book expresses the author s views ad opiios. The iformatio cotaied i this book is provided without ay express, statutory, or implied warraties. Neither the author, O Reilly Media, Ic., Microsoft Corporatio, or their respective resellers or distributors, will be held liable for ay damages caused or alleged to be caused either directly or idirectly by such iformatio. Acquisitios ad Developmet Editor: Russell Joes Productio Editor: Kriste Borg Productio Services: Octal Publishig, Ic. Techical Reviewer: David Hill Idexig: Fred Brow Cover: Kare Motgomery Illustrator: Robert Romao

4 To my wife Deborah. Thak you for everythig!

5

6 Cotets at a Glace 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios Desig Patters The Domai Model The Data Access Layer The Busiess Layer The UI Layer with MVVM MVVM Frameworks ad Toolkits v

7

8 Table of Cotets Itroductio xi Covetios ad Features i This Book xv Ackowledgmets xviii Errata ad Book Support xix 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios The Model View ViewModel Patter Lie of Busiess Applicatios Choosig the Right Techology Silverlight or WPF? Microsoft s UI-Buildig Tools Compositio of a LOB User Iterface The Meubar The Toolbar The Tooltip (ad Its Abuse) Notificatios ad Alerts The Ribbo Bar Geeral Style ad Cotrol Cosideratios Separatio of Cocers Layers, Tiers, ad Services Summary Desig Patters A Overview of Desig Patters Classifyig Desig Patters UI Desig Patters The MVC Patter The MVP Patter The PM Patter ad MVVM Advaced Desig Patters ad Techiques The Iversio of Cotrol Patter DSLs: Writig Fluet Code Itroductio to TDD Summary vii

9 viii Table of Cotets 3 The Domai Model Itroductio to Domai-Drive Desig DDD Termiology Aalyzig the CRM Domai Domai Etity ad Data Trasfer Object The POCO Object ad the O/RM Developmet Approaches of a Domai Trasactio Script Database-Drive Approach Domai-Drive Approach How To Create a Object I DDD Factory Patters Domai Etities Validatio Classic Validatio Validatio Usig Attributes ad Data Aotatios Available Validatio Frameworks Uit Test the Domai Model Sample Code: The CRM Domai Model The Perso Cotext The Order Domai Summary The Data Access Layer Itroductio The Database ad Stored Procedures Choosig a O/RM Microsoft Etity Framework NHiberate Other O/RMs for.net The Uit of Work Lifecycle of a UoW Idetify a Busiess Trasactio The Repository Patter Test-Drive Developmet: The Data Layer Buildig a Distributed Data Layer with RIA ad WCF

10 Table of Cotets ix Sample Code: The CRM Data Access Layer A Flexible IUitOfWork Iterface Mappig the Domai Model Usig Etity Framework Mappig the Domai Usig NHiberate Gettig the Tools The UitOfWork ad the ISessio Summary The Busiess Layer Itroductio A Busiess Rule Is Not a Validatio Rule Busiess Rules by Service The Facade Patter Busiess Rules by Workflow with WF Differet Ways of Ruig a Workflow Third-Party Toolkits Techologies for the Data Validatio Rule Egie ad Busiess Rule Egie Busiess Layer Cosideratios Whe Do I Need to Create a Busiess Layer? Bad BLL Habits Sample Code: The Busiess Service Layer Data Validatio with the Eterprise Library A Geeric Workflow Egie Service for Busiess Trasactios Summary The UI Layer with MVVM Itroductio to the MVVM Patter The View Bledability: A Dummy ViewModel The Model The Commad i WPF ad Silverlight A Workaroud: A MVVM Commad Re-evaluate ICommad Executio The ViewModel The INotifyPropertyChaged Iterface The IDataErrorIfo Iterface

11 x Table of Cotets DataTemplate i WPF ad Silverlight DataTemplate ad MVVM WeakEvets ad Messages The WeakEvet Patter The EvetAggregator Patter Dialogs ad Modal Pop-Ups Modal View i MVVM Iversio of Cotrol with MVVM Sample Code The Microsoft Office Ribbo ad MVVM Summary MVVM Frameworks ad Toolkits MVVM Toolkits MVVM Light Toolkit, by Lauret Bugio MEFedMVVM Cich, by Sacha Barber MVVM ad XAML Facilities Karl Shifflett s Tools Radical, by Mauro Servieti Composite UI Frameworks Microsoft Prism Calibur What do you thik of this book? We wat to hear from you! Microsoft is iterested i hearig your feedback so we ca cotiually improve our books ad learig resources for you. To participate i a brief olie survey, please visit:

12 Itroductio The Widows Presetatio Framework (WPF), Silverlight, ad Widows Phoe 7 are the latest techologies for buildig flexible user iterfaces (UI) for applicatios built with Microsoft techology. All three rely o the XAML markup laguage to describe UI elemets ad layout, ad you ca program applicatios for all three platforms with the most commo of Microsoft.NET Framework laguages: Visual C# or Visual Basic.NET. If you are a.net developer plaig to create a ew Lie of Busiess (LOB) applicatio usig the.net Framework, you should cosider adoptig oe of these techologies as your UI techology. At the same time, as you start plaig to build a applicatio based o oe of these techologies, you should also seriously cosider learig ad applyig the Model View ViewModel (MVVM) presetatio patter, a desig patter created specifically for these techologies. Ad that s what this book is about. You might be woderig, Why aother book o WPF? Or, if you have already looked at the Table of Cotets, you might be thikig, Why aother book about layerig ad desig patters? To aswer those questios, let me start by sayig that over the years, I have oticed that what developers ask for the most is ot the Bible of patters or the Bible of how to layer a applicatio; istead, they wat a simple, straightforward book that guides them through the developmet criteria for a real-world, yet simple, applicatio that uses ad explais patters but that is also reusable i future projects as a template for other applicatios. WPF ad Silverlight are youg techologies, ad the percetage of developers movig to this ew way of desigig the UI is still small. There are several reasos for this. First, the learig curve is relatively high. If you re used to Widows Forms, Java Swig, or Delphi, the way you desig ad structure a applicatio usig XAML ad WPF is sigificatly differet i fact, I would call it revolutioary. I the past, I have used well-kow patters to build applicatios, icludig the Model View Preseter patter with Widows Forms applicatios, ad the Model View Cotroller patter with ASP. NET applicatios. But with WPF, these two approaches are ow obsolete, because they ca t take advatage of the powerful egie provided by XAML. Of course, you ca still take advatage of the bidig egie of WPF usig the Model View Preseter patter, but the effort required is usually too large. Fortuately, MVVM provides a alterative. Microsoft, i collaboratio with some architects, has revised the origial Presetatio Model that was proposed years ago by Marti Fowler. This revisio (amed the Model View ViewModel patter) is the perfect approach for WPF ad Silverlight because, well, it was desiged specifically for them! Ufortuately, like XAML, MVVM is a relatively ew techology, so at the momet, there is t a lot of iformatio about implemetig it. There are a few bloggers tryig the MVVM approach ad bloggig about it; others are ivolved i buildig MVVM-specific toolkits. But early everythig is still experimetal, ad there are few truly cocrete examples. xi

13 xii Therei lies the ratioale for a book about buildig a LOB applicatio usig MVVM. As you proceed through this book, you will see examples that show how to build a straightforward Customer Relatioship Maagemet (CRM) program with WPF 4, Silverlight 4, ad the MVVM patter. The book guides you through the etire architectural process, illustratig the correct approach to usig MVVM. You ll also use some other ew techologies delivered with Microsoft.NET 4, such as Maaged Extesios, Widows Workflow Foudatio 4, ad of course, the Etity Framework. First, you are itroduced to the tools. Next, you move ahead to build the CRM, startig with the domai model, applyig a simple techique to persist the data i a relatioal database by usig two of the most popular Object-Relatioal Mapper (O/RM) systems available for.net: the Etity Framework ad NHiberate. The, see how to make everythig more flexible usig the MEF framework. Followig that, you lear to apply busiess logic ad data validatio to this model i a way that fulfills the requiremets of the MVVM patter. I this phase, you also look at Widows Workflow Foudatio (WF) 4.0, the powerful, ew workflow egie by Microsoft, ad study the steps required to build a simple workflow egie. The remaiig chapters all focus o MVVM. There are four major cocepts that you must lear to use MVVM correctly: commadig, the template, the bidig egie, ad how to orchestrate everythig together. At the ed of this process, you will have visited all the layers required to complete a classic LOB applicatio, but more importatly, you will be able to recycle the parts described here as a template for buildig future applicatios. Of course, there are some differeces betwee WPF ad Silverlight, so this book will try to cover those gaps where possible. Fially, you will take a brief tour of the MVVM toolkits that are already available, such as PRISM, a composite applicatio framework for WPF ad Silverlight. This will help you to determie whe ad how you should use each as part of the process of buildig a small ad flexible MVVM framework. Overall, the key goal of this book is to provide a complete step-by-step guide for usig WPF/Silverlight i cojuctio with MVVM for creatig geeric code that you will be able to use ad reuse i the future. Buildig Eterprise Applicatios with Widows Presetatio Foudatio ad the Model View View- Model Patter provides ot oly a solid aalysis of how the MVVM patter works ad how to apply it with WPF ad Silverlight, but it also offers a exhaustive guide to buildig layered applicatios by usig the most commo ad accepted techiques. This book itetioally does t show all the related code for ay give project; istead, it focuses more o the priciples ad patters that developers should apply to create well-structured ad easy-to-maitai LOB applicatios. The book aalyzes each layer that composes a LOB applicatio, startig with the Domai Model (also kow as the Busiess Layer), movig to the Data Layer (icludig a overview of Etity Framework ad NHiberate), ad edig with a chapter dedicated to Busiess Rules ad Widows Workflow Foudatio. Of course, you will also fid a chapter dedicated to the MVVM patter.

14 I additio to the patters ad practices explaied i the book, Chapter 7 cotais a useful list of ope source frameworks ad plug-is used by others i the.net commuity to build applicatios that implemet the MVVM patter with WPF or Silverlight. Who Should Read this Book This book is for ay.net developer or software architect who wats to lear how to build LOB applicatios usig well-kow eterprise architecture patters, icludig the MVVM patter. Readers should already have a solid geeral kowledge of programmig, be familiar with the overall purpose ad applicatio of patters, ad of course, kow WPF, Silverlight, or Widows Phoe 7. While the book touches all these topics, it does t attempt to teach basic programmig or patter applicatio priciples. Istead, it s aimed at developers ad architects who have already built.net applicatios ad are ow movig toward desigig ad buildig eterprise applicatios with.net. Specifically, this book targets WPF or Silverlight developers who already have experiece with oe or both of these techologies, but who do t yet kow how to implemet the MVVM patter or developers who have some exposure to MVVM ad wat to master the techiques to apply the MVVM patter effectively. To do that, you must have some basic kowledge of WPF ad Silverlight; if you do t, I suggest you familiarize yourself with the topics of routed commads, data bidig, data templates, ad stylig before readig this book. Assumptios With a heavy focus o desig patters, software architectures, ad agile techiques ad methodologies, this book assumes that you have a basic uderstadig of how to create a WPF or Silverlight applicatio with.net Framework ad Visual Studio. It further assumes that you have already developed a applicatio that coects to a database, icludig a UI that iteracts with users. All the sample code provided i the book was created usig the Visual C# laguage provided with.net Framework 4. You eed a solid uderstadig of C# to follow ad use the code. The book works with both WPF ad Silverlight extesively, so you should have at least a basic kowledge of these two techologies (ad a firm groudig i the XAML markup laguage as well the book uses some XAML sample code). Orgaizatio of This Book This book has bee developed i such a way that each chapter focuses o a specific topic. The first chapter, Itroductio to Model View ViewModel Applicatios, is a geeral itroductio to LOB applicatios, their compoets, ad their structure. Chapter 2, Desig Patters, shows a complete overview of all the well-kow desig patters ad architectural patters used to develop eterprise applicatios, ad more geerally, to develop loosely-coupled compoets. Chapter 3, The Domai Model, is a itroductio to the domai model ad Domai-Drive Desig (DDD). It illustrates how to achieve DDD desig goals, ad how to avoid commo mistakes that typically occur xiii

15 xiv whe buildig a DDD applicatio. Chapter 4, The Data Access Layer, cocetrates o the Data Access Layer (DAL) ad how you ca build oe by usig a O/RM, such as Etity Framework ad/or NHiberate. Chapter 5, The Busiess Layer, focuses its attetio o the desig ad costructio of a Busiess Logic Layer (BLL), icludig i-depth coverage of busiess rules, busiess rule egies, ad Service-Orieted Architecture (SOA) desigs. Fially, Chapter 6, The UI Layer with MVVM, discusses MVVM i depth, while Chapter 7, MVVM Frameworks ad Toolkits, lists available frameworks ad tools that you might fid useful whe buildig LOB applicatios with MVVM. Fidig Your Best Startig Poit i This Book The chapters of the book cover differet aspects of buildig a eterprise LOB applicatio. Except for the first two chapters, which are more of a geeral overview of the techiques used i the book, each chapter focuses o a specific layer of a LOB applicatio. The followig table may help you determie how best to proceed if you pla to focus oly o a specific layer. If you are New to LOB applicatios ad layered applicatios Familiar to Desig Patters ad Software architectures, but ot mastered yet Iterested oly i a specific layer, such as the DAL or BLL Iterested oly i MVVM Follow these steps Read the etire book ad experimet with the solutios used as examples i each chapter. Briefly skim Chapters 1 ad 2 for a quick review of the core cocepts. The read the remaiig chapters carefully, workig to apply the priciples you ll ecouter i each chapter to your daily tasks. Carefully read the specific chapter that covers the layer i which you re iterested. However, to set the cotext, you should also skim the other chapters. Read chapters 1 ad 2 to fortify your kowledge about desig patters ad presetatio patters, ad the read chapters 6 ad 7 carefully.

16 Covetios ad Features i This Book xv This book presets iformatio usig covetios desiged to make the iformatio readable ad easy to follow. I most cases, the book icludes separate exercises for Visual Basic programmers ad Visual C# programmers. You ca skip the exercises that do ot apply to your selected laguage. Boxed elemets with labels such as Note provide additioal iformatio or alterative methods for completig a step successfully. Text that you should type (apart from code blocks) appears i bold. A plus sig (+) betwee two key ames meas that you must press those keys at the same time. For example, Press Alt+Tab meas that you hold dow the Alt key while you press the Tab key. A vertical bar betwee two or more meu items (for example, File Close), meas that you should select the first meu or meu item, the the ext, ad so o. System Requiremets You will eed the followig hardware ad software to work with the code ad examples i this book: Ay of the followig operatig systems: Widows XP with Service Pack 3 (except Starter Editio), Widows Vista with Service Pack 2 (except Starter Editio), Widows 7, Widows Server 2003 with Service Pack 2, Widows Server 2003 R2, Widows Server 2008 with Service Pack 2, or Widows Server 2008 R2. Visual Studio 2010, ay editio (multiple dowloads might be required if usig Express Editio products). SQL Server 2008 Express Editio or higher (2008 or R2 release), with SQL Server Maagemet Studio 2008 Express or higher (icluded with Visual Studio, Express Editios require separate dowload). 1.6 GHz or faster processor (2 GHz recommeded). 1 GB (32-Bit) or 2 GB (64-Bit) RAM (Add 512 MB if ruig i a virtual machie or SQL Server Express Editios; more for advaced SQL Server editios). 3.5 GB of available hard disk space.

17 xvi 5400 RPM hard disk drive. DirectX 9 capable video card ruig at or higher resolutio display. DVD-ROM drive (if istallig Visual Studio from DVD). Iteret coectio to dowload software or chapter examples. Depedig o your Widows cofiguratio, you might require Local Admiistrator rights to istall or cofigure Visual Studio 2010 ad SQL Server 2008 products. Code Samples Most of the chapters i this book iclude exercises that let you iteractively try out ew material leared i the mai text. All sample projects, i both their pre-exercise ad post-exercise formats, are available for dowload from this book s page o the website for Microsoft s publishig parter, O Reilly Media: Click the Examples lik o that page. Whe a list of files appears, locate ad dowload the Mvvm- Crm.zip file. Note I additio to the code samples, your system should have Visual Studio 2010 ad SQL Server 2008 istalled. The istructios below use SQL Server Maagemet Studio 2008 to set up the sample database that is used with the practice examples. If available, istall the latest service packs for each product. Istallig the Code Samples To istall the code samples o your computer 1. Uzip the MvvmCrm.zip file that you dowloaded from catalog/ /. 2. If prompted, review the displayed ed user licese agreemet. If you accept the terms, select the accept optio, ad the click Next. Note If the licese agreemet does t appear, you ca access it from the same web page from which you dowloaded the MvvmCrm.zip file.

18 Usig the Code Samples xvii The structure of the Visual Studio solutio provided with the book is divided ito six differet projects, i which each project composes the full source code of the related chapter i the book. The etire applicatio the composes the CRM program, developed i WPF.

19 xviii Ackowledgmets Whe you are the sole author of a book, you are idelibly associated with that book s merits; i fact, this is oe of the reasos may people wat to write a book. But eve as a sole author, you are t the oly perso resposible for a book becomig a reality. I wat to thak all the people who have helped me to write ad publish this book, because without them, it would have remaied just a idea. This is my first book. Writig it has bee a amazig adveture for me, ad I hope this is just the begiig of somethig ew; somethig I feel is my atural bet. I would t have bee able to write this book without the immese help of my woderful wife, Deborah. Writig a book requires time, ad I work full time for a isurace compay, so the few remaiig hours of the days spet writig the book ad lookig for documetatio (which took a full six moths) were take out of my time with her. Without such a tremedous ad uderstadig wife, I probably would t have bee able to take that time. May times, whe I was close to quittig without fiishig the book due to its complexity ad the sheer volume of iformatio she steadfastly pushed me to complete the job, just as a perfect project maager should do! Thaks, Debbie! I also wat to thak Russell Joes, my editor ad primary publishig cotact for this book. He is the oly perso who believed i me from the begiig, ad he put himself o the lie to get this project approved by Microsoft Press. I will always be thakful to him for that. He also did a woderful job i helpig me to complete the job o time ad to orgaize the whole project. Fially, I wat to thak David Hill, who is both this book s techical reviewer ad my metor. David is a techical lead at Microsoft i the patters & practices team. Havig his ivaluable isight while writig this book helped a great deal to refie ad improve my uderstadig of presetatio patters i geeral as well as the right way to architect a Lie of Busiess applicatio. David is both flexible ad modest. I am extremely fortuate to have had the opportuity to work with him, ad fervetly hope to work with him agai i the future. Thaks, guys!

20 Errata ad Book Support xix We ve made every effort to esure the accuracy of this book ad its compaio cotet. If you do fid a error, please report it o our Microsoft Press site at oreilly.com: 1. Go to 2. I the Search box, eter the book s ISBN or title. 3. Select your book from the search results. 4. O your book s catalog page, uder the cover image, you ll see a list of liks. 5. Click View/Submit Errata. You ll fid additioal iformatio ad services for your book o its catalog page. If you eed additioal support, please Microsoft Press Book Support at mspiput@microsoft.com. Please ote that product support for Microsoft software is ot offered through the addresses above. We Wat to Hear from You At Microsoft Press, your satisfactio is our top priority, ad your feedback is our most valuable asset. Please tell us what you thik of this book at: The survey is short, ad we read every oe of your commets ad ideas. Thaks i advace for your iput! Stay i Touch Let s keep the coversatio goig! We re o Twitter at

21

22 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios After completig this chapter, you will be able to: Idetify a Lie of Busiess applicatio. Decide which is the right techology for you to develop a Lie of Busiess applicatio. The Model View ViewModel Patter The Model View ViewModel (MVVM) patter was itroduced by Joh Gossma (Software Architect at Microsoft for Widows Presetatio Foudatio ad Silverlight techologies) i 2005 o his blog. MVVM is a specializatio of the Presetatio Model (PM) patter that was itroduced i 2004 by Marti Fowler. Oe of the mai goals of the PM patter is to separate ad abstract the View the visible user iterface (UI) from the presetatio logic to make the UI testable. Additioal goals might iclude makig the presetatio logic reusable for differet UIs ad differet UI techologies, reducig the couplig betwee the UI ad other code, ad allowig UI Desigers to work i a more idepedet maer. MVVM is a specialized iterpretatio of the PM patter desiged to satisfy the requiremets of Widows Presetatio Foudatio (WPF) ad Silverlight. Structurally, a MVVM applicatio cosists primarily of three major compoets: the Model, the View, ad the ViewModel. The Model is the etity that represets the busiess cocept; it ca be aythig from a simple customer etity to a complex stock trade etity. The View is the graphical cotrol or set of cotrols resposible for rederig the Model data o scree. A View ca be a WPF widow, a Silverlight page, or just a XAML data template cotrol. The ViewModel is the magic behid everythig. The ViewModel cotais the UI logic, the commads, the evets, ad a referece to the Model. I MVVM, the ViewModel is ot i charge of updatig the data displayed i the UI thaks to the powerful 1

23 2 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios data-bidig egie provided by WPF ad Silverlight, the ViewModel does t eed to do that. This is because the View is a observer of the ViewModel, so as soo as the ViewModel chages, the UI updates itself. For that to happe, the ViewModel must implemet the INotifyPropertyChaged iterface ad fire the PropertyChaged evet. Iitially, oly WPF was powerful eough to satisfy the MVVM patter s requiremets. I Silverlight 2, you had the optio of implemetig MVVM, but it was harder tha implemetig MVVM with WPF. Now, with Silverlight versio 4, you ca apply MVVM to both WPF ad Silverlight i the same way, usig the power of data-bidig, commadig, behaviors, ad data templates. Whe you apply the MVVM patter, you must take special care with the ViewModel. Because it has so may resposibilities, it s easy to create messy solutios i which you fid yourself writig the same code agai ad agai. However, whe usig a proper approach, the MVVM patter ca save time ad helps to make your UI testable ad easy to maitai. Of course, to use MVVM properly, it s madatory that you master XAML ad its UI structure. You also eed to kow how the bidig egie of XAML works ad how commad objects ad commad behaviors (ICommad) ad data templates are structured. Fially, to use MVVM effectively with both WPF ad Silverlight, you eed to kow about the differeces betwee WPF ad Silverlight. This book aalyzes each compoet of the MVVM patter i depth. At the ed, you will create a simple MVVM Lie of Busiess applicatio that ca be used as a template for ay future MVVM applicatio. At the same time, you ll build a small utility MVVM framework that fuctios as a plug-ad-play compoet that you ca use i your WPF or Silverlight applicatios to simplify writig MVVM applicatios. For example, the framework will provide a basic ViewModel class, a sample Message Broker, ad other features required i a typical MVVM applicatio. Lie of Busiess Applicatios I my experiece, the best way to lear a techology is by doig buildig a applicatio step by step. A Lie of Busiess (LOB) applicatio makes the best example for several reasos: it s suitable for the flexible UI techology foud i both WPF ad Silverlight; it s ameable to the MVVM patter; ad it s a commo applicatio type, so you ca reuse the examples later, for real busiess purposes. Note LOB applicatios are those that are vital to ruig a eterprise, such as accoutig, supply chai maagemet, or resource plaig. LOB applicatios are usually large programs that cotai a umber of itegrated capabilities, ad tie ito other applicatios ad database maagemet systems. They are also commoly referred to as eterprise applicatios.

24 Choosig the Right Techology 3 A LOB applicatio ca be ay busiess-critical applicatio: the CRM used i the office, the accout software used by the fiacial departmet to prepare the payroll, or ay other type of busiess applicatio that follows specific guidelies ad that has a specific commo UI style. If you thik about it, such applicatios fit perfectly ito the cocept of a template. LOB applicatios are both the most requested by customers ad the easiest to develop. But at the same time, they are the most difficult to develop. This is because while their structure is usually pretty simple ad redudat, their requiremets ofte chage durig the developmet process as well as durig their lifetime. Icreasigly, LOB applicatios are gaiig web iterfaces, makig them easy to access via browsers, easier to deploy ad update, ad because they eable some busiess scearios that require both busiess parters ad customers to access the same features. They re also acquirig persoal applicatio features, such as ad address books. A LOB applicatio follows a icremetal desig, especially durig the developmet process. A Scrum project maagemet book that I read a while ago (thaks to my CTO, who has a addictio to agile techiques) metioed that the greatest expeditures of IT departmets ad software houses is for maiteace of existig software. Usually, people ivolved i a software project of ay type believe that the most expesive part is the developmet phase leadig to the iitial release, but it s oly after the release that the real pai starts. For example, suppose that you create ad sell a accoutig applicatio that was ot origially desiged to iclude HR payrolls. After a while, customers will ask you for this ew feature. If your desig is ot flexible eough to accommodate ew requests ad chages, you will probably lose customers ad the applicatio will fail. A LOB applicatio is the best fit for WPF/Silverlight ad the MVVM patter because it focuses o all the commo problems that a small, medium, or large team will ecouter durig the various phases of the developmet process, ad that you ca solve by usig these flexible techologies. Ufortuately, a book ca t teach you everythig, so i this book, you will ot lear how to build a idustrial-stregth CRM applicatio, or how to apply Scrum i your team but you will lear how to build a LOB applicatio that implemets a small CRM usig the latest Microsoft techologies. Choosig the Right Techology Because you ca build a LOB applicatio with either WPF or Silverlight, you ll eed to aalyze the project s requiremets to determie which techology is most appropriate for that particular applicatio ad which tools you might wat to use to build it. To aswer these questios, you ll first explore how to choose betwee Silverlight ad WPF, ad the explore the tools that Microsoft curretly offers for UI desig ad mockup. Fially, you ll move o to aalyze the commo graphical layout of a LOB applicatio, ad what users expect from it.

25 4 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios Silverlight or WPF? Silverlight ad WPF are both based o the same core techology: the Microsoft.NET Framework. I both, you build UIs usig the XAML laguage. WPF is the successor to Widows Forms, so it s desiged to icorporate a complete set of UI cotrols ad media elemets with which you ca produce rich ad iteractive Widows cliet applicatios. Silverlight is a cross-browser, cross-platform techology that supports rich iteret applicatios. There is some crossover; for example, browsers ca host WPF applicatios, ad Silverlight ca ru out-of-the-browser o desktops, but overall, WPF is iteded for Widows cliet applicatios, ad Silverlight is iteded for rich web applicatios. The compatibility betwee Silverlight ad WPF exists because both use the same UI descriptio laguage (XAML), the same stack of UI compoets (although Silverlight uses oly a subset of this stack), the same.net base class library, ad the CLR. The oly major differece here is that Silverlight curretly uses a differet implemetatio of the.net CLR. Figure 1-1 displays the mai differeces betwee these two techologies. WPF Presetatio Core SILVERLIGHT Presetatio Core NET Framework Commo Laguage Rutime NET Framework for Silverlight CLR for Silverlight Browser Host Figure 1 1 WPF ad Silverlight architectural overview. Because Silverlight focuses o the multi-platform, cross-browser web audiece, Microsoft was costraied to keepig its rutime smaller ad lighter. The takeaway here is that it s best to pla the fial target of your LOB applicatio from the begiig, because you wo t fid all the features of WPF available i Silverlight, ad it s far more difficult to migrate from oe target to the other later. Of course, both WPF ad Silverlight are improvig with every release, so the hope is that we ll get a uified framework i the future, but for ow, it s importat to remember that the targets of these two techologies are slightly differet.

26 Choosig the Right Techology 5 Note Witellect, i collaboratio with Microsoft, has released a whitepaper at wpfslguidace.codeplex.com that fully explais the differeces betwee these two techologies. The whitepaper is approximately 69 pages log. As you might expect, this book ca t cover all of the differeces; therefore, it oly highlights the most sigificat amog them. The first gap is with techologies crucial to the implemetatio of MVVM. Silverlight does t implemet routed commads, triggers, or the data template i the same way as WPF. Therefore, to get the same (or similar) behavior, you eed to implemet some custom fuctioality i Silverlight. But first, a word of cautio regardig the use of triggers i WPF ad Silverlight whe you implemet the MVVM patter: they should ot be heavily used because they ca easily icorporate presetatio logic that ca t be tested. The logic is ot available i the ViewModel but it is exposed i the View with the trigger. Silverlight 4 ships with a rich set of cotrols, styles, ad templates, oe of which is a ice LOB ASP.NET Model View Cotoller (MVC) website template. I cotrast, WPF ships with a smaller ad lighter cotrol toolbox. So, which should you use Silverlight or WPF? The aswer is: make your choice based o the type of applicatio you re buildig ad the most commo target of your applicatio. For example, if you re goig to develop a LOB applicatio for a fiacial departmet that will ot be used outside the customer s compay, WPF is the right techology for you. O the other had, if you eed to develop a CRM applicatio that will be used by customers ad maagers who might have differet devices, the it makes sese to host the applicatio i a browser; thus, Silverlight is the right techology. You ca easily build two UI layers if you use the MVVM patter correctly: oe layer for WPF, ad oe layer for Silverlight. Right ow, may developers follow this two-ui layer approach. The fial target ad purposes of your applicatio are the keys that should determie your choice of which techology to use. Do t worry about differeces i the cotrol set or the UI at this poit; Microsoft has released a set of desiger tools (Microsoft Expressio Studio) that ca hadle all the desig process eeds for both WPF ad Silverlight. Microsoft s UI-Buildig Tools The biggest problem for developers who wat to move to WPF or Silverlight is the learig curve. These two techologies use a ew UI laguage specificatio called XAML, which is othig more tha a declarative markup laguage like HTML or XML. Of course, it s ot easy to use this laguage to build graphical layouts whe you do t kow how the XAML rederig egie works. Similarly, it s ot easy to implemet full desiger support for a WYSIWYG approach. XAML is a very flexible markup laguage with few limitatios. For example, you ca place a DataGrid ito a Butto eve though that might make o sese i terms of usability. Such flexibility ca drive graphical egies crazy.

27 6 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios To help solve such problems, Microsoft has released a package of graphical tools called Expressio Studio. The latest versio is Expressio Studio 4, which must be bought separately (you ca also buy each idividual tool available i the Expressio package separately). This full Office applicatio set for WPF/Silverlight desigers covers the etire desig process of a XAML applicatio, from iitial UI mockup to all the desig elemets icluded i the fial product. Some of the tools i Expressio Studio, such as Expressio Web, are specifically for web desigers. Expressio Bled, aimed at user iterface desigers, separates ot oly the procedural code from the markup, but also separates desig tasks from developmet tasks, lettig developers focus o writig busiess code while leavig desigers free to desig fuctioal UI without havig to kow C#, or Visual Basic, or ay other.net Laguage. MVVM is key to this desig/developmet collaboratio process. I fact, Expressio Bled ships with a specific amespace that developers ca use to create a mockup ViewModel for the desigers. Desigers ca the bid the View to this mirror of the fial ViewModel ad cotiue developig the UI layer. You ca dowload Expressio Studio from i a 60-day trial versio, purchase it olie, or get it through a MSDN subscriptio. Expressio Bled For a WPF/Silverlight desiger, Expressio Bled is the primary Expressio Suite product. Its project files are completely compatible with Microsoft Visual Studio. You (or a desiger) ca work o a project i Expressio Bled, ad the later ope the project i Visual Studio, ad vice versa. This bi-directioal compatibility makes it easy to use Expressio Bled to desig the template ad the cotrols of your LOB applicatio, ad the move to Visual Studio to write your.net code. Despite this coveiece, movig back ad forth betwee Expressio Bled ad Visual Studio is ot madatory, because Expressio Bled ca reder XAML ad build C# ad Visual Basic solutios just like Visual Studio. Usig Expressio Bled, you ca desig a XAML user iterface, create a cotrol library for Silverlight, or WPF, or simply desig ad apply custom styles to your XAML applicatio. Oe truly powerful Expressio Bled feature is its ability to create a desig-time data template. This capability meas that a graphic desiger does t eed a real database or data files to represet a realistic result i the desiger; Expressio Bled lets you easily set up a data template, or you ca ask Expressio Bled to geerate oe. The fial result appears i the Itegrated Developmet Eviromet (IDE) ad looks just like the results you would get usig real data. Expressio Bled 4, the latest versio, has full desig-time support for WPF ad Silverlight, ad makes the desiger s job much easier. I additio, Expressio Bled also has a specific Behaviors SDK that adds desig-time support for the MVVM patter. This feature makes Expressio Bled the UI desiger s tool of choice for applicatios ivolvig MVVM.

28 Choosig the Right Techology 7 Fially, just to metio a couple more ew features i the latest versio of Expressio Bled, you ca easily build ad emulate applicatios for the ew mobile Widows Phoe 7 platform; create cool trasitios ad aimatios for your Silverlight or WPF applicatios; or create, aimate, ad deploy dyamic user iterface mockups. Figure 1-2 shows a populated data template i Expressio Bled. FigURe 1-2 Microsoft Expressio Bled data template. Figure 1-2 uses a simple data template to display the state of the ViewModel ad its data template at desig time. The code to do that is pretty simple. It uses data bidig to map the values betwee the UI ad the ViewModel, as show i the followig: <Grid x:name="layoutroot" d:datacotext="d:desigdata/sampledata/ CotactsViewModelSampleData.xaml"> <!-- omitted code --> <data:datagridtextcolum Bidig="Bidig Name" Header="NAME" Width="0.25*"/> <data:datagridtextcolum Bidig="Bidig " Header=" " Width="0.35*"/> <!-- omitted code --> <i:ivokecommadactio Commad="Bidig AddCotactCommad"/> </Grid>

29 8 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios Microsoft Sketchflow Microsoft SketchFlow is a UI mockup feature that ships with Expressio Bled. SketchFlow lets you quickly desig a mockup of the user iterface ad add some miimal iteractio betwee the sketches. Oe critical step i deliverig a ew applicatio is to get feedback from the customer as soo as possible eve before the UI developmet process starts. Usig Sketchflow, you ca provide a quick mockup of your applicatio, ad eve give it to ed users so they ca see ad provide feedback for modificatios. You ca publish SketchFlow mockups to a Silverlight or WPF player where users ca iteract with them, addig otes ad drawigs to capture feedback. By usig SketchFlow to support early user testig, you do t eed to desig a full user iterface before gettig feedback from the customer. Sketchflow is fully itegrated with Expressio Bled. It ships with a custom set of cotrols that are really othig more tha classic XAML cotrols with a custom theme. Figure 1-3 displays the mai Microsoft Sketchflow widow. Figure 1-3 The Microsoft Sketchflow start page.

30 Compositio of a LOB User Iterface 9 Usig Sketchflow i collaboratio with Expressio Bled, you ca bid mockup data to a dummy ViewModel so that whe you apply the MVVM patter i this process the UI desig ca evolve idepedetly from the busiess logic (for example, usig SketchFlow to tweak the UI desig). Later, you ca switch out the dummy ViewModel. Figure 1-4 displays the fial result of a mockup built usig Sketchflow. Figure 1-4 A fial mockup usig Sketchflow. Compositio of a LOB User Iterface I large developmet shops, by usig the Expressio Suite ad Visual Studio products, you ca easily divide your applicatio amog two differet teams without affectig productivity; oe team will use the Expressio tools to mockup ad develop the user iterface, while the other team will focus o implemetig core features ad activatig the UI. MVVM makes this clea separatio possible because it gives you the power to make the UI oly loosely coupled to the UI busiess logic cotaied i the ViewModel. Of course, this cocept does t mea that you must divide your team ito Desigers versus Developers if you pla to adopt the MVVM patter. Oe fudametal cocept that you eed to uderstad to build a successful LOB applicatio or ay other applicatio that ivolves user iterfaces is that users see oly UI. Ed users do t kow (ad do t care) that your applicatio uses the latest versio of SQL Server, or that

31 10 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios submittig a order ivolves iteractig with a NASA web service. The user iteracts oly with the user iterface. Therefore, it s importat to stay focused o a few cocepts that will reder the UI properly ad that will help prevet users from becomig lost i your applicatios. Before startig to defie each part of a LOB user iterface, it s worth lookig at a very successful Microsoft example that represets a classic LOB applicatio: Microsoft Dyamics, show i Figure Figure 1-5 A well-kow LOB applicatio, Microsoft Dyamics. Figure 1-5 cotais several highlighted items with umbered callouts, which are addressed i the paragraphs that follow. It s very commo for a LOB applicatio to use a avigatio pae (area 1 i Figure 1-5). You ca build a avigatio pae easily with a XAML tab cotrol ad some styles. You ll probably recogize this avigatio pae as the classic avigatio scheme used i programs such as Microsoft Outlook. The goal of a avigatio pae is to group, or gather, fuctioality ito oe place. As you ca see from Figure 1-5, Dyamics groups the various major sectios of the applicatio ito high-level cocepts such as Fiace, Ivetory, ad so o. This way, users ca easily access ay sectio of the LOB applicatio. Whe a user clicks oe of the high-level cocepts, the sectio for that cocept is loaded ito a more detailed View at the top of the avigatio pae (area 2).

32 Compositio of a LOB User Iterface 11 At the top of the applicatio you ll see both a Toolbar (area 3) ad a Meubar (area 4). The Meubar resides at the top of the applicatio ad should provide access to all the available commads. The toolbar is a graphical shortcut to the most-used commads. The Toolbar should be cotext-sesitive; for example, it should eable the Save butto oly whe the curret View has chages ad eeds to be saved. Note Meus should be cotext-sesitive as well, but because meu sub-items are ot visible as users work withi the UI, meu cotext sesitivity is less apparet tha that of toolbars. Note I may moder applicatios, such as Office 2010, the toolbar ad meu bar are beig replaced by a combiatio of the two, called a Ribbo. You ll see more about the Ribbo later i this chapter. The curret view (areas 5 ad 6) displays data that the user is curretly workig with i the applicatio. I this case Dyamics uses a Multiple Documet Iterface (MDI) approach, where each ope View has a separate widow. Aother possible approach is to use tabs for each View; this is the default style adopted by Visual Studio, for example. The followig sectio provides a more detailed explaatio of each major area, ad discusses some best practices for buildig useful LOB applicatio UIs. The Meubar The Meubar is the meu at the top of ay applicatio. It is the topmost cotaier, ad it should cotai all the available commads i the applicatio, divided ito related sectios. The Meubar should also iclude such commo sectios, such as File, Edit, ad Help. The Meubar is a critical LOB applicatio compoet, so your Meubars should adhere to some specific desig policies; otherwise, they will lose their potetial. Some commo Meubar rules are as follows: Wheever possible, iclude a uderlie (_) character i each item s text. I.NET, the uderlie defies that item s access key. Addig the uderlies lets users browse through the meus usig the Alt key i cojuctio with the access key. Respect commo shortcut key combiatios. For example, i Widows the Save commad is typically represeted by the shortcut Ctrl+S. Add a ico that represets each commad s cotext. The image should be clear ad uderstadable, ad the size of the image must be pixels. Figure 1-6 shows a example of a meu with ico images.

33 12 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios Figure 1-6 A sample Meubar that reflects the stadard guidelies. The Toolbar The Toolbar is a graphical cotrol that is typically positioed immediately below the Meubar. The commo characteristic of a Toolbar (as opposed to a Meubar), is that it provides users with visual cotrols rather tha simple labels. Usually the Toolbar cotais a set of buttos (ad sometimes other cotrols) each of which has a clear ad distiguishable image that suggests what that butto s fuctio is. The ormal size for a Toolbar ico is pixels or, at most, pixels. You might also cosider usig classic 16-pixel images, but i my opiio they are too small for a ormal Toolbar. You ca iclude text labels o your Toolbar buttos, but try to avoid this whe possible. Usually, users have oly the image to idicate the fuctio of a Toolbar butto, so the clearer ad more self-explaatory your images are, the more useful the Toolbar will be. Because the Toolbar supports the same (or fewer) commads that are already available i the Meubar, usig the MVVM approach, you might wish to use the same ViewModel for both cotrols or to provide a collectio of commads for each ViewModel ad build a DataTemplate to reder them. You ll see more about how to do that i the ext chapters. You could theoretically accomplish this with the Ribbo cotrol provided for WPF ad Silverlight, but the complexity of the UI ad the logic behid it will require a specific PM dedicated to the Ribbo cotrol. The Tooltip (ad Its Abuse) Despite the best desig itetios, sometimes circumstaces force you to positio too may cotrols i oe area, or to place images ad cotrols such that eve the most expert user ca easily become lost. Whe the user iterface is ot completely clear, you should provide users with dyamic feedback from the UI to help them make the best decisios.

34 Compositio of a LOB User Iterface 13 Oe way to provide such feedback is through the Tooltip cotrol. This is a little widow that appears whe users hover their mouse over a specific cotrol. The purpose of the Tooltip is to provide a immediate descriptio of the selected cotrol. That s it, othig more, ad othig less. So, for example, if a user hovers the mouse over a Toolbar butto with a image of a floppy disk, commo sese suggests that the Tooltip text for that image should read somethig like: Save. Save the curret record. This is a clear ad immediate descriptio, but it is ot too complex. While Tooltips ca be helpful, there is oe problem I ofte see whe workig with WPF/ Silverlight developers; because XAML has few limits, it s easy to add a Tooltip to a Datagrid or ay other cotrol. But overusig Tooltips defeats their purpose. The key is to remember that the goal of a Tooltip is simply to provide temporary ad trasiet help by meas of a brief descriptio of the curret cotrol. If you eed to exted the behavior of that cotrol, cosider adoptig a differet solutio. For example, WPF has a ice tag called Popup, where you ca store ay cotrol ad use it to show more iformatio usig the pop-up cocept. Because of its powerful reder template, Tooltips ca be easily misuderstood ad used improperly. Whe you pla to write a tooltip for a specific cotrol (textbox, butto, label, ad so forth), remember that the Tooltip will stay o the scree for just a few secods. Therefore, it should cotai oly a few words that describe its associated cotrol. If you determie that your Tooltip eeds more tha few words to describe the cotrol, it meas that there are two problems: The cotrol that eeds the Tooltip is placed i the wrog View or might ot be clear at all; cosider usig a label to idetify this cotrol to simplify (or elimiate) the Tooltip. The operatio doe by that cotrol is too complex to describe easily. I such cases, you might eed a more detailed help solutio, or you might cosider splittig the operatio ito differet cotrols, usig a Wizard or a validatio ico to idetify potetial errors caused by the operatio. As with the Toolbar ad the Meubar, a good approach to creatig uiform Tooltips is to create a specific DataTemplate stored i a commo dictioary. By usig this approach, every cotrol i your applicatio that uses a Tooltip ca use the same style. I wat to stress here that a Tooltip is just a UI artifact that a desiger ca choose to support or ot support; it does t defie ay UI logic, so it does t eed to be represeted i the ViewModel. Notificatios ad Alerts Commuicatio with users is paramout i UI costructio. Oe commo eed for commuicatio is whe you wat to otify users that etered or selected data is ivalid, or that they re attemptig to perform a ivalid operatio. At the same time, you wat to make your user iterface miimally ivasive ad reduce frustratio as much as possible. As a example,

35 14 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios if every time a user clicks the Save butto your UI asks for cofirmatio such as the all-toofamiliar prompt Are you sure you wat to save? after oly a few hours usig the applicatio, the user will be really frustrated. But you also eed to be sure that users do t execute ivalid or iappropriate commads, or eter ivalid data. Typically, you do this by addig some validatio logic to the user iterface. Remember though, that i almost every case, it s far more useful to disable ivalid actios i advace. As a example (ad as you ll see later), whe usig the MVVM approach it s better to set the CaExecute cotext of a butto to false, rather tha lettig users click it, ad the showig them a frustratig MessageBox otificatio. WPF ad Silverlight offer various ways to commuicate with the user. Historically, developers have used modal dialog boxes, which pop up ad capture all applicatio iput util dismissed. It is called a dialog box because it establishes a dialog betwee the UI ad the user. Dialogs ca be uidirectioal (otifyig users about a error, for example), or bidirectioal (users are asked to cofirm or cacel a operatio). The dialog approach is easy to implemet but very ivasive for users. Displayig a dialog forces users to click a butto such as Yes or No. Because dialogs capture all applicatio iput, util the user respods, the etire UI simply freezes. Dialogs are appropriate whe you eed a cofirmatio, such as whe a user tries to delete a record, but i most other cases you should use a differet approach. The MVVM patter makes it more difficult to implemet the dialog approach because the ViewModel does t kow aythig about the View, so it does t kow how to iteract with it. A easy solutio to this problem is the mediator patter. You ll aalyze this patter i more depth i Chapter 6, The UI Layer with MVVM. Note The Mediator is a behavioral desig patter that provides a cetral hub to guide iteractios betwee may objects. Whe you aalyze the composite UI framework built by the Microsoft patters & practices team i Chapter 7, MVVM Frameworks ad Toolkits, you will see that there are also better ways to accomplish this task. Aother iterestig approach that fits well ito the MVVM patter is usig validators ad the IDataErrorIfo iterface applied to the ViewModel. For example, whe you require a specific data format i a cotrol, you ca use a validatio otificatio, which i WPF ad Silverlight is both easy ad clea. If a user has etered icorrect data ito a cotrol, you ca easily highlight that cotrol ad display a error message. Ulike dialogs, such messages do ot require cofirmatio ad do ot freeze the UI. Whe validatio errors occur, users ca cotiue to work with the UI, but they wo t be able to submit the data util it s fixed. Figure 1-7 shows a example of a Silverlight LOB applicatio that validates data before sedig it to the server.

36 Compositio of a LOB User Iterface 15 Figure 1-7 Custom data validatio usig Silverlight 4. The key poit here is that you eed to choose appropriate methods for hadlig errors ad cofirmatios for which you wat to force users to respod, as opposed to those that provide advice or other iformatio, for which you do t eed to force users to respod. For the latter, you ca cosider a less ivasive approach. The Ribbo Bar Sice the Microsoft Office 2007 products were itroduced a few years ago, Widows users have begu to get comfortable with a ew custom cotrol kow as the Ribbo. The Ribbo is a set of tools that icludes the fuctioality of both a Meubar ad a Toolbar, wrapped ito a more moder approach. The Ribbo got its ame as the result of a meetig of the Outlook 2003 team, at which they decided to implemet this ew cotrol for the first time. The idea was to implemet somethig similar to a medieval scroll, where a log strip of paper ca be scrolled usig oe of the two spidles. Usig this cocept, the team itroduced the cocept of Tabs ad Groups i the existig Ribbo cotrol. The purpose of the Ribbo is to reduce the umber of meus floatig aroud your applicatio. I fact if you pla to itroduce a Ribbo bar i your applicatio, you will o loger eed a Toolbar or Meubar, because the Ribbo subsumes those fuctios. Ribbos have some very restrictive desig costraits, so if you pla to use oe, you should follow the desig policies suggested by Microsoft, which are available here: library/cc aspx. Note Durig the writig of this book, Microsoft released the fial versio of the Ribbo cotrol for WPF 4, compiled i.net 3.5 SP1, with full support for the MVVM patter. The Ribbo cotrol has bee released i beta for WPF 3.5 (ad works with WPF 4) but it s ot available for Silverlight. You might wat to cosider a third-party solutio if you pla to use a Ribbo i a Silverlight applicatio.

37 16 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios The WPF Ribbo bar was desiged to work with MVVM; it has ative support for routed commads ad data bidig, ad it s also easy to customize. The Ribbo cotrol s structure, which uses regios ad groups, is probably the best match so far for a MVVM-rich meu cotrol. Figure 1-8 shows the mai structure of a Ribbo bar usig the Office 2007 style. Applicatio butto Quick access toolbar Tab Cotextual tab Cotextual tab set Help Group Ehaced tooltip I-Ribbo gallery Dialog box laucher Figure 1-8 The Microsoft WPF Ribbo bar (from MSDN). Before decidig if a Ribbo is a good fit for your applicatio, be aware that the effort you eed to costruct a usable Ribbo is greater tha that eeded to create a simple Meubar or a Toolbar. Therefore, here are some thigs you should cosider: Is your applicatio complex? If you are buildig a simple UI, cosider usig a simple meu system rather tha a Ribbo bar. Do your users have problems fidig ad executig the right commads? The Ribbo, if properly desiged, might help ameliorate such usability problems. Do you have space costraits? Rederig a Ribbo requires sigificat scree space, so if you are plaig to develop a applicatio with small widows that does t use a Tabbed/MDI cocept, the Ribbo is probably ot for you. Geeral Style ad Cotrol Cosideratios Lookig backward through this chapter, you ve see that LOB applicatio UIs have some commo characteristics based o specific UI cotrols ad specific techiques that reder the cotrols ad the views properly. Usig commo styles throughout your applicatio is critical i LOB applicatios especially whe you work with a flexible techology such as WPF/Silverlight.

38 Separatio of Cocers 17 Cosider the cocept of a fot, which icludes the fot family, fot face, fot size, colors, ad more. I most LOB applicatios, you should strive to miimize fot use i fact, it s best to use oly oe fot face. Withi that sigle fot face, you ca adjust the weight, size, ad decoratios, so oe fot is flexible ad ca meet may eeds. You should avoid mixig may differet fots i the same applicatio. Secod, ad very importat for most customers, is the color scheme. For this aspect of your applicatio you eed to cosider two thigs. First, are you developig a applicatio for a specific customer? If so, you should try to apply the compay s colors to your applicatio or at least you should try to keep the same colors ad styles as their previous applicatio, if there was oe. Such cotiuity helps users avoid becomig lost withi the ew iterface. Secod, are you developig the applicatio as a software suite? Emulatig existig suite applicatios ca be a good idea. For example, the Office package uses a successful combiatio of colors. Emulatig Office styles i XAML is possible, ad it makes your applicatio look professioal, while also makig it familiar ad easy to uderstad, because most customers have already worked with Office. That familiarity ca trasfer to your ew UI. Fially, remember that oe aspect of beig effective i XAML is based o DataTemplates ad styles. Do t waste your time creatig dictioaries ad styles for each view by doig massive copy ad paste operatios. Remember that you ca use a dictioary from a differet assembly ad load styles o the fly. Workig i this way, you ca easily build a applicatio with custom themes ad deploy a specific theme for a specific customer without the eed to chage the etire applicatio code. Also remember to be careful ot to duplicate style ad layout i multiple places; if you cetralize these aspects usig data templates ad styles, you ca guaratee more cosistecy i your applicatio UI. Note Microsoft has released a series of ice templates that customize the commo cotrols for WPF. The Silverlight team has also released a ice set of templates for the Silverlight Busiess applicatio. You ca get the WPF ad Silverlight Cotrol themes from com. If you pla to use the Silverlight 4 LOB applicatio template, you ca get some themes from Separatio of Cocers I iformatics, the term Separatio of Cocers (SoC) refers to the process of separatig pieces of code so that they overlap i fuctioality as little as possible. The mai cocept here is that you wat to make a applicatio composed of layers. SoC is a key software egieerig priciple that states that a give problem ivolves differet kids of cocers, which should be idetified ad separated to cope with complexity ad to achieve required egieerig quality factors such as robustess, adaptability, maitaiability, ad reusability.

39 18 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios You ca apply the priciple i various ways. The most commo way of separatig cocers is to divide the layers by fuctioality. Typically, a LOB applicatio will have a UI layer, the layer that composes the graphic iterface; a Domai Layer, the layer that represets busiess etities (such as a Customer, a Order, ad so o); a Busiess Layer, which is i charge of ecapsulatig all the busiess logic of the applicatio; ad a Data Access Layer, the layer i charge of persistig ad retrievig data. All programmig paradigms aid developers i the process of improvig SoC. For example, object-orieted programmig laguages such as Delphi, C++, Java, ad C# separate cocers ito objects; a desig patter such as MVC ca separate cotet from presetatio, ad data-processig (model) from cotet. Service-orieted desig ca separate cocers ito services. Procedural programmig laguages such as C ad Pascal ca separate cocers ito procedures. Aspect-orieted programmig laguages ca separate cocers ito aspects ad objects. SoC is a importat desig priciple i may other areas, as well, such as urba plaig, architecture, ad iformatio desig. The goal is to desig systems so that fuctios ca be optimized idepedetly of other fuctios, such that failure of oe fuctio does ot cause other fuctios to fail, ad i geeral to make it easier to uderstad, desig, ad maage complex iterdepedet systems. Commo examples iclude usig corridors to coect rooms rather tha havig rooms ope directly ito each other, ad keepig the stove o oe circuit, ad the lights o aother. A Little Taste of History I 1974, Edsger W. Dijkstra, a Dutch computer scietist, wrote a paper called O the role of scietific thought, which was the first paper that discussed the cocept of SoC. I his paper, Mr. Dijkstra metioed that: the separatio of cocers, [is] the oly available techique for effective orderig of oe s thoughts, that I kow of. I 1989, Chris Reade wrote the book Elemets of Fuctioal Programmig, i which he also metios SoC: The programmer has to do several thigs at the same time, amely, 1. Describe what is to be computed; 2. Orgaize the computatio sequecig ito small steps; 3. Orgaize memory maagemet durig the computatio. Movig forward, i the years (I am ot goig to bother you with dates ), Marti Fowler ad Eric Evas started to talk about desig patters related to cotextual desig, leadig directly to the moder cocept of SoC.

40 Separatio of Cocers 19 Both authors, but especially Marti Fowler, bega amig patters, discussig cocepts ad patters such as Domai-Drive Desig, Iversio of Cotrol, Uit of Work, ad may other agile approaches to make applicatios that are layered, testable, ad maitaiable. Shortly thereafter, large compaies ad programmig commuities started to implemet frameworks or applicatio blocks that facilitated SoC i applicatios ad worked with commo programmig laguages such as.net, Java, ad C. You ll see all these patters ad techiques i this book ad apply them to a real-world problem. Layers, Tiers, ad Services Usig UI patters such as MVVM forces you to divide applicatio code ito differet layers. That s good, because it helps keep the applicatio testable ad flexible. Commoly, such blocks are called layers. Sometimes a set of layers have a specific iteractio (see the MVVM patter), ad they compose a tier, such as the cliet tier i a MVVM applicatio. Figure 1-9 displays a coceptual sketch of the differece betwee layers ad tiers. Database Database Applicatio Server LAYERS Data Layer TIERS Data Layer Busiess Layer User Iterface User Iterface Cliet Cliet Figure 1-9 The differece betwee a layered applicatio ad a tiered applicatio.

41 20 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios I a commo three-tier applicatio such as a MVVM applicatio (UI, busiess logic, ad database), you usually have two/three layers per tier ad two tiers. The tiers are the cliet applicatio ad the remote database (physically separated), ad the layers for the cliet tier might be the UI ad the Presetatio, while for the Busiess tier, they might be the Busiess Layer ad the Data Access Layer. Whe the applicatio starts to be more complex or its distributio starts to icrease, you should cosider usig the service-orieted applicatio (SOA) approach. For example, i Silverlight you ca t recycle the biaries of the Domai Layer or the data layer because they are ot usually compiled for the Silverlight CLR. The solutio i this case is to use SOA through WCF RIA Services. These services are proxies built ito WCF, with which you ca share the code exposed i a class library such as the domai layer, compiled for the ormal NET CLR, with the Silverlight CLR. Of course, if you pla to move to SOA, you should keep i mid other problems that you might ecouter, such as cocurrecy, trasactios, service availability, ad more. History of the Service Layer The term Service Layer was coied by Marti Fowler, oe of the most famous software architects, who said: A Service Layer defies a applicatio s boudary [Alistair Cockbur s applicatio boudary patter also kow as Cockbur PloP] ad its set of available operatios from the perspective of iterfacig cliet layers. It ecapsulates the applicatio s busiess logic, cotrollig trasactios ad coordiatig resposes i the implemetatio of its operatios. If you pla to move to a Service Layer ad to SOA architecture, you eed to keep a lot of other architectural cosideratios i mid. For example, whe usig the Etity Framework ad RIA Services, the effort required to move to a SOA solutio is ot large, but SOA forces you to thik through some additioal cosideratios. SOA is complex. Microsoft techologies such as WCF ad the RIA services for Silverlight ca help, but ufortuately whe you actually start to use SOA, you ll eed to cosider additioal possible problems such as cocurrecy, trasactios, ad availability. You ll eed to tackle each of these carefully. Note The Data Trasfer Object will be covered i the Chapter 3, The Domai Model. The Busiess Layer cotais the busiess logic of your applicatio. For ow it s eough to kow that the busiess logic must reside there; you ll see later how complex this layer ca

42 Separatio of Cocers 21 become. I fact, it s usually composed of two layers: oe o the cliet side, ad oe o the server side. I the example LOB applicatio for this book, the Busiess Layer will cotai etity classes such as Customers ad Orders, ad busiess logic such as workflows ad validatio. Fially the Data Access Layer is i charge of commuicatig with the repository the data store, ot the repository patter, which you ll read more about i Chapter 2, Desig Patters. Of course, the data store ca be a commo database, a service, a simple text file or aythig else able to store data. Usually you do t have this layer if you use a object relatioal mapper (O/RM) because that becomes your Data Layer. Of course, you might eed to exted or expad the O/RM; if so, you will keep such extesios i the Data Layer. If everythig were desiged this eatly, it would t be so complex to be a software architect. You ll start by aalyzig each layer i more detail to see the complexities of a well doe layered applicatio. First, you have the UI, which ca implemet oe of the followig UI Patters: MVC, MVP (Model View Preseter), or MVVM. I ve purposely skipped the lesser-kow patters; it s eough to focus o just these three. Because the Presetatio Layer will cotai the Views (widows, widgets, ad so o), the orchestratio (preseter, cotroller, or ViewModel), ad the resources, you ll probably ed up with three sublayers similar to the structure i Figure Presetatio Layer RESOURCES.DLL PRESENTER.DLL VIEWS.DLL FigURe 1-10 Oe possible breakdow of the Presetatio Layer. You ca imagie these three layers i Visual Studio as three differet class library projects. Usig this approach, you ca assig each layer to a differet developer, but this depeds o the size of the project ad o the size of the layers. Also, if you eed to update just oe of them, because they are loosely coupled you wo t eed to upgrade the etire UI layer oly the oe affected by the chages. As you saw i the sectio about Expressio Bled, you ca ow provide desigers with a fake XAML ViewModel, allowig them to build the UI while

43 22 Chapter 1 Itroductio to Model View ViewModel ad Lie of Busiess Applicatios lettig developers move forward o the ViewModel assembly. If istead, the Views ad the ViewModels were stored i the same assembly (the same Visual Studio Project), accomplishig this task would be difficult. The Busiess Layer is a more complex cocept. If you follow the Domai-Drive Desig approach used i this book, you should represet the busiess i the form of classes. For example, you would have a Customer class that has a collectio of classes such as Address, ad so o. The ed result is a class structure called a Graph or Model. At this poit, you might be thikig, Where ca I write the C# code that will allow me to add a order for a specific user? This is a commo ad pretty simple busiess rule, typical of a Busiess Layer. Usually, you d iclude all such rules i a separated layer that we will call the Service Layer (or better, Busiess Service Layer) that should ot be cofused with the SOA approach. Usig this techique lets you take advatage of a third-party framework, such as Widows Workflow, to execute busiess rules agaist the domai. Of course, you ca dispatch such rules usig the SOA approach, but at this poit the architectural cosideratios become more complex. Fially, the Data Layer, which typically is ot the repository itself, but the compoet i charge of exchagig the data betwee the domai ad the repository. For example, if you wat to create a collectio of Customer classes usig the Customer table i the database as a source, you would use the Data Layer to do that. Of course, this task ca be the most expesive i terms of resources, because you eed to map each etity agaist the correspodig data i the database. You will also eed to provide the mappigs for commads, such as Save, Update, ad so o. You will also eed to maitai a blueprit of the mappig process; otherwise, whe chages occur i the database, your Data Layer wo t reflect this chage. Doig all this is far easier if you use a O/RM. I this book, you ll see what a O/RM is ad how you ca use it to map a domai etity agaist a database.

44 Summary Summary 23 The MVVM patter was itroduced by Microsoft a couple of years ago to satisfy the demad for a Separated Presetatio patter specifically iteded for use with WPF ad Silverlight. The MVVM patter is the best presetatio patter available for WPF ad Silverlight because it s able to take advatage of specific built-i features of Silverlight ad WPF, such as data bidig, commads, behaviors, ad so o. LOB applicatios, ofte called eterprise applicatios, are those that have bee idetified as critical to the busiess. If you pla to write a robust ad maitaiable LOB applicatio usig WPF or Silverlight, it s madatory that you implemet the MVVM patter, ad it s also madatory that you follow some UI guidelies specific to LOB applicatios. The term Separatio of Cocers refers to the process of separatig code so that overlaps i fuctioality with other code occur as little as possible. The mai cocept here is that you wat to make a applicatio composed of modules, also kow as layers. Usig this approach, you ca create testable ad flexible applicatios that differet teams ca develop i parallel.

45

46 Chapter 2 Desig Patters After completig this chapter, you will be able to: Apply the appropriate desig patter for a specific problem. Distiguish betwee the three major presetatio patters. Apply Iversio of Cotrol ad DSL. A Overview of Desig Patters Writig a computer applicatio is a complex task writig oe that is flexible ad that ca be efficietly maitaied is eve more complex. If you are a seior developer or a software architect, you might already kow that arguably the most difficult task is figurig out how to write the code oly oce, recyclig it as much as you ca to save time ad make your applicatios easier to maitai. As the Pirelli Compay famously said about its tires, Power is othig without cotrol, ad i this case, cotrol is very importat. Whe writig code, you first eed to cosider the likelihood that you will ot be the oly perso workig o that project or applicatio. Secod, the applicatio might require maiteace ad modificatio i the future. Ad fially agai it s preferable to write code oly oce. If you are a seior developer or a software architect, you have probably already experieced may problems durig your career. I fact, you might have a commo solutio for a commo problem that you recycle i every applicatio whe you ecouter that specific problem. This type of solutio usig similar code to solve similar problems is called a patter, or typically, a desig patter. A desig patter is a commo solutio for a commo problem that has already bee idetified ad tested. From the outset, let me say that this defiitio does t mea that every desig patter is the same; istead, the patter is a tested approach to solvig a commo problem. I other words, it s a guidelie that must be adjusted depedig o the cotext, ot used i a sigle, o-chagig sytax. This book uses a umber of desig patters, some of which you might be familiar with, others might be completely ew. For example, the Model View ViewModel (MVVM) is a user iterface (UI) desig patter. Of course, desig patters are used for more tha just buildig UIs; there are desig patters for the domai, for the UI, ad for typical commo problems. You wo t explore each desig patter i depth i this book, because that s ot the mai purpose; however, it s worth lookig at some of the commo available desig patters to see how they might apply to the sample Lie of Busiess (LOB) applicatio. 25

47 26 Chapter 2 Desig Patters A Little Taste of History Desig patters were origially itroduced by Christopher Alexader i 1977 as a commo solutio for a commo problem i the field of costructio architecture. Later, at the ed of the 1980s, Ket Beck ad Ward Cuigham bega to apply patters i the field of the computer sciece. The first importat book o desig patters for developers was Desig Patters: Elemets of Reusable Object-Orieted Software (Addiso-Wesley, 1995; ISBN: ). This well-kow work was writte by four software architects the Gag of Four (GOF) Erich Gamma, Richard Helm, Ralph Johso, ad Joh Vlissides. I highly recommed it as a fudametal book for ay developer. I 2002, Marti Fowler wrote a more advaced versio of this book, Patters of Eterprise Applicatio Architecture (Addiso-Wesley Professioal, 2002; ISBN: Commoly kow as PoEAA, this book discussed architectural problems ot origially covered by the GOF. I my opiio, this is aother milestoe of computer sciece literature, ad agai, I heartily recommed it. Note To aalyze the topic of desig patters i more depth, go to e-us/practices/default.aspx. This page was created by Microsoft s patters & practices team, which aalyzes the architectural aspects of Microsoft techologies. Classifyig Desig Patters The basic desig patters implemeted i 1977 are divided ito three major categories: creatioal, structural, ad behavioral, each of which has a specific role. I additio, you ca fid patters specific to UI, ad advaced patters for architectural problems. These patters are members of a ew classificatio, also kow as the architectural desig patters classificatio. The creatioal patters are specific to solvig problems related to object creatio. The structural patters deal with the compositio of classes or objects, ad the behavioral patters are cocered with desigig the way objects commuicate or iteract. These are also collectively kow as Gag of Four patters, because they were itroduced i the aforemetioed GOF book. Creatioal Patters The followig table presets patters that were desiged to solve problems related to the creatioal process of objects ad classes.

48 Name Descriptio Example Abstract Factory Factory Method Builder Prototype Sigleto Provides a method for creatig objects or classes that are related or depedet, without specifyig the cocrete class. Defies a iterface for creatig a object, but lets subclasses decide which class to istatiate. Separates the costructio of a complex object from its represetatio so that the same costructio process ca create differet represetatios. Specifies the kid of objects to create usig a prototypical istace, ad creates ew objects by copyig this prototype. Esures a class has oly oe istace ad provides a global poit of access to it. A Overview of Desig Patters 27 Factory.CreateProductA(); Factory.CreateProductB(); FactoryA.Create(); FactoryB.Create(); Builder.BuildPartA(); Builder.BuildPartB(); Build.GetFialProduct(); Product = Prototype.Cloe(); Sigleto.DoSomethig(); Structural Patters The ext table itroduces patters that were desiged to solve problems related to the compositio of a object or class. Name Descriptio Example Adapter Coverts the iterface of a class ito aother Target obj = ew Adapter(); iterface that cliets expect. obj.dosomethig(); Bridge Composite Decorator Facade Flyweight Proxy Decouples a abstractio from its implemetatio so that the two ca vary idepedetly. Composes objects ito tree structures to represet part-whole hierarchies. Attaches additioal resposibilities to a object dyamically. Provides a uified iterface to a set of iterfaces i a subsystem. Uses sharig to support large umbers of fiegraied objects efficietly. Provides a surrogate or placeholder for aother object to cotrol access to it. Var obj = ew CocreteA(); obj.dosomethig(); obj = ew CocreteB(); obj.dosomethig(); Composite.Add(objA); Composite.Add(objB); obj.setdecorator(deca); obj.dodecoratio(); obj.setdecorator(decb); obj.dodecoratio(); Façade.MethodFromObjA(); Façade.MethodFromObjB(); A = FWFactory.GetFW( A ); B = FWFactory.GetFW( B ); var proxy = ew Proxy(); proxy.requestchael();

49 28 Chapter 2 Desig Patters Behavioral Patters The table that follows describes patters that were desiged to solve problems related to the behavior ad iteractio betwee objects or classes. Name Descriptio Example Chai of Respose Avoids couplig the seder of a request to its receiver by givig more tha oe object a chace to hadle the request. Employee.SetSupervisor(Maager); Maager.SetSupervisor(Director); Employee.Execute(); Commad Iterpreter Mediator Memeto Observer State Strategy Template Method Visitor Ecapsulates a request as a object ad supports udoable operatios. Give a laguage, defies a represetatio for its grammar. Defies a object that ecapsulates how a set of objects iteract. Without violatig ecapsulatio, captures ad exteralizes a object s iteral state so that the object ca be restored to this state later. Defies a oe-to-may depedecy betwee objects so that whe oe object chages state, all its depedets are otified ad updated automatically. Allows a object to alter its behavior whe its iteral state chages. The object will appear to chage its class. Defies a family of algorithms, ecapsulates each oe, ad makes them iterchageable. Usig Strategy, the algorithm ca vary idepedetly from cliets that use it. Defies the skeleto of a algorithm i a operatio, deferrig some steps to subclasses. Represets a operatio to be performed o the elemets of a object structure. Commad.DoSomethig(); Commad.Redo(); Commad.Udo(); Vocabulary.Add(expressioA); Vocabulary.Add(expressioB); Vocabulary.Traslate(); Mediator.Add(ObjA); Mediator.Add(ObjB); ObjA.Sed( ObjB, Message ); ObjA.Name = ObjA ; Memeto.Save(ObjA); Memeto.Restore(ObjA); Observer.Attach(ObjA); Observer.Attach(ObjB); Observer.ChageSomethig(); Observer.Notify(); Cotext.Add(ObjA); ObjA.ChageState( A); ObjA.ChageState( B ); List.Add(ObjA); List.Add(ObjB); List.SortStrategy(Ascedig); List.SortStrategy(Descedig); Template A = ew Studet(); Template B = ew Teacher(); A.Write(); B.Write(); List.Add(Studet( A ); List.Add(Studet( B ); List.Visit(ew VoteVisitor()); You do t eed to memorize or fully uderstad all these patters yet; istead, make a metal ote of this list as a referece for the future. You ll see more about some of these patters ad how you ca implemet them cocretely i the sample LOB applicatio (CRM software)

50 UI Desig Patters 29 that you will create durig the course of this book. You ll also see why you should choose a specific patter for a specific problem. Of course, you wo t use them all here, because some are solutios to problems that you will ot ecouter i a ormal MVVM applicatio. Still, it s worth havig the list, ad I suggest that you study ad experimet with these patters, because the oly way to master all of these differet approaches is to uderstad them i the cotext of experiece. As developers start to lear the GOF patters, they typically try to apply the same patter to every solutio but that approach is icorrect. For example, if you were buildig a Widows Service, it would probably be over-egieered if you were to apply the MVVM patter to it. UI Desig Patters A full brach of desig patters is dedicated to buildig UIs. The best-kow UI desig patters are the Model View Cotroller (MVC), the Model View Preseter (MVP), ad the Presetatio Model (PM) patters that you ecoutered i the book s itroductio as forebears of the MVVM. Other UI patters exist as well. These are subpatters of the MVC ad MVP patters, but they are rarely implemeted ay more with the.net Framework. The UI is probably the most volatile part of a applicatio, because it s subject to frequet chages over time. Iexperieced developers ted to bid the UI ad the Model together, puttig busiess logic related to the Model ito UI code, which leads to umaitaiable applicatios. Aother commo problem is that iexperieced developers ted to mix i the UI part of the presetatio logic with some busiess logic ad some UI logic. By doig this, the testable surface of your applicatio becomes smaller ad smaller, ad it becomes difficult to test ad maitai the applicatio Separatio of Cocers (SoC). Before startig to talk about the available desig patters ad ito which types of techology they best fit, let me clarify whe you should use a desig patter for the UI, ad whe you should ot. The mai purpose of these patters is to separate the busiess logic from the UI, to make the UI more testable ad maitaiable, ad to preclude the eed to write busiess logic i the UI, which is somethig that you should always avoid. May developers misuderstad this fudametal cocept ad try to make the UI totally agostic they try to separate the Model from the UI completely. But that approach is wrog because the UI, usually defied as a View, has some depedecies o the Model; the View is desiged to display the iformatio provided by a specific Model or by a set of Models. This iformatio is the maipulated by a itermediary object, which is the ViewModel i the MVVM patter. Creatig a geeric View is a pretty cool accomplishmet, but it s ot the purpose of a UI desig patter. However, the iverse of this is ot true: it s importat to keep the Model agostic ad uaware of the View because you might wat to recycle the Model to use it with additioal Views or i other applicatios. For ow, remember that buildig a agostic

51 30 Chapter 2 Desig Patters View is ot a requiremet of a UI patter. I ll also metio here that the Model will cotai busiess logic related to the busiess operatio that it ca execute. I ay case, this busiess logic should ever iclude ay presetatio or UI logic, because as discussed earlier, the Model is View-idepedet. You should also keep i mid that the UI patters you ll aalyze i the ext sectios are suggestios ad guidelies to make the UI testable ad maitaiable but they are ot costraits. Especially with a flexible patter like MVVM, you might eed to desig some hybrid solutios to satisfy specific problems that do ot fit i the basic structure of the patter. A Little Taste of History The father of all the UI desig patters is the MVC patter, first described i 1979 by Trygve Reeskaug, a software developer workig for Smalltalk at Xerox. I the origial MVC patter, the View was i charge of maagig the graphical cotrols displayed o the scree, the Cotroller was i charge of iterpretig the keyboard ad mouse iputs, ad the Model was the object i charge of maagig the data ad the behaviors of the applicatio domai. Over the years, MVC has split ito two braches: passive MVC, where the Cotroller is i charge of cotrollig the View ad the Model, ad active MVC, where the View actively iteracts with the Model ad listes to its chages. I the early 1990s, developers at Taliget Corporatio bega to adopt a alterative iterpretatio of the MVC, the MVP patter, which removed the Cotroller ad itroduced the Preseter. This approach is sigificatly differet because the Preseter is aware of the Views, ad each View kows its Preseter. This patter has bee widely adopted i both web ad cliet applicatios. I 2004, Marti Fowler itroduced his set of eterprise desig patters, which icluded the father of the MVVM patter, the PM patter. Ufortuately, due to its strict requiremets, the PM patter was ever as successful as the MVC or the MVP patters, largely because it was desiged for a techology like Widows Presetatio Foudatio (WPF), which was t yet released. I 2005, Microsoft applied the PM patter to WPF, itroducig a PM-derived patter specifically tailored for WPF, the MVVM patter, which fully exploits the bidig egie power of WPF ad Silverlight. The MVC Patter The MVC patter comprises three objects, each oe i charge of a specific fuctio i the UI cotext. You ca apply the MVC patter i a web applicatio (which is a stateless applicatio

52 UI Desig Patters 31 by desig) where the Cotroller is i charge of processig user iputs ad coordiatig server-side calls util the View is redered (as with ASP.NET MVC); however, you ca also apply this patter to a stateful Cliet UI techology such as Widows Forms or WPF. I MVC: The Model represets the data i the applicatio i a logical way; it is i charge of carryig the data ad makig other objects aware of data chages. The View is the graphical represetatio of the Model; it is resposible for displayig the Model data i suitable form. The Cotroller is the orchestrator of this patter; it is i charge of iterceptig user iput (mouse ad keyboard) ad iteractig with the Model ad/or the View. Figure 2-1 shows the structure of a basic MVC desig. This desig is also called the Passive MVC patter, ad it s the default implemetatio. Cotroller Model View Figure 2-1 A Passive MVC patter. The most importat poit of this implemetatio is that the Model is aware of either the View or the Cotroller. The Model remais agostic, so you ca develop ad test it i a separate cotext. However, the View ad the Cotroller are both aware of the Model: the View because it s i charge of displayig the Model s data, ad the Cotroller because it s the bridge betwee user iput ad the Model s chages. Fially, the View ad the Cotroller are aware of each other; i the default passive implemetatio the Cotroller kows its Views, but Views are uaware of their Cotroller.

53 32 Chapter 2 Desig Patters Listig 2-1 is a theoretical implemetatio of a MVC patter i C#. This example uses the framework ASP.NET MVC. Listig 2-1 MVC patter usig ASP.NET MVC V2 ad C# /// Simple Model that represets a Employee etity public class Employee /// The First Name public strig FirstName get; set; /// The Last Name public strig LastName get; set; /// The Compay ame public strig Compay get; set; ///<summary> /// The Cotroller i charge of displayig the Views ///</summary> public class HomeCotroller : Cotroller /// A actio that reders the Idex View public ActioResult DisplayEmployee() var model = ew Employee FirstName = "Joh", LastName = "Smith", Compay = "Microsoft" ; retur View(model); <h2>displayemployee</h2> <fieldset> <leged>fields</leged> <div class="display-label">firstname</div> <div class="display-field"><%: Model.FirstName %></div> <div class="display-label">lastname</div> <div class="display-field"><%: Model.LastName %></div> <div class="display-label">compay</div> <div class="display-field"><%: Model.Compay %></div> </fieldset>

54 UI Desig Patters 33 The implemetatio of the MVC patter i Listig 2-1 uses a simple Model: a employee that represets a busiess object. The Cotroller is i charge of creatig the Model based o a ew employee request made by a user. Whe the user makes a ew employee request, the Cotroller creates a ew istace of a specific View ad ijects the Model ito that View. Fially, the View reders the Model by usig some HTML tags ad the MVC Framework bidig sytax. Of course, i a real applicatio you would have a service or a Data Layer that retrieves the Model from the database ad seds it to the Cotroller. Figure 2-2 shows the process flow of this implemetatio. Cotroller Model View Request Employee Service Update Get Figure 2-2 A MVC request flow. Figure 2-3 shows the fial result as it might appear i a browser. Figure 2-3 The fial result of a MVC applicatio usig ASP.NET MVC.

55 34 Chapter 2 Desig Patters Pros ad Cos of the MVC Patter The MVC patter fits web applicatios best. Its stregths are its capacity to display the same Model i differet Views ad the ability to chage the way the View reders without affectig the Model (which is uaware of the Views). Aother stregth is its testability. Because the View is also uaware of the Model, the Cotroller ca simply use a mockup Model for testig purposes. That makes MVC a good fit for a Test-Drive Developmet (TDD) approach. That said, the MVC patter ca be also used i cliet applicatios that are ot stateless (such as web applicatios). I fact, there are popular MVC frameworks specifically for cliet techologies such as Widows Form or Java. O the other had, MVC is a complex patter, ad it is evet-drive; the Cotroller reacts to chages made by users, about which it otifies the Model ad the View. I additio, updatig MVC ca ca cosume a cosiderable amout of resources, because the View must be alerted ad updated through the Cotroller for every update. Some of the moder frameworks such as ASP.NET MVC do ot apply the MVC patter i its origial form aother reaso why this patter a good fit for both cliet ad web applicatios. I additio, the origial MVC patter, as it was coceived, would ot be a good fit for ew UI techologies such as WPF ad Silverlight. With that said. I would also like to specify that there are may moder UI desig patters today that are wrogly idetified with the ame MVC patter, but these are ot the origial MVC patter; they re substitutes for the origial patter. The MVP Patter The MVP patter is categorized either as a evolutio of the MVC patter or a differet iterpretatio of it. The mai differece is that i the MVP patter, the View ad the Preseter are coected usig a differet approach. I MVC, the View is totally idepedet; i MVP the View is passive ad delegates ay actio to the correspodig Preseter. Aother importat differece is that i MVP, the Preseter iteracts with the View usig a bidig egie or a custom implemetatio of a bidig egie if the UI techology does t provide oe. The View ad Model are ot coected i MVP, while i MVC, the View is totally or partially aware of its correspodig Model. Like the MVC, the MVP has three compoets, but with some differeces: The Model is the same as i MVC. It represets ay busiess etity with associated data ad busiess logic.

56 UI Desig Patters 35 The View is the graphical iterface i charge of rederig the data. It directly refereces the Preseter so that it ca delegate to it the iterpretatio of all user iteractios. The Preseter drives the UI logic; it kows both the View (through a iterface) ad the Model. It updates the View based o chage otificatios from the Model ad updates the Model based o chage otificatios from the View. This is the object that ecapsulates the presetatio logic, ad it usually sets property values ad calls methods o the View rather tha usig a bidig egie. The MVP patter has bee implemeted i both cliet ad web applicatios. You might read that the MVP patter fits best with web applicatios, but i my persoal experiece, because its desig is so depedet upo the Preseter, it s a better fit for a cliet applicatio, although it is flexible eough to be used for a web applicatio. Figure 2-4 shows the passive implemetatio of the MVP patter. Preseter Model View Figure 2-4 A MVP passive implemetatio. Listig 2-2 shows a simple Widows Form example that illustrates how to implemet the MVP passive view patter i a simple cliet applicatio.

57 36 Chapter 2 Desig Patters Listig 2-2 MVP implemetatio usig Widows Form ad C# /// The Employee View cotract public iterface IEmployeeView /// The Firstame strig FirstName get; set; /// The Lastame strig LastName get; set; /// The Compay ame strig Compay get; set; /// The Employee preseter i charge of /// drivig the UI logic public sealed class EmployeePreseter /// The curret view private IEmployeeView view; /// Iitializes a ew istace of the <see cref="employeepreseter"/> class. /// <param ame="view">the view.</param> public EmployeePreseter(IEmployeeView view) this.view = view; /// Iitializes this istace. public void Iitialize() var model = ew Employee FirstName = "Joh", LastName = "Smith", Compay = "Microsoft" ;

58 UI Desig Patters 37 //Bid the Model to the View UpdateViewFromModel(model); /// Updates the view from model. /// <param ame="model">the model.</param> private void UpdateViewFromModel(Employee model) this.view.firstname = model.firstname; this.view.lastname = model.lastname; this.view.compay = model.compay; /// Cocrete View. public partial class EmployeeView : Form, IEmployeeView /// The correspodig preseter private EmployeePreseter preseter; /// Iitializes a ew istace of the <see cref="employeeview"/> class. public EmployeeView() IitializeCompoet(); this.preseter = ew EmployeePreseter(this); this.preseter.iitialize(); /// The Firstame /// <value></value> public strig FirstName get retur txtfirstame.text; set txtfirstame.text = value; /// omitted This example still uses the model Employee you saw i Listig 2-1. As you might have oticed, the most sigificat differece from the MVC patter is that the MVP View is totally uaware of the Model it is rederig because the data is boud ito the View cotrols by the

59 38 Chapter 2 Desig Patters Preseter. Whereas the View is totally depedet o the Preseter, it must have a referece to it, because the View does t kow how to react to user iput. Figure 2-5 shows the fial result. Figure 2-5 The MVP Passive View fial result. Pros ad Cos of the MVP Patter What distiguishes the MVP patter from other UI patters are its roles ad resposibilities. I the MVP patter, the Preseter drives all logic; the View ca oly make otificatios about user iteractios to the Preseter, which ca the call methods ad chage data o the View ad/or o the Model. Aother problem lies i the roud trip that occurs each time a user iteracts with the View; the View must call a Preseter method, ad the the Preseter must update the View. MVP is t appropriate for WPF or Silverlight because its passive implemetatio does t use the power of XAML s bidig egie, ad it s ot able to clealy separate the XAML code that costructs the UI from the procedural C# eeded i the View for it to kow its correspodig Preseter. I would discourage you from usig the MVP patter i WPF ad Silverlight applicatios. If you are plaig o usig it, you might fid that you do t eed either of these techologies, ad that classic Widows Forms techology might be better. The big dowside of MVP is that all presetatio logic ad every bidig process must go through the Preseter, so if you pla to adopt a Supervisig Preseter patter (more o this i the ext sectio) i WPF or i Silverlight, you will wid up with a View that has the Model as its DataCotext, plus a separate referece to the Preseter. Alterative Approaches to MVP Aother approach is the MVP Supervisig Preseter. I this variat, the View is ot passive; it kows the Model it is rederig, ad requires a data bidig egie to react to chages i the Model. The Preseter s role dimiishes such that it s i charge oly of iterceptig user iput that is t to be hadled by the Preseter. You might thik that this approach would be iterestig if applied to WPF or Silverlight ad it probably is whe you eed to work with a View/Model combiatio i which the iteractio betwee them is very complex. O

60 UI Desig Patters 39 the other had, the View has multiple refereces to maitai, which is difficult to test ad requires more iterfaces to maitai loose couplig. Fially, it s also complex because you must write code i the UI to maage the iteractio with the Preseter. Figure 2-6 shows the MVP Supervisig Cotroller structure. Preseter Model View Figure 2-6 The MVP Supervisig Cotroller. The PM Patter ad MVVM This sectio covers both the PM ad the MVVM patters because they are closely related to each other. The PM patter appeared whe techologies such as WPF ad Silverlight were ot yet available. Whe they did appear, Microsoft applied the PM patter to WPF ad Silverlight usig the MVVM patter. The guidig priciples of the PM are to maitai a loosely-coupled relatioship betwee the PM ad the View by makig the View a observer of the PM, ad usig data bidig to accomplish that. The PM kows the Model, but it does t specifically eed to kow the correspodig View. The View kows its PM oly ad exclusively through the bidig egie. The power ad flexibility of WPF/Silverlight data bidig make this a suitable patter for use i WPF/Silverlight applicatios. The MVVM patter is a evolutio of the PM patter that has the three usual pricipal compoets: a Model that represets the busiess etity (like the Employee class example), a View that is the XAML UI, ad the PM or View Model, which cotais all the UI logic ad the referece to the Model, so it acts as the Model for the View.

61 40 Chapter 2 Desig Patters Figure 2-7 cotais a diagram that shows how to implemet the MVVM patter. Of course, this is a geeric implemetatio. Durig the course of this book, you ll see that you eed to implemet the MVVM patter i differet ways depedig o the type of View you are usig, which ca icrease the complexity compared to that show i Figure 2-7. View (XAML) Template Behaviors View Model (Presetatio Model) Commads Model Figure 2-7 The basic structure of a MVVM applicatio. If you are plaig to work with WPF or Silverlight, you must take advatage of the powerful bidig egie provided by these techologies. By doig this, your ViewModel should implemet some specific iterfaces required by the bidig egie of WPF ad Silverlight. Oe of these is the INotifyPropertyChaged iterface, itroduced with.net Framework versio 2.0. This iterface implemets a otificatio system that activates whe the value of a property chages. It s required i the ViewModel to make the bidig egie of XAML work properly. Aother customizatio of the PM is the Commad exposed by the iterface ICommad, which is available for WPF ad Silverlight. This specific Commad ca be boud to ay XAML cotrol ad determies whether the cotrol ca or caot execute a specific actio. I WPF, this Commad has a more powerful implemetatio through the Routed Commad, which is a Commad routed through the Visual Tree of a WPF UI. A third customizable compoet is the DataTemplate, a XAML structure that defies how to reder a specific ViewModel, or a specific state of the ViewModel. DataTemplate compoets are really views that are redered at rutime by the WPF/Silverlight egie. They are particular type of Views that caot cotai ay code behid because they are dyamically created. Logically you are displayig a ViewModel or Model directly i the UI, but the view is cojured up at rutime ad attached to the ViewModel or Model (through the data cotext). Listig 2-3 shows a simplified example of implemetig the MVVM patter i WPF. I the ext chapters, you ll see how you ca customize every ViewModel compoet.

62 UI Desig Patters 41 LISTINg 2-3 MVVM implemetatio usig WPF 4 /// ViewModel for the Employee view public sealed class EmployeeViewModel : INotifyPropertyChaged public EmployeeViewModel() var employee = ew Employee FirstName = "Joh", LastName = "Smith", Compay = "Microsoft" ; //Bid the model to the viewmodel this.firstame = employee.firstname; this.lastame = employee.lastname; this.compay = employee.compay; #regio INotifyPropertyChaged /// Occurs whe a property value chages. public evet PropertyChagedEvetHadler PropertyChaged; /// Called whe [property chaged]. /// <param ame="ame">the ame.</param> public void OPropertyChaged(strig ame) var hadler = PropertyChaged; if (hadler!= ull) PropertyChaged(this, ew PropertyChagedEvetArgs(ame)); #edregio /// Private accessor for the Firstame private strig firstame; /// Gets or sets the firstame. /// <value>the firstame.</value>

63 42 Chapter 2 Desig Patters public strig Firstame get retur firstame; set if (firstame!= value) firstame = value; OPropertyChaged("Firstame"); // omitted <Widow.DataCotext> <vm:employeeviewmodel /> </Widow.DataCotext> <StackPael Orietatio="Vertical"> <TextBlock>FirstName :</TextBlock> <TextBox Text="Bidig Path=Firstame, Mode=TwoWay, UpdateSourceTrigger=PropertyChaged" /> <TextBlock>Lastame :</TextBlock> <TextBox Text="Bidig Path=Lastame, Mode=TwoWay, UpdateSourceTrigger=PropertyChaged" /> <TextBlock>Compay :</TextBlock> <TextBox Text="Bidig Path=Compay, Mode=TwoWay, UpdateSourceTrigger=PropertyChaged" /> </StackPael> Agai, this example uses the Employee cocept from Listig 2-1. I it, you ca see a simple ViewModel, which is othig more tha a class that implemets the INotifyPropertyChaged iterface ad exposes the Model properties that you wat to reder i the UI. The View is a XAML widow that uses the ViewModel istace as the data source, ad that bids each property of the ViewModel to a specific cotrol. Because Microsoft Visual Studio 2010 has full support for the WPF ad Silverlight bidig egie, ad because you are bidig the Employee i the ViewModel costructor, you do t eve eed to ru the applicatio to view the fial result the View is fuctioal eve i desig mode i the Visual Studio IDE, as illustrated i Figure 2-8.

64 Advaced Desig Patters ad Techiques 43 Figure 2-8 A fuctioal MVVM applicatio i the Visual Studio 2010 desiger. MVVM Pros ad Cos First, i the pro colum, the MVVM patter is desiged for use with WPF or Silverlight, but it s ot completely restricted to those techologies; you ca implemet MVVM i Widows Forms or with aother UI techology as well. However, the power ad flexibility of WPF or Silverlight (icludig features such as data bidig, XAML, data templates, behaviors, ad so o), make MVVM much easier to implemet o WPF/Silverlight. The ViewModel is the core of a MVVM applicatio, so you must cosider all the appropriate precautios, or you might easily ed up with a ustable ad messy applicatio. Follow the guidelies carefully, ad experimet with differet solutios. Do t try to fit your ViewModel ito a strage architecture simply because you do t kow how to write a specific behavior or DataTemplate i WPF or Silverlight. The patter is desiged for these techologies, so you should master them before masterig the MVVM patter itself. Fially, oe key advatage of adoptig the MVVM patter is that the View is a observer of the ViewModel, which makes it easier to build the UI separately, ad it lets you replace the View later or eve at rutime, without the eed to touch the presetatio logic at all. Advaced Desig Patters ad Techiques The desig patters available i the GOF patters were created ad adopted to solve some commo problems related to object-orieted programmig, such as how to create a object or how to ope a dialog betwee two differet objects. The UI patters were desiged ad adopted to separate the busiess logic from the user iterface, ad to make the UI testable ad flexible. As architecture advaced, these basic techiques were uable to satisfy larger architectural requiremets. The solutio gave rise to commo solutios ow called eterprise patters or patters for eterprise applicatios.

65 44 Chapter 2 Desig Patters This book does ot cover all the available eterprise patters ad techiques, but it will provide a overview of the commo eterprise patters ad show i detail those that are fudametal to adoptig MVVM. More Iformatio Read Patter of Eterprise Applicatio Architecture by Marti Fowler, ad Domai Drive Desig by Eric Evas, the fouders of the Eterprise Architecture patters. These two books are madatory readig, i my opiio, for ay seior developer or software architect, especially those who pla to build complex LOB MVVM applicatios. Marti Fowler has exhaustively covered all of these patters ad divided them ito i 10 differet categories, each specific to a particular cotext. The first category is the domai logic patter, which you ll aalyze i the ext chapter. There are three categories related to the Data Layer, which you ll cover i depth i Chapter 4, The Data Access Layer. There are two patters for cocurrecy ad sessio state that are ot used i this book. I the ext sectio, you ll cover two particular patters/approaches that are madatory for a MVVM patter or, i geeral, for ay LOB applicatio: the Depedecy Ijectio patter, also kow as Iversio of Cotrol, ad the Domai Specific Laguage (DSL) patter. You ll also get a itroductio to the TDD approach, a agile techique for testig a applicatio durig its developmet phase. The Iversio of Cotrol Patter The term Iversio of Cotrol (IoC) is a computer programmig techique wherei the flow of the cotrol of a applicatio is iverted. Rather tha a caller decidig how to use a object, i this techique the object called decides whe ad how to aswer the caller, so the caller is ot i charge of cotrollig the mai flow of the applicatio. This approach makes your code flexible eough to be decoupled. It ca be uaware of what is goig o i the call stack because the called object does t eed to make ay assumptios about what the caller is doig. The Depedecy Ijectio patter is simply a cocrete implemetatio of the IoC. Ufortuately, as Marti Fowler specifies i his book, there is a lot of cofusio about these terms, because the commo IoC cotaiers available for laguages such as Java or.net are typically idetified as IoC cotaiers, but the techiques implemeted i your code whe you use these frameworks is the Depedecy Ijectio patter, which is just oe of the available cocrete implemetatios for IoC. For example, if you pla to work with a modularized WPF/Silverlight applicatio usig a well-kow framework such as Prism, you might implemet IoC usig the Service Locator patter ad ot Depedecy Ijectio because you eed a global IoC cotaier available for all the modules.

66 Advaced Desig Patters ad Techiques 45 Imagie that you have a simple LogWriter cocept that is used to write a log message either to a specific database table or to a specified file. You might depict this as show i Figure 2-9. Figure 2-9 Basic structure of a multi-targeted log system. The UML diagram i Figure 2-9 is pretty clear; there s a abstract BaseLogger class that exposes a WriteLog message, ad two cocrete classes that iherit from BaseLogger. These expose the method i two ways: oe writes a log message to a database, the other to the file system. The followig code shows the wrog way to use oe of these cocrete loggers without applyig a IoC implemetatio: static void Mai(strig[] args) /* Wrog way * * */ var firstlogger = ew FileLogger(); firstlogger.writelog("some Text."); var secodlogger = ew DatabaseLogger(); secodlogger.writelog("some other Text."); Cosole.ReadKey(); The biggest problem with this approach ot applyig a IoC implemetatio is that if you wat to specify a differet log at rutime, you ll eed to rewrite some code. That s a huge architectural costrait. For example, suppose that you wat to get rid of the FileLogger object. That s ot easy. You ca t simply elimiate it, because the applicatio would t execute ay more, or at least, you would eed to modify ad recompile it for it to cotiue workig. To solve the problem, the first step is to decouple the existig hierarchy by usig a iterface istead of the base abstract class, as illustrated i Figure This way, you simply defie a cotract betwee a cocrete log ad its iterface. Subsequetly, to write a log message to a differet locatio, you just eed to reder the iterface i a specific way.

67 46 Chapter 2 Desig Patters Figure 2-10 Refactorig the LogWriter usig a commo iterface. The code that follows is a refactored versio that uses a IoC approach to declare the type of logger to be used at rutime. This approach is still procedural, because it decides which logger to use, but at least it decouples the code, so this is a somewhat more flexible versio of the custom writer. /// Custom writer that ca uses ay log public sealed class Writer /// Accessor to the ijected logger private ILogger logger; /// Iitializes a ew istace of the <see cref="writer"/> class. /// <param ame="logger">the logger.</param> public Writer(ILogger logger) this.logger = logger; /// Writes the specified message. /// <param ame="message">the message.</param> public void Write(strig message) this.logger.writelog(message); At this poit, you eed somethig betwee the applicatio ad the logger that ca resolve which logger to use at rutime. The followig example uses procedural code to do that without usig the Depedecy Ijectio or the Service Locator patters:

68 Advaced Desig Patters ad Techiques 47 static void Mai(strig[] args) // IoC without a IoC cotaier var firstlogger = ew FileLogger(); //Ijecti of a specific logger var writer = ew Writer(firstLogger); writer.write("log for the File system."); Cosole.ReadKey(); A alterative solutio would be to implemet the Depedecy Ijectio or the Service Locator. Figure 2-11 shows the mai differece betwee these two differet approaches. ILOGGER Referece WRITER Uses 3 Ijects 2 FILELOGGER Creates 1 BUILDER Depedecy Ijectio FILELOGGER WRITER 3 ILOGGER DBLOGGER 1 Uses 2 Locates LOCATOR Service Locator Figure 2-11 The differeces betwee the Depedecy Ijectio ad the Service Locator patters. I the ext sectio, you ll see how to implemet these two techiques usig Microsoft Uity or Microsoft Maaged Extesibility Framework.

69 48 Chapter 2 Desig Patters Microsoft Uity Microsoft Uity is a applicatio framework that is delivered as part of the Microsoft Eterprise library, but you ca also dowload it as a stadaloe compoet from CodePlex at As of this writig, the latest versio is 2.0, available for WPF ad Silverlight. You ca also use Microsoft Uity i ay other type of.net applicatio. Uity is a extesible Depedecy Ijectio cotaier through which you ca apply Depedecy Ijectio i your code usig either a declarative approach (XML) or a procedural approach (C# or Visual Basic.NET). With Uity, you ca iject code ito costructors, properties, ad methods. Uity has a extesible core egie called cotaier that implemets the iterface IUityCotaier (you ca iherit from this if you eed to exted the existig implemetatio). It has three pricipal methods which it uses to register a istace, retrieve a specific istace, ad defie the lifetime of a object. Figure 2-12 shows the basic structure of Uity. Figure 2-12 The basic structure of a Uity applicatio block. Depedecy Ijectio with Uity I this first example, you ll see how to defie a policy for a specific logger ad use it i your applicatios. I this case, the logger is declared i the cotaier, ad the the example assigs Uity the resposibility of creatig the logger. To implemet this, chage the code i the Writer costructor to specify that Uity will be i charge of creatig this object at rutime usig the [IjectioCostructor] attribute.

70 Advaced Desig Patters ad Techiques 49 /// Iitializes a ew istace of the <see cref="writer"/> class. /// <param ame="logger">the logger.</param> [IjectioCostructor] public Writer(ILogger logger) this.logger = logger; Now you ca chage the code to register the type of logger that you wat to use alog with the type of writer, ad leave the resposibility of creatig the objects to Uity. //Prepare the cotaier var cotaier = ew UityCotaier(); //We specify that the logger to be used is the FileLogger cotaier.registertype<ilogger, FileLogger>(); //ad how to istatiate a ew Writer cotaier.registertype<writer>(); //Here Uity kows how to create the ew costructor var writer = cotaier.resolve<writer>(); writer.write("some Text."); Beyod that, you ca use Uity to implemet all aspects of the Depedecy Ijectio patter. For example, you ca write some policies that defie how log a istace of a specific object should stay alive, or you ca itercept object creatio ad chage the code ijected at rutime usig specific behaviors. Service Locator with Uity Aother possible implemetatio of the IoC patter is to use the Service Locator. Note You might read o the Iteret that the Service Locator is a ati-patter, because its decouplig is too high, ad that you should ot use it because it ca prevet you from kowig if your code executes correctly outside the rutime cotext, thus makig your code less testable. Or you might read that you totally lose cotrol of the ijectio because the resultig code is more decoupled tha whe usig Depedecy Ijectio. I disagree, as the ext example shows. To see how you ca write a Service Locator usig Uity, there is othig better tha some sample code. To use the Service Locator with Uity you eed a adapter, which you ca fid o the CodePlex website at This adapter was built to apply the Service Locator patter with ay of the available IoC cotaiers for.net, icludig Uity, Castle, Sprig, StructureMap, ad so o.

71 50 Chapter 2 Desig Patters First, you create a simple adapter (provider) so you ca use the Microsoft Service Locator i cojuctio with Uity, as show i the followig: /// Utility to cofigure the cotaier public sealed class UityCotaierCofigurator /// Cofigures this istace. /// <returs></returs> public static IUityCotaier Cofigure() var cotaier = ew UityCotaier().RegisterType<ILogger, FileLogger>().RegisterType<Writer>(); retur cotaier; The you implemet the writer usig the Service Locator istead of Uity (of course, you kow that this is ot totally true, because you re usig the Uity cotaier behid the scees); what the developer will see here is a Service Locator implemetatio: // create a ew istace of Microsoft Uity cotaier var provider = ew UityServiceLocator(UityCotaierCofigurator.Cofigure()); // assig the cotaier to the Service Locator provider ServiceLocator.SetLocatorProvider(() => provider); // resolve objects usig the service locator var writer = ServiceLocator.Curret.GetIstace<Writer>(); writer.write("some Text."); I this case, the created provider istatiates ad registers a ew Uity cotaier. It the assigs the provider to the ServiceLocator istace, ad fially, resolves the objects by usig the Service Locator. As you probably oticed, the primary differece is that with the Depedecy Ijectio patter, you cotrol the creatio ad the flow of the code. I cotrast, whe usig the Service Locator, you o loger cotrol how or what to create; you simply call the commo Service Locator ad get a istace of the available compoet. Typically, you d use the Service Locator i decoupled applicatios for which the developer does t have access to commo compoets that are t refereced i the curret assembly. The Service Locator covers that gap.

72 The Maaged Extesibility Framework Advaced Desig Patters ad Techiques 51 Maaged Extesibility Framework (MEF) is a applicatio block itroduced i.net 3.5 as a beta experimet from Microsoft Labs ad the implemeted as part of the.net 4 Framework. It is available for both WPF (commo CLR) ad Silverlight. MEF is ot really a IoC cotaier, or more accurately, it is ot oly a IoC cotaier, it s a framework to maage extesios ad plug-is. Choosig to use MEF does t mea that you ca t use Uity for the basic IoC operatios; the two are parallel ad differet applicatio blocks. I additio, Uity is more powerful for Depedecy Ijectio, because that s its mai target, while the mai target of MEF is applicatio compositio. Like Uity, MEF has a catalog ad a cotaier that are i charge of discoverig ad rederig a istace of a registered object at rutime. But more tha that, with MEF you ca declare some specific compoets o a separate assembly ad register them i the MEF catalog. You ca the access the catalog from the cliet applicatio at rutime ad use these compoets. The mai differece is that MEF is ot a Depedecy Ijectio cotaier; it s a extesible framework to resolve additioal compoets at rutime. Its mai priority is to make large applicatios extesible. Figure 2-13 shows the basic structure of MEF. Catalog Custom Provider Catalog Provider Mutable Provider Cotaier Part Part Part Export Import Export Import Export Import FigURe 2-13 The compositio of the MEF Framework (source: MSDN library).

73 52 Chapter 2 Desig Patters To use MEF, you eed to write a custom logger that satisfies the MEF desig requiremets. I this case, you wat to specify how MEF should export ad use the logger. /// Logger customized for MEF [Export(typeof(ILogger))] public class MefLogger : ILogger /// Writes the log. /// <param ame="message">the message.</param> public void WriteLog(strig message) Cosole.WriteLie("Strig built from MEF: 0.", message); At this poit, you ca use the program ad declare a MEF property. Next, you eed to istatiate the MEF catalog; here, the code declares that the catalog is the executig assembly. The you ca easily use the compoets. /// Gets or sets the writer. /// <value>the writer.</value> [Import] public ILogger Writer get; set; public void Ru() // first we build the catalog var catalog = ew AssemblyCatalog(Assembly.GetExecutigAssemb //create the cotaier usig the catalog var cotaier = ew CompositioCotaier(catalog); cotaier.composeparts(this); //use the resolved property Writer.WriteLog("Mef message"); The approach here is sigificatly differet tha usig a IoC cotaier. With MEF, you prepare a catalog of compoets ad the access them directly. Notice that this example does ot i ay way cotrol how to create a ew istace of a logger, it simply starts the MEF egie. Differeces Betwee MEF ad Uity To wrap up this discussio, I wat to focus your attetio o what a IoC cotaier is, what a extesibility framework like MEF is, ad why you should use oe istead of the other.

74 The mai reasos to use Uity (or ay other IoC cotaier) are if: Advaced Desig Patters ad Techiques 53 You have depedecies betwee your objects. You eed to maage the lifetime of a object. You wat to maage depedecies at rutime, such as cache, costructors, ad properties. You eed to itercept the creatio of a object. The mai reasos to use MEF are if: You eed to implemet exteral ad reusable extesios i your cliet applicatio, but you might have differet implemetatios i differet hosts. You eed to auto-discover the available extesios at rutime. You eed a more powerful ad extesible framework tha a ormal Depedecy Ijectio framework, ad you wat to get rid of the various boot-strapper ad iitializer objects. You eed to implemet extesibility ad/or modularity i your compoets. If your applicatio does t require ay of the items i these lists, you probably should ot implemet the IoC patter, ad you might ot eed to use Uity ad MEF. DSLs: Writig Fluet Code The Fluet Iterface approach we are goig to view ow is ot specifically related to the MVVM patter, ad it does t eed to be implemeted i order to obtai good results with the MVVM patter. O the other had, as this approach is used i this book whe I talk about MVVM ad how to write some custom factories used to build the ViewModels, I believe it is worthwhile to sped some time takig a look at it, if oly to see what it is ad how it works. The domai-specific laguage (DSL) approach istigates aother iterestig discussio about eterprise patters. DSL is a techique to make code fluet ad readable for a specific cotext. For example, whe you write a query for Microsoft SQL Server, you work with a DSL laguage kow as T-SQL; it s a domai-specific laguage because it does t work outside the specific cotext of writig queries for SQL Server. The mai purpose of this techique is to make the code more readable iside the cotext where it s supposed to be used, helpig to reduce mistakes ad misuderstadig. You might eed to implemet a custom DSL laguage i your applicatio to avoid mistakes or improper implemetatios by other colleagues. For example, you might have a small MVVM framework that eeds to be implemeted i a specific order, ad you would like

75 54 Chapter 2 Desig Patters to avoid chages i the call stack order. Whe a DSL is built for a iteral use, it takes the ame fluet iterface, which is a term that was first coied by Marti Fowler ad Eric Evas whe they were writig about Eterprise patters. The followig code shows how you might write a fluet iterface by usig C#: Var mvvmview = FluetEgie.BuildCommads().BuildData().IitView().Create(); You could write the same thig usig a ormal approach i this way: Var mvvmview = ew MvvmView(); mvvmview.buildcommads(); mvvmview.builddata(); mvvmview.iitview(); You might agree with me that you ca read the first implemetatio with greater ease. A secod importat poit though, is that the first implemetatio provides a costrait. Usig the fluet approach, a developer caot iitialize the View before callig the iitializatio of the Commads ad the Data. This approach ca be very easy to implemet, but it must be desiged carefully; otherwise, the DSL might ed up usig a custom dictioary that s ot always readable ad uderstadable for other developers, such as the code that follows: Var mvvmview = FluetEgie.BuildPart01().BuildPart02().DoThis().DoThat(); Of course, this is a extreme view of what a DSL implemetatio should look like, but it s better to get the team members to agree to the termiology so that you do t ed up writig a DSL laguage that oly you ca uderstad. Writig a Fluet Iterface i C# Microsoft s LINQ sytax is a good example of a fluet iterface. The essece of LINQ is the IQueryable collectio, whose methods always retur aother IQueryable collectio. That makes it easy to chai the methods, so you ca easily write code such as the followig: Var employees = employees.where(x => x.firstname == "Joh").Where(x => x.age > 35).OrderBy(x => x.lastname).first();

76 Advaced Desig Patters ad Techiques 55 This fluet code will be traslated by LINQ to SQL i somethig like the followig: SELECT TOP 1 FROM EMPLOYEE WHERE FIRSTNAME = 'JOHN' AND AGE > 35 ORDER BY LASTNAME Cosider for a momet how you create a object. Usually, you call the object costructor, ofte a parameterless costructor, ad the assig a value to each property, such as this: Var employee = ew Employee(); employee.firstame = "Joh"; employee.lastame = "Smith"; employee.age = 35; This is pretty simple, but what if you wat to kow, i advace of creatig the object, that the object will be valid, or esure that Employee.Age will ever be lower tha 30? Ufortuately, you ca t; istead, you eed to remember to ru some checks before usig the created object. However, if you were to refactor this code usig the Factory patter ad a fluet iterface, you could provide such costraits. To do that, you first eed a iterface to defie the cotracts available i the DSL object, such as the followig: public iterface IFluetEmployee /// The Firstame. /// <param ame="firstname">the first ame.</param> IFluetEmployee FirstName(strig firstname); /// The Lastame. /// <param ame="lastname">the last ame.</param> IFluetEmployee LastName(strig lastname); /// The compay ame. /// <param ame="compay">the compay.</param> IFluetEmployee Compay(strig compay); /// Creates this istace. /// <returs></returs> Employee Create();

77 56 Chapter 2 Desig Patters Now you ca implemet this iterface i a custom class ad massage the static methods, to make the code more fluet, as follows: /// The Fluet creator public class FluetEmployee : IFluetEmployee private static Employee employee; private static IFluetEmployee fluet; /// Iitializes a ew istace of the <see cref="fluetemployee"/> class. public FluetEmployee() fluet = ew FluetEmployee(); /// Iits this istace. public static IFluetEmployee Iit() employee = ew Employee(); retur fluet; /// The Firstame. /// <param ame="firstname">the first ame.</param> public IFluetEmployee FirstName(strig firstname) employee.firstname = firstname; retur fluet; /// The Lastame. /// <param ame="lastname">the last ame.</param> public IFluetEmployee LastName(strig lastname) employee.lastname = lastname; retur fluet; /// The compay ame. /// <param ame="compay">the compay.</param>

78 public IFluetEmployee Compay(strig compay) employee.compay = compay; retur fluet; Advaced Desig Patters ad Techiques 57 /// Creates this istace. /// <returs></returs> public Employee Create() retur employee; Now, you ca write a fluet iterpretatio of the Employee costructor i the followig way: var employee = FluetEmployee.Iit().FirstName("Joh").LastName("Smith").Compay("Microsoft").Create(); This is a simple task with far-reachig implicatios; it helps to esure that ay developer who uses the code wo t misuderstad the methods. For example, it s pretty clear that the FirstName() method will chage the value of the Employee istace s FirstName property. You ca ow move forward ad refactor this code agai to defie a specific order for this method or implemet lambda expressios to make your DSL laguage totally dyamic. You ll see a custom implemetatio of the DSL sytax i the Chapter 4 ad subsequet chapters. For example, i Chapter 3, The Domai Model, you ll see how to build a custom Factory ad a custom Validator usig the DSL techique ad lambda expressios. Itroductio to TDD TDD is a parallel programmig techique of developig software by writig tests for it eve before you write the code. This is a topic that you ll revisit throughout this book; this sectio provides a brief overview of what TDD is. With the MVVM patter, you ca use TDD, which works very well due to the decoupled ature of the MVVM patter; TDD is ot madatory to use the MVVM patter, but it is a very highly-suggested step. That dovetails icely with the mai cocept of TDD, which is to write the test for your code before writig the code itself. Ay iput you provide at this poit would cause the test to fail.

79 58 Chapter 2 Desig Patters Oly the do you implemet the code that would pass the test. Fially, you refactor the code ad ru the test to be sure that the refactor process has bee implemeted correctly. At first, the idea of writig a test before writig the required code might soud strage, but you ll fid that whe you apply this pair-programmig techique, you will write better code. I cotrast, if you develop the code first, ad the try to test it, it s far more difficult to guaratee that the code is implemeted properly. The motto of TDD is red, gree, refactor, which meas, write the specificatios, verify the code agaist those specificatios, ad the refactor. A TDD Example Here s a example that illustrates how you might write code usig TDD. For cosistecy, this example also sticks with the by ow well-kow Employee etity. Simply right-click the [TestMethod()] text, ad the select Add New Uit Test; the fial result should appears as i the followig example: ///A test for Compay ///</summary> [TestMethod()] public void CompayTest() Employee target = ew Employee(); strig expected = "Microsoft"; strig actual; target.compay = expected; actual = target.compay; Assert.AreEqual(expected, actual); The precedig code verifies that the property Compay i the class Employee is populated correctly. Of course, this is a simple (ad probably icoclusive) test but it should serve to give you a overview of how TDD works. Tools for Uit Testig There are several good tools for buildig uit tests. I the iterest of space, I ll limit the discussio to oly two commo oes. This book uses MSTest, which is the uit test tool that is delivered with Microsoft Visual Studio 2010 ad Team Foudatio Server (TFS). It is available through the Visual Studio IDE. Figure 2-14 shows the itegratio betwee Visual Studio ad MSTest.

80 Advaced Desig Patters ad Techiques 59 Figure 2-14 Available optios for Visual Studio ad MSTest. If you re plaig to use MSTest, you ll welcome its full itegratio ito Visual Studio ad TFS, which makes it easy to deliver your code with itegrated tests durig the build process. Aother agile programmig techique called Cotiuous Itegratio (CI) requires you to deliver a build of your code every day; to do that, the oly possible safe approach is to implemet TDD throughout your applicatio ad itegrate it i ito your build process. If you use Visual Studio 2010 with TFS, all these features are available i oe eviromet. Aother famous test framework for.net is NUit, a ported versio of the JUit framework used i the Java laguage derived from xuit. NUit is writte i C# ad is fully.net compliat. NUit is more flexible tha MSTest, ad it ships with both a commad lie ad a itegrated eviromet for Visual Studio. If you re plaig to work usig the TDD approach, you should give it a try. Ufortuately, sytax differs cosiderably betwee the various testig frameworks, so it s best to try all the available frameworks i advace, ad the adopt oly oe. Available Resources for TDD TDD is a complex techique that ca t be leared ad implemeted i a couple of days. To make it work, you eed to implemet it correctly. More importat, TDD requires disciplie ad cosistecy.

81 60 Chapter 2 Desig Patters For more readig about TDD, I recommed these books: Test-Drive Developmet i Microsoft.NET, by James W. Newkirk ad Alexei A. Vorotsov (Microsoft Press, 2009; ISBN: ) The Art of Uit Testig, by Roy Osherove (Maig, 2009; ISBN: ) You ca also fid a useful list of TDD resources o the MSDN website at or at this TDD developmet commuity site: I this book, you will ofte fid refereces to TDD techiques, alog with explaatios of how to properly test the MVVM patter implemetatios that are discussed here. Summary A desig patter is a guidelie that idetifies a commo solutio for a commo problem but that might be adapted to the specific problem to which it is applied. The commo desig patters are kow as Gag of Four desig patters ad classified ito three categories: creatioal, structural, ad behavioral. The classificatio is based o the type of problem the desig patter tries to solve. A additioal category of desig patters is composed of those used for user iterfaces; i this category there are four major patters: the MVC, the MVP, the PM, ad the MVVM. While the MVC ad the MVP are more geeric ad flexible, the MVVM is specifically desiged for WPF ad Silverlight. Yet aother category of desig patters is kow as Desig Patters for the Eterprise, or Architectural Desig Patters. Marti Fowler ad Eric Evas classified these patters, ad you ll fid them explaied i the book Patters of Eterprise Applicatio Architecture. The IoC patter is just oe of these Eterprise Patters. It s useful for movig the depedecies iside a called object from a caller object. Testig your applicatio is fudametal to avoidig bugs ad rutime errors. If you implemet TDD techiques from the outset, you ca guaratee that your applicatio is followig the desig requiremets ad that your code has bee tested before movig the applicatio to a productio eviromet.

82 Chapter 3 The Domai Model After completig this chapter, you will be able to: Uderstad Domai-Drive Desig techiques. Create a validatio mechaism for the Domai Model. Create a sample Domai Model. Itroductio to Domai-Drive Desig The key role of software is to solve problems ad fulfill requiremets. Of course, this ca be accomplished i differet ways. Oe way is by usig Domai-Drive Desig (DDD). With DDD, you try to solve the busiess problems that characterize the Domai Model by creatig a set of Domai Etities that represet the various busiess parts of the applicatio. Usig the DDD techique, you write a applicatio that has a firm foudatio, based o a object-orieted approach. You develop the code aroud the busiess etities that compose the busiess domai ad the adapt it to satisfy the busiess relatioships betwee the etities ad their behaviors. DDD is a set of methodologies ad techologies applied to a specific cotext, so implemetatio ca be very differet from oe applicatio to aother. The mai objective of a DDD applicatio is to focus o uderstadig ad modelig the Domai (the busiess requiremet), which is possible oly whe the developmet team already has a deep kowledge of the busiess requiremets. For this ad other reasos, DDD ca usually be achieved oly whe the team works i parallel with a group of aalysts who already kow the busiess requiremets of the applicatio. If you ad your team decide to apply the DDD techique, you are essetially agreeig to defie a commo laguage focused o the Domai Model desiged for the applicatio, which will reduce the laguage gap betwee aalysts, architects, ad developers. I fact, whe you start to develop a applicatio that ivolves people from differet backgrouds (such as the aforemetioed aalysts, architects, or developers) you will fid that each will typically defie the same thig usig differet termiology. The DDD techique should be able to bridge this gap. Because the DDD approach acts as a commuicatios chael betwee the project members, it is essetial that the laguage defied for the Domai Model is uambiguous ad clear. If the Domai Model is well defied ad the domai laguage is clear ad reflects the domai behaviors ad relatioships, the busiess logic of the etire domai will be clear ad uderstadable, as well to all the members of the project, whether they are aalysts, 61

83 62 Chapter 3 The Domai Model architects, or developers. The laguage you create usig the Domai Model should let you idetify gaps ad mistakes i the model, because it is the oly bridge betwee you ad the model. Oe fudametal requiremet of DDD is to isolate the Domai from the rest of the applicatio; you eed to keep the Domai Model as a pure laguage costruct for your domai problem. With that said, it s pretty clear that the DDD approach requires a lot of additioal effort, ad you should probably cosider it oly whe the domai problems are relatively complex ad the applicatio is relatively large. By that, I mea that you probably should t cosider the DDD as a feasible approach for a very simple applicatio because of its high cost. Still, I persoally always use the DDD approach, eve for very small domais composed of oly two or three domai etities. I believe that the DDD approach gives my applicatios a very high level of flexibility for future growth. As a summary of this brief itroductio to the DDD approach, here are the mai beefits of applyig the DDD techique to your applicatio: Commo Laguage If you defie a commo domai for your applicatio you will create a commo laguage usable i the same way ad with the same meaigs by all the team members. Extesibility The DDD approach lets you create a extesible applicatio because the domai is the core of the applicatio ad by desig a domai is extesible ad loosely coupled, so it should be relatively easy to exted ad implemet ew features i a existig domai model. Testability A DDD applicatio is testable by desig. DDD Termiology To uderstad ad model a domai, you eed a itroductio to the commo termiology used i this set of techiques so that you ca uderstad how DDD is structured. The Domai is the set of activities, kowledge, ad cotexts with which the applicatio is developed; it is specific to the busiess cotext of the applicatio. The Model is part of the Domai. It usually represets a specific set of aspects related to the Domai, ad is composed of a set of etities ad value objects. A etity is a uique object represeted i the Domai by a Domai Etity. Domai Etities are uique ad do ot chage whe the applicatio state chages. A etity ecapsulates properties, behaviors, ad states. For example, the Customer object of the sample CRM applicatio is a Domai Etity.

84 Itroductio to Domai-Drive Desig 63 A value object is a object used to describe some aspect of the Domai but that is immutable ad does t have a uique idetity i the Domai. For example, a Customer might have a list of Addresses; oe of these Addresses is a value object because it is used to describe a address of a Domai Etity of type Customer. Aggregate roots are root etities used to cotrol relatioships betwee child etities or child value objects. They typically cotrol access to these child objects ad/or to cotrol the iteractios betwee them. The ubiquitous laguage is laguage costructed aroud the Domai that developers ad aalysts will use to specify a particular aspect of the Domai. The cotext is clearly the world i which the model ca exist. Aalyzig the CRM Domai With those defiitios i place, you ca start with the user stories that represet the CRM applicatio example. Note A user story captures a requiremet, task, or part of a busiess process that the user will carry out whe usig the applicatio. It describes the busiess process i a uderstadable way for both users ad developers. The desig of this applicatio will be domai-drive (a cocept aalyzed i depth i this chapter), so the domai is the first compoet that eeds to be desiged. This domai-first desig is the typical approach you will use whe developig MVVM applicatios usig DDD for the Domai Layer. The user story is the draft of the busiess space; it describes how the various elemets of the domai iteract ad how specific tasks or busiess processes will be accomplished. There are usually several user stories for a applicatio, ot just oe. The sample CRM applicatio that you ll build i this book is composed of some user stories which are summarized i the followig paragraph as a set of macro user stories: As a Employee, I wat to be able to add ad maage Customers. As a Employee, I also wat to be able to maage Orders submitted by a Customer. As a Employee, I also wat to verify that a specific Product ordered by a Customer is available i stock. As a Customer, I wat to Order ay available Product.

85 64 Chapter 3 The Domai Model That s pretty simple. It s a pity that this clear ad complete statemet does t really offer much guidace to developers. So first, you eed to extract the core cocepts of this user story. The statemet idicates oe domai that we will call CRM.Domai, ad four pricipal etities: a Employee, a Customer, a Order, ad a Product. You will eed to add additioal compoets to these major models, such as a Address, a Cotact, a OrderLie, ad so o. Usig a piece of paper ad a pecil to create a rough model, we ed up with somethig like Figure 3-1. This is the first draft of the Domai Model. As you proceed through this chapter, you will see how to evolve ad compose each part of this domai ad use it i a MVVM applicatio. Perso Cotact Address Employee Customer Approval Orders Items Product Figure 3-1 A mockup of the CRM Domai Model. You ca compare this diagram to a set of simple objects modeled i C# or Visual Basic.NET, where each shape represets othig more tha oe or more classes with relatioships that ca be properties, complex objects, a collectio of child objects, or a referece to a paret object. Domai Etity ad Data Trasfer Object Let s start with the defiitio of a Domai Etity ad a Data Trasfer Object (DTO), with the uderstadig that you ll keep these cocepts i mid for the remaider of the book. I ve used the followig covetio sytax i this book; you might fid differet defiitios, but the cocepts that I expose here are the basic cocepts of DDD ad ot a merely a persoal iterpretatio. A Domai Etity, also kow as a Domai Object, is a compoet of the Domai Model that represets the uiqueess of a elemet i the busiess domai, ad that maitais the state of that elemet. For example, i the CRM Domai Model, the Employee etity is a Domai Etity.

86 Domai Etity ad Data Trasfer Object 65 A DTO is a flat object it s serializable, ad used to trasfer data betwee layers, objects, ad/or tiers. It does t have ay busiess logic, ad usually, it does t have ay circular refereces to paret or child objects. Software architects such as Marti Fowler use the term Value Object to defie a simple object i the Domai Model that does t have a specific idetity. The cocept of a DTO is madatory i DDD, ad here s why. Imagie that the MVVM applicatio has a simple XAML combo box that you wat to populate with all the available employees i the database. You might easily come up with somethig like this: // C# code to retrieve the data Var employees = datalayer.getallemployees(); // this returs a IList<Employee> // Pseudo XAML <combobox ItemSource="Bidig Path=employees" DisplayMemberPath="FirstName" SelectedValuePath="Id" /> I the precedig code, a big problem is that you are truly bidig the etire employee etity. Eve though the code uses oly the first ame ad the ID, i reality, you re holdig the etire object i memory. For example, if the Employee has a list of Address etities mapped as a property, the code also carries that list alog i memory. The solutio is to flatte this object by usig a DTO that will represet oly the data eeded at the momet. A etity might have oe or may DTOs, depedig o the cotext. The followig example uses a LINQ extesio to create a ew list of DTOs, startig from a list of etities. Public class EmployeeDto strig FirstName get; set; Guid Id get; set; // C# code to retrieve the data Var employees = datalayer.getallemployees().aggregate(ew List<EmployeeDto>() => (list, obj) var dto = ew EmployeeDto FirstName = obj.firstname, Id = obj.id ; list.add(dto); retur list; ); // Pseudo XAML <combobox ItemSource="Bidig Path=employees" DisplayMemberPath="FirstName" SelectedValuePath="Id" /> There are two more cosideratios about etities ad DTOs. First, ote that although busiess logic was ot discussed, it should be icluded i the Domai Etities ad i the Domai

87 66 Chapter 3 The Domai Model Services. You ll see why i future chapters. The secod cosideratio lies i the way you ca map a etity agaist a DTO, ad vice versa. You ll see how to use reflectio or emit to create a simple auto-mapper compoet for your applicatios, ad how to use existig tools such as Auto-Mapper ( or Emit Mapper ( codeplex.com). Here s a brief summary of what a Domai Etity is, alog with its commo characteristics ad costraits: A Domai Etity should be implemeted usig persistece igorace; it should ot be aware of how it is persisted i a database or whe it should be persisted. You wat to be able to use the domai across multiple applicatios ad across multiple storage types. A Domai Etity represets a specific problem of the domai, but it is ot a busiess object; it ecapsulates oly the busiess logic required, ad othig more. If you wat to add busiess logic to a Domai Etity, you should cosider buildig a specific Busiess Object (this is discussed i future chapters). A Domai Etity should be aware of its validatio ad its costraits as related to other Domai Etities available i the same Domai. It should use a clear amig covetio, ad it should reflect the ubiquitous laguage usig oly the ative properties ad methods of the etities. The POCO Object ad the O/RM I the previous sectio, you saw that the uique role of a Domai Etity is to address a specific area or aspect i the domai. This cocept is clear, but it s a far cry from the reality of a real-world applicatio. Based o DDD defiitios ad paradigms, a Domai Etity should be a POCO object, or rather, a object that does t kow aythig about its persistece, ad that does t iherit specific classes before it ca be persisted or used with a specific framework. Referrig back to the previous example, you might have oticed that I added a ID property to the Employee etity to specify its uiqueess i the collectio, such as i a database table. Without the ID, you would ot be able to idetify the selected Employee i the ComboBox. I DDD, the Domai Etity should be a POCO (.NET) or POJO (Java) object. I my opiio, this cocept works oly i the abstract; it is ot feasible i practice. I also wat to expoud upo the importace of idetity for a Domai Etity. Suppose you have two Employee etities, defied as follows: Var employee = ew Employee FirstName = "Joh", LastName = "Smith", Age = 54 Var employee = ew Employee FirstName = "Joh", LastName = "Smith", Age = 23

88 Developmet Approaches of a Domai 67 Without attachig some sort of UiqueId to each oe, you would t be able to distiguish betwee them. This is t a urealistic example; it s highly likely that a orgaizatio might have two differet employees with the same FirstName ad LastName, but who have differet ages or differet roles i the system. To work with a O/RM such as the Etity Framework or NHiberate (as you will i this book or i ay other multi-tiered applicatio), it will be madatory, by desig, to add a costrait to such etities that makes them uique i the model. Therefore, you must give them a idetity just as you would with the rows of a table, usig the primary key. This requiremet does ot mea that the etities are ot POCO, but it does break the perfect desig of a POCO object. Aother questio revolves aroud persistece igorace, which occurs whe your classes ad the surroudig applicatio layers do t kow or care how their data is stored. For example, i the.net 3.5 versio of Etity Framework, if you wated to use pre-existig classes, you had to modify them by forcig them to derive from EtityObject. I.NET 4, this is o loger ecessary. You do t eed to modify your etities for them to participate fully i Etity Framework operatios. This allows you to build applicatios that embrace loose couplig ad Separatio of Cocers. With these codig patters, your classes are cocered oly with their ow jobs. May layers of your applicatio, icludig the UI, have o depedecies o exteral logic, such as the Etity Framework APIs, yet those exteral APIs are still able to iteract with your etities. I coclusio, the cocept of POCO (POJO) objects is eat ad clear i DDD, but urealistic i a real-world applicatio. As I have metioed before, remember that the cocepts are guidelies, ot policies, so you should follow them whe possible, ad the adapt your code to meet your specific eeds. Developmet Approaches of a Domai Marti Fowler s book, Patters of Eterprise Architecture Applicatio (PoEAA), metios three differet approaches for developig the Domai. Takig the cocept of a Domai as just a geeral defiitio, Fowler says that you ca develop a applicatio usig oe of the three available patters for the Domai: the Trasactio script, the Active Record, ad the Domai Model. The DDD approach described i this book uses the Domai Model approach, but for simpler applicatios, you might cosider usig the Active Record approach, or if you just eed to write a sequetial set of commads, you would probably wat to use the Trasactio Script approach. It s worth explorig why ad whe you should use each of these patters.

89 68 Chapter 3 The Domai Model Trasactio Script The Trasactio Script approach is ofte used by o-expert developers i situatios such as a juior developer s first project or for a simple utility script. The mai cocept of the Trasactio Script is to orgaize all logic primarily as a sigle procedure, makig calls directly to the database or through a thi database wrapper. Each trasactio will have its ow Trasactio script, although commo subtasks ca be broke ito subprocedures. For example, you might eed to write a fuctio that will prit out a list of available employees. To do that usig the Trasactio Script approach, you would write code similar to that show below, where the coectio, the SQL statemets, ad the C# code are mixed together i a sigle step. Var coectio = ew SqlCoectio(); var commad = ew SqlCommad(coectio, "SELECT * FROM EMPLOYEE"); var reader = commad.executereader(); Coectio.Ope(); while(reader.read()) Cosole.WriteLie("Employee: 0 1" reader["firstname"], reader["lastname"]); // ed of pseudo code You might agree with me that this piece of code is faster to develop ad easier to read ad chage tha a layered applicatio approach, but it s absolutely umaitaiable ad redudat. That s because if you later decide that you eed to execute that same query withi some other fuctio, you would have to copy (or rewrite) the same code ad every time you eed to chage somethig you would have to make that chage i every piece of code that uses that SQL statemet. I additio, this code is o-testable, because the database logic ad the code are totally boud together without ay architectural logic. Usig the Trasactio Script approach becomes uteable whe the sigle trasactio code (procedure) becomes complex. Evetually, you will wat to break the code ito a smaller set of trasactios that are called sequetially by a mai task. That s the poit where you begi to completely lose cotrol of your applicatio. Every time you have a bug, the oly solutio is to debug the full stack. I simply do t recommed this techique for ay situatio except whe you have sequetial steps that eed to be executed ad the flow of these sequetial steps will ever chage durig the evolutio of the software, such as i the followig pseudo code: Public void ApproveOrder() VerifyOrder(order); VerifyCustomer(customer); AssigOrder(employee, order); ApproveOrder(order);

90 Developmet Approaches of a Domai 69 I this case, the workflow sequece is a requiremet of the Domai Etity Order before a order ca be approved. Most probably, this workflow will ever chage, so you ca use the Trasactio Script approach i this type of situatio successfully. Still, ote that this example is just a sequece of methods; it does t embed SQL calls or UI calls withi a sigle method. Database-Drive Approach Ofte, developers do t have the power to desig a applicatio from the begiig, for may differet reasos. For example, you might be tasked with rewritig a existig legacy system where the database ca t be altered, ad it s difficult to desig a domai that fits the existig database. Or you might have scarce programmig resources, ad the lifetime of the applicatio will be short, such as a utility that will ru for few moths. These cases are t coducive to writig a complex tiered system that will possibly take more time to develop tha the expected applicatio lifetime. The database-drive approach forces you to adopt the Active Record patter. I this patter, the mai player of the applicatio is the database, ad you desig the domai to reflect the structure of that database. Therefore, you will have a Domai Etity for each table i the database ad the eeds of the database drive the applicatio flow. This approach is ot wrog especially if you have just started to use the DDD approach but have t yet mastered it. May O/RMs, such as Etity Framework or NHiberate, offer the possibility of creatig a Active Record domai without losig the power of a relatioal model ad a Data Layer; ufortuately, this approach is still far away from the more robust ad complex DDD approach. I this case, because the object (etity) is a specular image of the relative database table, the object itself must be i charge of updatig its status agaist the database, ad must also be aware of how it s saved ad retrieved from the database, so you d typically see code such as: Var employee = New Employee().Get(1); employee.firstname = "Joh"; employee.save(); I would say that if you eed to write a simple data-etry applicatio that does t iclude ay complex busiess logic or ay data trasactios, the Active Record patter is probably a good startig poit. Remember however, that it would be both the startig ad edig poit; this patter ca t be exteded or chaged like DDD. Aother problem with this patter is that because etities have full cotrol of the persistece process, a developer ca easily write code that will icorrectly drop or chage a existig record.

91 70 Chapter 3 The Domai Model I my opiio, you should avoid this patter whe desigig complex ad extedable Lie of Busiess (LOB) applicatios, because: Versioig of a record with the Active Record patters is a osesical approach. The active etity is the row i the database, so if you wat to keep a history of data chages, you have to cloe the active record wheever it chages, storig the older versio ad replacig it with the ew versio. You caot separate state ad behavior, because the etity is i charge of persistig itself ad also holds its data structure. I other words, with Active Record, etity state ad behavior are wrogly mixed together, such as i the Save() commad or the IsNew property. There s o Separatio of Cocers, ad the code is difficult to test. For oe thig, the etity works oly if the database is available, so you ca t test the etity by itself without also testig the database ad that breaks oe of the priciples of Test-Drive Developmet (TDD), because the tests caot be as idepedet as they should be. Domai-Drive Approach The Domai-Drive approach is the cocrete implemetatio of the DDD techique. I this case, you have a Domai that drives the etire applicatio. The Domai is totally uaware of ay correspodig database. To make everythig simpler, you ca use a O/RM, such as Etity Framework or NHiberate, to help create the correct SQL code to persist the etities i the database. DDD is the most complicated approach because it requires more time, more tests, ad more agility, ad because it also requires a deep kowledge of the busiess processes. I the ed, though, it is also the most flexible ad maitaiable approach because the Domai ad the database are ot closely related. Suppose that ext moth, your compay has decided to switch from SQL Server to MySQL. By usig the DDD approach, you will oly eed to chage the coectio strig i your O/RM. Or suppose that the order approval process chages, because of some restrictive policies itroduced i the accoutig departmet. With DDD, you will just eed to idetify that process i the model ad update it. With the Domai-Drive approach, you usually work with a O/RM ad have a UitOfWork, which is a compoet that keeps the database sessio alive so that you ca execute create, read, update, ad delete (CRUD) operatios agaist it. You ll aalyze this patter i detail i the ext chapter, whe you build the Data Layer for the sample CRM applicatio. With the UitOfWork ad the DDD, you would execute the code you saw i the Trasactio Script sectio this way istead: Var employees = uitofwork.get<employee>(); foreach (var employee i employees) Cosole.WriteLie("Employee: 0 1", employee.firstname, employee.lastname);

92 How To Create a Object I DDD 71 You saw i the chapter itroductio why you should use the Domai-Drive approach ad why it s more flexible tha other approaches. As you go forward, just keep i mid the highlights listed here: DDD is busiess orieted, so you do t eed to kow all the available tables i a database to commit a busiess trasactio with your code; the Domai speaks for itself ad it s self-explaatory, providig ubiquitous laguage The Domai is extesible ad recyclable because the oly costrait is the busiess aroud it ad othig else, such as a database or framework Your applicatio becomes plug-ad-play because the Domai (the busiess core) is t costraied to a specific techology. If you eed it for aother applicatio, you ca just add it as a compoet ad use it It s totally testable; you ca test the Domai before you have ay database or UI ready for testig. You ca also expad or evolve ad retest it repeatedly durig your applicatio s evolutio. How To Create a Object I DDD I object-orieted programmig (OOP) sytax, you usually create o-static objects usig the ew keyword. The process is similar but a little bit differet i C#, Visual Basic.NET, or Java. Whe you eed a ew istace of a object, you simply create it usig the ew keyword, ad the start usig it, for example, by chagig some property values or callig a specific method. Usig the costructor method, you ca come up with two differet choices; you ca create a parameterless costructor or a costraied costructor that will force developers to provide specific values whe creatig the object. //parameterless var employee = ew Employee(); employee.firstname = "Joh"; employee.lastname = "Smith"; employee.age = 54; //costructor with parameters var employee = ew Employee("Joh". "Smith", 54); Both methods work fie. The first oe is probably more ope because it does t force developers to specify aythig they ca simply create a empty ew Employee object. The secod oe is more data drive because it requires a specific FirstName, LastName, ad Age to work. (You ca also use C# 4 optioal parameters to avoid the last oe, but i that case you ca set up default values that might be icorrect for that Etity type.)

93 72 Chapter 3 The Domai Model Whe you start to work with MVVM, the first problem you will ecouter from a architectural poit of view is that the applicatio is layered, so the developer who wrote the Domai Model might ot be the same as the developer(s) who will use it i the ViewModel or Busiess Layer. For these reasos, you must apply some costraits o how to create a ew Domai Etity to esure that the etity is valid ad created correctly. The factory patter, discussed i Chapter 2, Desig Patters, is a object-creatioal patter desiged to drive the creatio of a specific object. The factory patter is madatory i a DDD applicatio because it drives developers to create etities usig specific guidelies ad it supports TDD. The followig example illustrates why: //factory for Employee var employee = Factory.CreateEmployee("Joh", "Smith", 54); // throw exceptio because the age ca t be lower tha 1 var employee = Factory.CreateEmployee("Joh", "Smith", 0); //here we have some busiess logic that we may ot eed to kow var employee = Factory.CloeEmployee(aotherEmployee); The precedig code forces developers to create a ew Employee through the available factory methods; if the developer eters a ivalid age, for example, the factory will simply throw a exceptio. The same is true for the cloig process; usig the factory method forces the developer to cloe a employee i a predefied way, drive by the Domai logic. Factory Patters If you pla to use the factory method i your Domai you will guaratee a costrait i the creatio of a ew Domai Etity i the etire project. Factory patters are divided ito two subpatters: the abstract factory ad the factory method. The mai differece betwee these two creatioal patters is that the first oe defies a geeric factory that s i charge of creatig ay object, as show i the followig code: Var employee = AbstractFactory.CreateEmployee(); var order = AbstractFactory.CreateOrder(); I cotrast, the Factory patter is orieted more toward the Domai Etity, so you will have a factory class for each available etity i the domai: Var employee = EmployeeFactory.Create(); var order = OrderFactory.Create(); Which method you use is up to you, but you should cosider the maiteace process whe makig a decisio. For example, if you choose to use the abstract factory, wheever you eed to chage the creatioal process for a specific type, you might break the code for creatig some other type. For simplicity, I use a custom implemetatio of a abstract factory/ method.

94 How To Create a Object I DDD 73 The small Domai below (Figure 3-2) represets a Employee etity with a set of addresses. The first rule of the factory is that you ca t create a Address without havig it attached to a paret Employee, because a Address without a Employee does t have ay logical busiess meaig i the Domai. Figure 3-2 A sample Domai Model for the Factory Patter. The factory method/abstract factory implemetatio I use is represeted by the followig class diagram (Figure 3-3), which cotais a abstract factory that defies the costraits i my code but has a cocrete implemetatio of the factory for each Domai Etity, to provide more cotrol ad decouplig from the Abstract Factory patter: Figure 3-3 Implemetatio of the Abstract Factory patter i cojuctio with the factory method. This architecture provides a clea way to create a ew object for use i a applicatio. For example, to create a ew Address, you must specify a paret Employee etity, ad to create a ew Employee, you must provide the basic iformatio required for a Employee: // Create a ew Employee var employee = FluetFactory.Employee().Create("Joh", "Smith", "Microsoft", 54); // Create a ew Address var address = FluetFactory.Address().Create(employee, "Mai Street 14", coutry: "USA"); employee.addresses.add(address);

95 74 Chapter 3 The Domai Model // verify the object created Cosole.WriteLie("Employee: 0 1 has 2 addresses.", employee.firstname, employee.lastname, employee.addresses.cout); Cosole.ReadLie(); //cloe the employee ad chage the first ame var cloed = FluetFactory.Employee().Cloe(employee); cloed.firstname = "Sarah"; // verify the cloed object Cosole.WriteLie("Employee cloed: 0 1 has 2 addresses.", cloed.firstname, cloed.lastname, cloed.addresses.cout); Cosole.ReadLie(); You ca still put costraits i your factory, such as throwig a exceptio if the value provided for a parameter is ot correct (for example, the Age < 21) or if a value is ot withi a specified rage, but at this poit, you ca make developers aware of the potetial exceptios usig Visual Studio decoratios. Look at the followig code used to create a ew Employee: /// Creates the specified Employee. /// <param ame="firstname">the first ame.</param> /// <param ame="lastname">the last ame.</param> /// <param ame="compay">the compay.</param> /// <param ame="age">the age. /// </param> /// <returs></returs> /// <exceptio cref="system.argumetnullexceptio">throw whe the /// Age is lower tha 21</exceptio> public Employee Create( strig firstname, strig lastname, strig compay, it age) if (age < 21) /// <exceptio cref="system.argumetnullexceptio">throw whe /// the Age is lower tha 21</exceptio> throw ew ArgumetNullExceptio("The Age should be greater tha 21."); You might also cosider leavig the factory wide ope, ad the implemetig the validatio patter over the Domai Etity. You ll see more about the Validatio Patter i the ext sectio.

96 Domai Etities Validatio Domai Etities Validatio 75 Earlier, whe discussig the Domai Model, I wrote that a Domai Etity should be agostic agaist ay framework or Data Layer: it should be a POCO object. For the same reaso, a Domai Etity should ot be aware of its validatio, because that might differ betwee two differet applicatios usig the same Domai. Note that this is just my poit of view; there are ogoig debates i the software architect commuity o where to place validatio logic. Some believe it should be placed iside a Domai Etity while others believe it should be placed outside. Validatio is the process by which you verify that the data of a specific object or class is valid. To make that decisio, you eed a set of validatio rules for each property that describes why ad whe the data might or might ot be valid. Oe possible way to provide validatio support i the Domai Model is to provide a layer supertype (a commo class or compoet used to icorporate commo behaviors or properties used by all the classes or objects of that layer through iheritace from this supertype) that ca delegate the validatio of a specific etity to a separate validatio service. This is what happes with the Etity Framework auto-geerated model, i which each class iherits from a commo base class that also provides validatio support. A alterative method is to provide a parallel iterface for validatig a specific Domai Etity, usig that Iterface to keep the Etity itself uaware about the validatio process. Classic Validatio The example that follows shows the classic way of validatig a object usig a simple Validatio Service, ot geeric, with embedded validatio rules. First, there s a base class that defies the cotract for the validator: public abstract class BaseValidator<T> /// Determies whether the specified etity is valid. /// <param ame="etity">the etity.</param> /// <returs> /// <c>true</c> if the specified etity is valid; otherwise, <c>false</c>. /// </returs> public abstract bool IsValid(T etity); /// Gets or sets the errors. /// <value>the errors.</value> protected IList<ValidatioResult> Errors get; set;

97 76 Chapter 3 The Domai Model Next, you eed to create a validator for each Domai Etity that you wat to validate. Of course, usig this approach, you ca easily exted the validator for other objects, such as a ViewModel i a WPF/Silverlight applicatio or a DTO for a RIA Service. public sealed class EmployeeValidator : BaseValidator<Employee> /// Determies whether the specified etity is valid. /// <param ame="etity">the etity.</param> /// <returs> /// <c>true</c> if the specified etity is valid; otherwise, <c>false</c>. /// </returs> public override bool IsValid(Employee etity) var result = true; this.errors = ew List<ValidatioResult>(); if (etity.firstname.legth < 10) this.errors.add(ew ValidatioResult( "The Firstame should be greater tha 10.")); result = false; if (etity.lastname.legth < 10) this.errors.add(ew ValidatioResult( "The Lastame should be greater tha 10.")); result = false; retur result; You ca easily test this code by verifyig that the Domai Etity is ot valid if you isert a empty FirstName, such as i the followig: ///A test for IsValid ///</summary> [TestMethod()] public void IsValidTest() EmployeeValidator target = ew EmployeeValidator(); Employee etity = ew Employee FirstName = "", LastName = ""; bool expected = false; bool actual; actual = target.isvalid(etity); Assert.AreEqual(expected, actual, "The Etity should ot be valid at this poit.");

98 Domai Etities Validatio 77 The mai disadvatages of this approach are: It embeds the validatio rules i a custom class that is difficult to documet. The validatio rules are composed of a set of if statemets i procedural C# code; as the rule set becomes more complex, it becomes more difficult to test its correctess. The advatage of usig this approach is that the Domai Model is totally uaware of the available validatio rules. You ca use this Domai Etity with or without validatio support, ad you ca chage the validatio depedig o the cotext. Validatio Usig Attributes ad Data Aotatios I the.net Framework 4, a amespace called System.CompoetModel.DataAotatios is available for both the commo CLR (WPF) ad the lighter Silverlight CLR. You ca use the DataAotatios amespace for various purposes. Oe of these is for data validatio usig attributes, ad aother is the visual descriptio of fields, properties, ad methods, or to customize the data type of a specific property. These three categories are classified i the.net Framework as Validatio Attributes, Display Attributes, ad Data Modelig Attributes. This sectio uses Validatio Attributes to defie validatio rules for objects. You ll use the Display Attributes category i Chapter 6, The UI Layer with MVVM, which is dedicated to the MVVM toolkit, ad the Data Modelig Attributes i Chapter 4, The Data Access Layer. To use the DataAotatios amespace, you eed to add a referece to the assembly that referece is ot icluded i ay Visual Studio project template by default. The you eed to decorate your objects with the correct attributes. As a example, the code below uses a icorrect approach of decoratig a Domai Etity directly with these attributes. Next, I will refactor this code to make that etity uaware of its validatio. public sealed class Customer /// Gets or sets the first ame. /// <value>the first ame.</value> [Required(ErrorMessage = "The FirstName is a madatory Field")] [StrigLegth(10, ErrorMessage = "The FirstName should be greater tha 10 characters.")] public strig FirstName get; set; /// Gets or sets the last ame. /// <value>the last ame.</value>

99 78 Chapter 3 The Domai Model [Required(ErrorMessage = "The LastName is a madatory Field")] [StrigLegth(10, ErrorMessage = "The LastName should be greater tha 10 characters.")] public strig LastName get; set; /// Gets or sets the title. /// <value>the title.</value> [Required(ErrorMessage = "The Title is a madatory Field")] public strig Title get; set; The Customer etity ca be easily validated usig a geeric validator because you kow that we wat to validate oly those properties that have a DataAotatios attribute o them. public sealed class GeericValidator<T> /// Validates the specified etity. /// <param ame="etity">the etity.</param> /// <returs></returs> public IList<ValidatioResult> Validate(T etity) var results = ew List<ValidatioResult>(); var cotext = ew ValidatioCotext(etity, ull, ull); Validator.TryValidateObject(etity, cotext, results); retur results; At this poit, we ca easily test the validator agaist the Customer etity, as follows: /// Determies whether this istace [ca validate customer]. [TestMethod] public void CaValidateCustomer() Customer etity = ew Customer FirstName = "", LastName = "" ; GeericValidator<Customer> target = ew GeericValidator<Customer>(); bool expected = false; bool actual; actual = target.validate(etity).cout == 0; Assert.AreEqual(expected, actual, "The Etity should ot be valid at this poit."); Now, to remove the validatio from the Domai Etity you eed to create a iterface that represets the Domai Etity ad that icludes the validatio rules, ad the iherit the Domai Etity from this iterface. At the ed of this process, you should be able to write code like this:

100 Domai Etities Validatio 79 /// Determies whether this istace [ca validate customer]. [TestMethod] public void CaValidateCustomer() Customer etity = ew Customer FirstName = "", LastName = "" ; GeericValidator<ICustomer> target = ew GeericValidator<ICustomer>(); bool expected = false; bool actual; actual = target.validate(etity).cout == 0; Assert.AreEqual(expected, actual, "The Etity should ot be valid at this poit."); Available Validatio Frameworks The validatio techique that was just preseted is oly oe of the techiques available for.net. The advatage of usig DataAotatios is that it plugs ito WPF ad Silverlight perfectly, ad it is desiged i a way that works throughout all the layers of a MVVM applicatio. I the ViewModel sectio, you ll see why the DataAotatios approach is the perfect match for WPF or Silverlight. Aother iterestig framework created by Microsoft is the Validatio Applicatio Block, which is available with Microsoft Eterprise Library 5.0 ( The Validatio Applicatio Block uses the same geeral approach validatig a object agaist a set of rules defied usig attributes (data aotatios) or a exteral XML file. The major differece from the DataAotatios is the process you use to validate a object, but you should obtai the same fial result. Aother framework, part of the ope-source project NHiberate, is the NHiberate Validatio Framework. This is available at as part of the NHiberate Cotrib project. The mai disadvatage of usig this framework is that uless you are plaig to use NHiberate as your O/RM, you will itroduce a additioal depedecy i your layers that might ot be eeded. This framework also requires you to sully your etities with validatio rules related to a specific O/RM. To sum up, it s importat to keep the Domai clea ad uaware of the validatio rules or methods you re usig, but it s also importat that you decide to use the appropriate framework for the type of applicatio that you re writig. I this book, you ll largely use the data aotatios feature provided i the.net Framework.

101 80 Chapter 3 The Domai Model Uit Test the Domai Model You should create the process for testig the Domai Model before startig to write the code for the Domai Model itself; this will guaratee that you will test the code agaist the expected results rather tha vice versa. Whe you write a Domai Model, you usually iclude some small busiess rules i your code that should be validated so that you ca be sure that the Model is workig properly. For example, the CRM Domai Model will have a Perso etity that will have a set of Address etities icluded i a IList<T> collectio. We wat to guaratee throughout the etire model cotext that a Perso ca have oe, ad oly oe, Address as the default address. Aother rule is that uless specified, the first address added to a Perso etity s Address list will be the default address. For this example, you should be able to write a first test like this: Var perso = PersoFactory.Create(); var address01 = AddressFactory.Create(); var address02 = AddressFactory.Create(); perso.addaddress(address01); perso.addaddress(address02); Assert.IsNotNull(perso.DefaultAddress); Assert.IsTrue(perso.DefaultAddress == address01); Aother test borig but useful is to test each property value of your etity before startig to validate the etity itself. For example, we might wat to be sure that whe we call the FullName read-oly property of a Perso etity, the result will be the FirstName, a space, ad the LastName. Var perso = PersoFactory.Create("Joh", "Smith"); Assert.AreEqual(perso,FullName, "Joh Smith"); Costatly testig the defiitio of your Domai Model agaist the rules of your Model is your blueprit for guarateeig that ay chage to the Model wo t adversely affect the existig data structure ad the existig flow of the Model. Validatio is also aother iterestig part that must be tested to be sure that the approach is workig as expected. The oly problem you might have whe testig validatio is that you should hard code the validatio rules i your tests to be sure that you are testig the correctess of the validatio rule set; o the other had, that s useful for trackig what you have chaged i the validatio rule set itself. Var perso = PersoFactory.Create("Joh", "Smith"); // Validate retur a Boolea result Assert.IsTrue(Validator.Validate(perso)); var ivalidperso = PersoFactory.Create(); Assert.IsFalse(Validator.Validate(ivalidPerso));

102 Sample Code: The CRM Domai Model Sample Code: The CRM Domai Model 81 Begiig with this chapter, the ed of every chapter cotais a sectio called Sample Code, which is where you ll build the CRM applicatio usig the kowledge acquired i the earlier parts of the chapter. I this chapter, you ve see what a Domai Model is, how it should be implemeted ad tested, ad looked at factory implemetatio ad the validatio process. So first, let s revisit the user story that was give to us from the customer whe he called to get a ew CRM applicatio. As a Compay that sells products, I wat to be able to maage my Orders; I eed a system that moitors the availability of the Products, a registry sectio to admiister my Customers, ad a approval process maaged by oe of the available employees registered i the system. I have idetified this user story with oe Domai composed of the etities i charge of admiisterig employees, customers, ad their iformatio, ad a etity i charge of makig ad approvig a order, based o a list of submitted ad available products. The Perso Cotext A Employee ad a Customer ca be grouped by some commo iformatio, such as FirstName, LastName, ad so o. But there are also properties that relate more to a Customer tha to a Employee. For example, you might ot care about displayig a address for a employee, but you might eed to kow how to cotact him; o the other had, the user probably eeds to kow everythig about a customer who placed a order, because you must kow where to ship the order ad how to cotact the customer if there is a problem with the submitted order. Your Domai will have, for ow, a very simple layer supertype that will be the DomaiObject class. This class has oly oe property, PrimaryKey, of type GUID, which will help distiguish the various etities available i the Domai cotext. I the ext chapter you ll see why it s importat to decide the primary key type of a etity before decidig o the fial data store. Note As a desig choice I will decorate the Domai Etities with Validatio Rules. I am doig this solely because I wat to show how to use validatio attributes ad at the same time you ll be able to explore the structure of the Domai Etities. For real-world applicatios, I suggest that you embed validatio attributes o a exteral iterface that will be implemeted by the Domai Etity.

103 82 Chapter 3 The Domai Model The followig code shows the base DomaiObject layer supertype: /// The basic Domai Object public abstract class DomaiObject /// Gets or sets the primary key. /// <value>the primary key.</value> [Required(ErrorMessage = "The Primary Key ca t be ull or empty.")] public Guid PrimaryKey get; set; The Model will cotai aother abstract class called Perso, which defies some commo properties ad methods available for both Employee ad Customer etities. The class must be abstract because we do t wat this class used directly by some developer i the code by mistake, but at the same time, we do t wat to write the same code twice. public iterface class Perso : DomaiObject /// Gets or sets the first ame. /// <value>the first ame.</value> [Required(ErrorMessage = "The FirstName ca t be ull or empty.")] public strig FirstName get; set; /// Gets or sets the last ame. /// <value>the last ame.</value> [Required(ErrorMessage = "The LastName ca t be ull or empty.")] public strig LastName get; set; /// Gets the full ame. /// <value>the full ame.</value> public strig FullName get retur Strig.Format("0 1", FirstName, LastName); /// Gets or sets the title. /// <value>the title.</value> [Required(ErrorMessage = "The Title ca t be ull or empty.")] public strig Title get; set;

104 Sample Code: The CRM Domai Model 83 /// Gets or sets the birth date. /// <value>the birth date.</value> [Required(ErrorMessage = "The Birth Date ca t be ull or empty.")] public DateTime BirthDate get; set; /// Gets or sets a value idicatig whether this istace is active. /// <value><c>true</c> if this istace is active; otherwise, <c>false</c>.</value> public bool IsActive get; set; /// Gets or sets the cotacts. /// <value>the cotacts.</value> public IList<Cotact> Cotacts get; set; /// Gets the default cotact. /// <value>the default cotact.</value> public Cotact DefaultCotact get if (Cotacts == ull) retur ull; retur Cotacts.Where(x => x.isdefault).firstordefault(); /// Adds the cotact. /// <param ame="cotact">the cotact.</param> public void AddCotact(Cotact cotact) if (Cotacts == ull) Cotacts = ew List<Cotact>(); // If there are o default address, set this oe as default if (Cotacts.Where(x => x.isdefault).cout() < 1) cotact.isdefault = true;

105 84 Chapter 3 The Domai Model //If this is the ew default address if (cotact.isdefault) foreach (Cotact cot i Cotacts) cot.isdefault = false; // If the address is ot already i the list if (!Cotacts.Ay(x => x.primarykey == cotact.primarykey)) Cotacts.Add(cotact); You might already otice that this etity itroduces two ew etities: Cotact ad Address. The Cotact etity will be exposed by both Employee ad Customer etities, because we might eed to have a default cotact for each of them. The Address etity is exposed oly by the Customer, because it is ot part of the LOB applicatio that we are buildig to make us aware of ay specific address for a Employee. public sealed class Cotact : DomaiObject /// Gets or sets the type of the cotact. /// <value>the type of the cotact.</value> public CotactType CotactType get; set; /// Gets or sets the ame. /// <value>the ame.</value> [Required(ErrorMessage = "The Name is a madatory field")] public strig Name get; set; /// Gets or sets the descriptio. /// <value>the descriptio.</value> [Required(ErrorMessage = "The Descriptio is a madatory field")] public strig Descriptio get; set; /// Gets or sets the umber. /// <value>the umber.</value> [Required(ErrorMessage = "The Number is a madatory field")] public strig Number get; set;

106 Sample Code: The CRM Domai Model 85 /// Gets or sets a value idicatig whether this istace is default. /// <value> /// <c>true</c> if this istace is default; otherwise, <c>false</c>. /// </value> public bool IsDefault get; set; Note that the Cotact etity itroduces the first Eum i this applicatio. Usig Eums i a Domai is importat because they re self-explaatory ad totally elimiate mistakes that ca occur whe usig plai strigs or iteger values. The followig Address etity is o differet tha the Cotact etity except for the exposed properties. Note If you follow the Marti Fowler approach, you would classify the Cotact ad Address etities as Value Objects more tha Domai Etities because they represet a small compoet of a bigger Domai Etity, but they are ot really Domai Etities they do t have a idetity represetatio i the Domai. public sealed class Address : DomaiObject /// Gets or sets the address lie1. /// <value>the address lie1.</value> [Required(ErrorMessage = "The AddressLie1 is a madatory field")] public strig AddressLie1 get; set; /// Gets or sets the address lie2. /// <value>the address lie2.</value> public strig AddressLie2 get; set; /// Gets or sets the tow. /// <value>the tow.</value> public strig Tow get; set; /// Gets or sets the city. /// <value>the city.</value> public strig City get; set;

107 86 Chapter 3 The Domai Model /// Gets or sets the state. /// <value>the state.</value> [Required(ErrorMessage = "The AddressLie1 is a madatory field")] public strig State get; set; /// Gets or sets the coutry. /// <value>the coutry.</value> [Required(ErrorMessage = "The AddressLie1 is a madatory field")] public strig Coutry get; set; /// Gets or sets the zip code. /// <value>the zip code.</value> [Required(ErrorMessage = "The AddressLie1 is a madatory field")] public strig ZipCode get; set; /// Gets or sets a value idicatig whether this istace is default. /// <value> /// <c>true</c> if this istace is default; otherwise, <c>false</c>. /// </value> public bool IsDefault get; set; The Domai Etity Employee has bee omitted because, as you ca see from Figure 3-4, the implemetatio is self-explaatory; it iherits from the class Perso ad it does t have ay additioal properties. I coclusio, we ow have the two mai etities of this Model: Employee ad Perso. The differece betwee them is, as poited out previously, the Addresses list, but also, a Customer has a list of Orders while the Employee has a list of Approval. Figure 3-4 shows the fial diagram for the Perso Domai. To save space, I have t icluded the rest of the code here, but the full code is available with the dowloadable compaio cotet to this book (see the dowload istructios i the Itroductio to this book).

108 Sample Code: The CRM Domai Model 87 FigURe 3-4 Part of the full Domai Model, the Perso Domai. The Order Domai The CRM applicatio example is i charge of moitorig the order process for a specific Customer/Products combiatio. The order process is composed of three major etities: the order itself, the order's list of items, ad each item which is composed of a product, a quatity, a uit price, ad a total amout based o a applied discout. Goig i reverse, the first etity we ecouter is the Product etity, which represets a uique product i the compay s stock. The Product is the Domai Etity i charge of represetig a product ad its properties throughout the etire domai. Figure 3-5 represets the full domai for a order process.

109 88 Chapter 3 The Domai Model Figure 3-5 The Order Domai Model. I the diagram, you ca see the Order etity, exposed by a OrderLie, which idetifies the amout ad the total price for that Order. The Order has two Address refereces: oe for the BilligAddress ad oe for the ShipmetAddress. Each Order is subject to a approval process that ivolves the Order itself, a Employee, ad a Customer. A couple of iterestig lies of code ivolve calculatig the total amout of a OrderLie, as show i the followig: /// Calculates the total. private void CalculateTotal() if (Discout > 0) Total = Product.Price * Quatity * Discout; else Total = Product.Price * Quatity; As a costrait i the costructor of a OrderLie, we must already kow how to build a OrderLie before creatig oe. /// Iitializes a ew istace of the <see cref="orderlie"/> class. /// <param ame="order">the order.</param> /// <param ame="product">the product.</param> /// <param ame="quatity">the quatity.</param> /// <param ame="discout">the discout.</param> public OrderLie(Order order, Product product, it quatity, decimal discout)

110 Summary 89 this.product = product; this.quatity = quatity; this.discout = discout; this.order = order; CalculateTotal(); The etire trasactio is wrapped aroud the AddProduct method of a Order etity. /// Adds the product. /// <param ame="product">the product.</param> /// <param ame="quatity">the quatity.</param> /// <param ame="discout">the discout.</param> public void AddProduct(Product product, it quatity, decimal discout = 0) if (OrderLies == ull) OrderLies = ew List<OrderLie>(); OrderLies.Add(ew OrderLie(this, product, quatity, discout)); The complete project code available with this book icludes all the uit tests for the Domai, the factories for each Domai Etity ad all the validatio rules. To avoid pritig umerous pages of C# code, the book itself icludes oly the highlighted steps of the Domai Model creatio. Summary I this chapter, you created a basic Domai Model for a CRM applicatio. This is the Busiess Cotext (ot the busiess logic) for the applicatio that you ll complete i the followig chapters. You ca easily exted this Domai by usig a differet approach or by addig ew etities, such as those i the suggestios below: The Product should referece a Magazie or Stock that will keep the ivetory ad availability of the Product itself up to date. The Approval process used i the Order process should cotact the correspodig Customer ad Employee usig their default address every time the status of the Approval chages. For other improvemets, we will use a specific Busiess Layer i Chapter 5, The Busiess Layer, where you ll see how to implemet custom rules ad workflow for approvig, rejectig, ad completig a order.

111

112 Chapter 4 The Data Access Layer After completig this chapter, you will be able to: Idetify ad choose the proper Object/Relatioal Mapper. Create a flexible Data Access Layer. Create a mappig with Etity Framework ad with NHiberate. Itroductio The Data Access Layer (DAL) abstracts data access ad storage away from the rest of the applicatio, providig a Separatio of Cocers (SoC) that lets you separate the mechaics of data storage ad retrieval from the use of the data withi the applicatio. This meas that the applicatio ad data store ca evolve more easily or eve be swapped out completely. However, the two are ot completely decoupled; there is a cotract betwee them which is desiged so that the DAL provides access to the specific data (etities) that the applicatio eeds, regardless of how the uderlyig data is actually stored. The DAL allows you to write the applicatio i terms of etities, which ca be read ad updated through the DAL. The DAL also eforces ay busiess rules or busiess logic to esure data itegrity. Whether you are plaig to use a third-party library, a ope-source framework, a more complex Object/Relatioal Mapper (O/RM), or a i-house DAL, you should always try to keep its use ecapsulated i the DAL compoet itself. This meas that the DAL should expose atomic methods that are able to execute queries ad iteract with the iteral objects that compose the DAL without exposig these objects to the other layers. Aother problem you might face whe buildig a custom DAL is the mappig process. The DAL must provide a traslatio mechaism betwee the data model (the Domai Etities) that the applicatio will use ad the uderlyig data storage ad schema. You ca do this maually ad simultaeously gai some beefits i terms of performace ad customizability, or you could also employ a O/RM framework such as Microsoft Etity Framework or NHiberate ( just to metio two) to make the traslatio more flexible ad icrease the level of stadardizatio. The use of a DAL i a Model View ViewModel (MVVM) applicatio is ot a madatory requiremet because the two architectural patters are ot itercoected; the DAL describes a way of layerig the data access compoet while the MVVM describes a presetatio desig patter. Usually, you would also add a DAL to a MVVM applicatio to maitai a clea SoC ad to icrease the flexibility of the applicatio. Ideally, the Domai Etities should support the iterfaces ad features that make them ideal Model classes for use i a 91

113 92 Chapter 4 The Data Access Layer MVVM applicatio (such as INotifyPropertyChaged, IErrorIfo, ad so o) by breakig the cocept of POCO objects. I the same way, a well-desiged DAL allows the applicatio to retrieve the Model that it eeds for a particular scree ad supports updatig it. Usig a DAL i your applicatio isolates the UI ad the Domai from the database. The example MVVM applicatio will have a structure composed of the Domai (Chapter 3, The Domai Model ), the DAL (this chapter), the Busiess Layer (Chapter 5, The Busiess Layer ) ad the UI Layer (Chapter 6, The UI Layer with MVVM ). The Database ad Stored Procedures A Database Maagemet System (DBMS) is a set of computer programs that cotrols the creatio, maiteace, ad use of a database. I my opiio, the most dagerous thig you ca do i a database is create stored procedures (SPs). It s possible that may of you will ot agree with me o this poit. From a Domai-Drive Desig (DDD) perspective, here s why SPs are evil ot oly i a MVVM applicatio that uses a Data Layer, but also for more geeric Lie of Busiess (LOB) applicatios that have bee layered to icrease the testig surface ad decrease the effort ivolved i maiteace. The mai purpose of usig a Data Layer is to abstract the applicatio away from the data storage by makig the other layers uaware of the persistece mechaism used by the DAL. If the data storage uses SPs the this goal ca be achieved i fact, several O/RM implemetatios provide full support for SPs. O the other had, the mai purpose of havig a DAL is to avoid tight couplig betwee the C# code ad the database, apart from the cotract that you defie as part of the DAL. As log as the database fulfills this cotract, you do t eed to care at all about exactly what the uderlyig implemetatio is. You create a mockup of the DAL so that you ca test everythig o the upstream side of it. Similarly, you ca test aythig o the dowstream side of the DAL to esure that the database is fulfillig its cotract. Ideally, you would ot keep the applicatio busiess logic iside a SP, because a SP's role should focus more o maitaiig data itegrity withi the database. However, i practice, creatig solid busiess logic ad data itegrity ca be cosidered as two sides of the same coi. Testig the busiess logic stored iside a SP is a complex task, as are maitaiig a database ad securig a database. These cocepts are well uderstood by database admiistrators, ad of course may orgaizatios might ot tolerate the costs of buildig ad maitaiig a database where all applicatios have to play by the rules to esure data itegrity ad security, because that would t be practical.

114 Choosig a O/RM 93 To help clarify why you should avoid the use of SPs ad itroduce a flexible DAL-O/RM combiatio i your applicatios, I ve icluded few commo argumets that I use with database admiistrators: Maiteace SPs are ot easy to maitai. Whe you chage a SP, you ofte eed to chage its sigature to iclude a ew parameter. As a result of that chage, every piece of code that uses that SP is ivalid but the DBMS does t offer a way to fid the depedecies betwee a SP ad the C# code that uses it. Security I Microsoft SQL Server, you ca defie ad grat graular access to a sigle field of a sigle row of a table, ad that s pretty safe, but with a DAL applicatio you ca simply apply security through a Security Layer without worryig about autheticatio ad authorizatio o the database side. Performace Most moder O/RMs ca geerate executio plas ad optimize the Dyamic SQL created by the DAL, which effectively eds the fatasy story that SPs are more efficiet i terms of performace tha dyamic SQL statemets. If you are still motivated to use SPs i your applicatios, you are of course free to do so. You should also cosider that O/RMs such as NHiberate ad Etity Framework are able to replace their auto-geerated T-SQL code usig some predesiged SPs that you might eed to use if you have a legacy database. Choosig a O/RM A O/RM (also kow as a Object-Relatioal Mapper) is a framework i charge of covertig data betwee two disparate systems. Oe of these systems is usually a Object Model ad the secod oe is a database object, such as a table or a view. As you saw i Chapter 3, there are differet ways to develop a applicatio Domai. Based o whether you use a Active Record patter or DDD, your O/RM will be cofigured differetly. The O/RM cocept is a easy-to-uderstad but difficult-to-accomplish mechaism for persistece. It stores the istructios to map a Domai Object agaist oe or more database objects i a mappig dictioary. Usig this dictioary, the O/RM geerates the ecessary code to retrieve ad store data from the database to the Domai Model ad vice versa, o the fly. It usually also geerates a ghost class of your Domai Model kow as a proxy, which is a override of the Domai Model class specifically for the persistece aspect. More tha that, may O/RMs offer the ability to cache data, write trasactios agaist the data store, ad might eve provide a object-orieted programmig query laguage that is fully itegrated with the Domai Ubiquitous Laguage, traslated o demad to a Domai- Specific Laguage (DSL) uderstadable by the data store. Some O/RMs also offer the ability

115 94 Chapter 4 The Data Access Layer to switch betwee differet databases, such as from SQL Server to Oracle, or from MySQL to IBM DB2. The followig list shows why it s so importat to use a O/RM i a MVVM applicatio: Isolatio You ca completely isolate the Domai from the data store. This is a pricipal rule of a DDD applicatio, ad of course, for ay LOB MVVM applicatio. Simplificatio O/RMs elimiate the eed to write code to create, modify, ad query database objects. Improved Maitaiability With a O/RM, you eed to chage oly the Domai Model; the data store will be adapted automatically if you pla to use the O/RM to drive the maiteace of your database schema. Domai Navigatio It s ot easy to uderstad how a database flow works just by readig the available table schema, but it s usually quite easy to read a UML diagram of a Domai Model to uderstad how the applicatio has bee desiged. If you use a O/RM, the Domai will be your oly blueprit. Of course, i this case you ca achieve the same goal usig a custom DAL; it is importat that behid that there is a Domai Model. Features My motto is, why re-ivet the wheel? O/RMs offer features such as cachig, trasactioal capabilities, cocurrecy checkig, ad so forth. That s probably eough. O/RMs are cool ad shiy but ot all that glitters is gold. For example, a O/RM geerates dyamic SQL as eeded, so it probably is t a good fit with some specific architectural desigs. Here are two more cosideratios: Learig Curve Degrades It s bee my experiece that there s a problem with the learig curve, especially with a O/RM or a techology such as XAML. If you do t kow how to use these properly, you ca easily ed up usig them the wrog way, resultig i the worst outcome from usig the products. Large Bulk Operatios While most moder O/RMs are able to execute bulk operatios, they do t always choose the best possible method to do them. For example, trucatig a table is far more efficiet tha clearig a IList<Employee>, which, whe executed by a O/RM, is ofte traslated to a set of DELETE commads. There are several types of O/RMs o the market that rage from reliable, to semi-reliable, to oly for ewbies. I the ext sectios, I will show the most reliable O/RMs ad based purely o my experiece whe you should use oe istead of aother.

116 Microsoft Etity Framework Choosig a O/RM 95 Microsoft itroduced the Etity Framework quite some time ago. At the time of this writig, Etity Framework is at versio 4 ad is delivered with Microsoft.NET Framework 4.0. The latest versio of this O/RM covers all the requiremets of a stadard O/RM, icludig lazy loadig, persistece igorace, a UI desiger, ad a query traslator that allows developers to use the well-kow LINQ sytax. You ca coect the Etity Framework to various databases, icludig SQL Server, Oracle, DB2, ad more. This capability, plus the availability of a graphical tool to desig the mappig, makes the Etity Framework a easy O/RM to lear ad use. However, it s probably still less powerful tha other O/RMs available o the market. Etity Framework is composed of a layer that capitalizes o existig Microsoft ADO.NET techology, which makes learig Etity Framework sytax ad usage easy for Microsoft developers who already have a ADO.NET backgroud. Figure 4-1 displays the basic structure of Etity Framework 4. Etity Framework EDM Domai Sytax ADO.NET Providers LINQ Datastore SQL Figure 4-1 The Microsoft Etity Framework layered structure. To create a ew Data Model usig Etity Framework 4, you eed to uderstad what the available models are ad why you should create oe type rather tha aother. The Etity Framework show i Figure 4-2 curretly allows you to create three differet models: ADO.NET Etity Data Model Usig this model, the Etity Framework will create a ew empty Domai Model. You have the optio of creatig the iitial model from a existig database (the database-first approach) or creatig a empty Domai Model that you will later map to a database. ADO.NET Etity Object Geerator Usig this optio, you ca create a strogly-typed Object Cotext ad persistece-aware classes startig from a existig Etity Framework domai by usig the Text Templatig (TT) feature of Microsoft Visual Studio 2010.

117 96 Chapter 4 The Data Access Layer Note I Visual Studio, a text template is a mixture of text blocks ad cotrol logic that ca geerate a text file. The cotrol logic is writte as fragmets of program code i Microsoft Visual C# or Microsoft Visual Basic. The geerated file ca be text of ay kid, such as a webpage, or a resource file, or program source code i ay laguage. Text templates ca be used at rutime to produce part of the output of a applicatio. They ca also be used for code geeratio, i which the templates help build part of the source code of a applicatio. ADO.NET Self-Trackig Etity You use this optio to geerate etity types that have the ability to record chages o scalar ad complex property values, ad o referece ad collectio avigatio properties, idepedet of the Etity Framework. Figure 4-2 Available optios for Etity Framework withi Microsoft Visual Studio Right ow, Etity Framework versio 4 is still lackig i its implemetatio of the POCO cocept. I fact, if you have a existig Domai Model such as the oe created i Chapter 3, the oly solutio is to create a maual mappig for each etity, bypassig the power of the itegrated Etity Framework desiger. Alteratively, you would eed to use the Etity Framework desiger to create a proxy etity for each Domai Etity. Here are the pros ad cos of usig Etity Framework for your data mappig: Pros Etity Framework is easy to lear, easy to use, ad has rich wizard ad UI desigers that allow you to create a model from a existig database with just a few clicks. It is fully itegrated with the.net LINQ query laguage.

118 Choosig a O/RM 97 It s a Microsoft product that will beefit from cotiued updates ad ehacemets, ad it is probably the most reliable i terms of lifecycle. Etity Framework is perfect for a database-first approach because it has a powerful T4 code geerator that ca geerate a full Domai Model startig from a existig database. Cos Etity Framework forces you to use LINQ to Etities, a extesio of LINQ desiged for Etity Framework with a somewhat differet sytax tha the origial LINQ provider. It lacks the flexible support for lazy load ad POCO cocepts that are preset i other O/RMs. The SQL it geerates is still ot perfect, ad i some situatios, the performace is uacceptable. With Etity Framework, you ca write mappig files two ways. Oe way is to decorate your POCO objects usig Etity Framework attributes, specifyig the SQL data type, the field ame i the data store, ad the validatio rules for each property. Here s a example of this approach: public class Book [Key] public strig ISBN get; set; [StrigLegth(256)] public strig Title get; set; public strig AuthorSSN get; set; [RelatedTo(RelatedProperty="Books", Key="AuthorSSN", RelatedKey="SSN")] public Perso Author get; set; The secod way is to use three available XML files to specify the database mappigs, the etity mappigs, ad the relatioship mappigs, as demostrated here: <Associatio Name="CustomerOrders"> <Ed Type="ExampleModel.Customer" Role="Customer" Multiplicity="1" /> <Ed Type="ExampleModel.Order" Role="Order" Multiplicity="*"> <ODelete Actio="Cascade" /> </Ed> <ReferetialCostrait> <Pricipal Role="Customer"> <PropertyRef Name="Id" /> </Pricipal> <Depedet Role="Order"> <PropertyRef Name="CustomerId" /> </Depedet> </ReferetialCostrait> </Associatio>

119 98 Chapter 4 The Data Access Layer NHiberate Started i 2005, NHiberate is a ope-source O/RM for.net that is derived from the successful ope-source O/RM for Java called Hiberate. It is ow oe of the most popular ad most-used O/RMs i the ope-source commuity; it has well-established commuity support ad umerous plug-i ad code geerators. The cocept behid NHiberate is pretty simple: you create your POCO-compliat Domai Model, ad the you decide how to map it agaist a database. You ca use a existig database (the database-first approach) or create a ew oe (the domai-first approach). NHiberate has all the characteristics of a professioal O/RM, such as persistece igorace, lazy load ad fetch strategies, a complex query laguage, full support for LINQ, ad may more features. You ca see a overview of this product at the official NHiberate commuity. Figure 4-3 shows the structure of NHiberate versio 3 (the latest versio as of this writig). At the top of the diagram sits the Domai Model, which is totally uaware of the O/RM; the the mappig, which ca be accomplished usig a separate assembly composed of either XML files or C# classes; ad fially, the core NHiberate egie, which traslates the mappig files ito proxies that are able to speak with the targeted data store. NHiberate hadles this architecture usig the sessio object, which is a cotextual object that holds the status of the Domai Model objects ad tracks their chages so that developers ca determie whether a etity is ew or already exists, ad whether it has bee modified. All these steps are clear ad ca be executed usig a trasactio (Database Trasactio) patter. MODEL SESSION TRANS. ADO.NET ODBC OLEDB Datastore Figure 4-3 The NHiberate architecture Pros NHiberate is extremely powerful ad flexible. You ca execute SQL calls directly from the O/RM sessio, access the OLEDB/ODBC coectio object, maage trasactios, ad cofigure stored procedures ad views.

120 Choosig a O/RM 99 NHiberate is a ope-source product with a very large commuity. It thus beefits from extesive documetatio, such as easy-to-fid e-books, blogs, code samples, ad sample projects o the Iteret. You ca fid a umber of free plug-is for NHiberate that assist i tasks from cofigurig your domai mappig, to writig LINQ queries, to usig a GUI desiger iside Visual Studio. Agai, NHiberate is a ope-source project, which makes it highly customizable ad cofigurable. You ca obtai the latest build ad cofigure it ad eve chage the core code if you wat or eed to. Beyod that, NHiberate has a very powerful tracig egie; you ca moitor the dyamic SQL ad the mappigs it creates. Cos It s a ope-source product ad yes I realize that I ve just bee expoudig the virtues of a ope-source project. But the flip side to ope-source applicatios is that they ca be a big risk, because there s o guarateed support or ay warraty that the product will be available as log as you eed it. It has a steep learig curve. At the begiig, NHiberate is ot a easy solutio. The cofiguratio is extremely complex (especially if you choose the XML method), ad the core egie has thousads of optios ad methods that ca give you poor performace if used icorrectly. It works better with the custom SQL geerated by the egie. It is ot iteded to be used with customized SQL statemets or for bulk operatios. The code example that follows shows the classic mappig used by NHiberate ad by its Java paret Hiberate. Specifically, the example shows a XML file with a.hbm.xml extesio. Everythig is defied usig a specific XML format, based o three mai.xsd files that you ca easily import ito Visual Studio after which, Visual Studio will provide custom ItelliSese. <?xml versio="1.0" ecodig="utf-8"?> <hiberate-mappig xmls="ur:hiberate-mappig-2.2" amespace="quickstart" assembly="quickstart"> <class ame="cat" table="cat"> <id ame="id"> <geerator class="idetity" /> </id> <property ame="name"> <colum ame="name" legth="16" ot-ull="true" /> </property> <property ame="sex" /> <may-to-oe ame="mate" />

121 100 Chapter 4 The Data Access Layer <bag ame="kittes"> <key colum="mother_id" /> <oe-to-may class="cat" /> </bag> </class> </hiberate-mappig> FluetNHiberate is aother tool you might wat to cosider that lets you write mappig files usig C#. FluetNHiberate is a ope-source plug-i, available at org. I the ext sectio, you ll see a couple of examples that demostrate how it works. The team at NHiberate has just released a major ew versio of NHiberate, 3.0, which will be available i RTM form at the begiig of I this versio, the team has added full support for LINQ sytax plus a iteral C# fluet mappig called coform. No preview of this plug-i is available yet, but the code should look somethig like the followig example: var orm = ew ObjectRelatioalMapper(); orm.tableperclass<aimal>(); orm.tableperclass<user>(); orm.tableperclass<stateprovice>(); orm.tableperclasshierarchy<zoo>(); orm.maytomay<huma, Huma>(); orm.oetooe<user, Huma>(); orm.poidstrategies.add(ew NativePoidPatter()); Other O/RMs for.net Etity Framework ad NHiberate are probably the most commoly used O/RMs i the.net world possibly because both are free. Etity Framework ships with the.net Framework ad NHiberate is ope source. If you are lookig for a code geerator tool that also acts as a O/RM, you might wat to cosider a third-party O/RM. Most of these are ot free. The followig table attempts to summarize the pros ad cos of two of these products: Name URL Pros Cos Subsoic Active Record Auto-geerate code Geome Flexible Auto-geerate code Ope Source, Not flexible Expesive, Sparse documetatio

122 The Uit of Work The Uit of Work 101 If you pla to write your DAL usig a O/RM, you wo t eed to put a lot of effort ito writig custom SQL code ad custom trasactioal code to save or retrieve etities. O the other had, you do eed a solid orchestrator which will be i charge of etity status. For example, you eed to kow whether a etity is ew, or whether a requested etity is already i memory or eeds to be retrieved from the data store. Marti Fowler itroduced the cocept of the Uit of Work (UoW) (see Chapter 2, Desig Patters ). The UoW is i charge of maitaiig a list of objects affected by a busiess trasactio ad coordiatig writig out chages ad resolvig cocurrecy problems. Each of the O/RMs discussed i the previous sectio have a UoW cocept at their core. NHiberate uses the Sessio ad ITrasactio objects, Etity Framework uses the ObjectCotext class, ad basic LiQToSQL uses the DataCotext. These are implemeted ad work differetly, but their mai goals are the same. The followig code displays the basic cocept of a UoW: Public IUitOfWork<T> void MarkDirty<T> (T etity); void MarkNew<T> (T etity); void MarkDeleted<T> (T etity); void Commit(); void Rollback(); The mai cocept here is that the UoW takes care of etity status. The oly thig you eed to remember to do is to mark a etity with the specific status ad the Commit or Rollback the busiess trasactio. The ext pseudo-code example shows how this works over a complete trasactio usig the UoW patter: var uitofwork = Cotaier.Resolve<IUitOfWork>(); //IoC to retrieve the IUitOfWork var customer = Factory.CreateCustomer(); var order = Factory.CreateOrder(); customer.orders.add(order); try uitofwork.marknew(customer); //mark the ew etity uitofwork.commit(); //commit the chages to the database catch(exceptio ex) uitofwork.rollback(); //rollback if a error occurs If you keep this patter i the DAL, you do t eed to implemet a custom DAL for each O/RM that you pla to use. For example, you might have a applicatio composed of two DALs: oe is the Etity Framework, ad the other is a more complex DAL that uses NHiberate. I this case, you might oly eed to implemet the IUitOfWork iterface i two differet ways, usig the most appropriate oe for each DAL, without havig to chage the code of the UitOfWork itself.

123 102 Chapter 4 The Data Access Layer I ve see the UitOfWork over egieered i may projects. For example, I ve see a UitOfWork implemetatio that was able to retrieve data, execute SQL statemets, ad more. At that poit, of course, it is t really the UitOfWork patter ay loger; it s the Repository patter (you ll explore more about this i the ext sectios). Remember that the oly purpose of the UitOfWork is to keep the state of a set of busiess objects for a related busiess trasactio. Lifecycle of a UoW Aother importat poit is the lifecycle of your UoW. The lifecycle depeds o the type of applicatio that you are writig. For example, a busiess trasactio that ivolves a Widows Presetatio Foudatio (WPF) cliet applicatio might be very differet tha a busiess trasactio that happes i a more web-orieted Silverlight applicatio. I the classic MVVM patter, I usually like to associate the lifecycle of a UitOfWork to the correspodig View/ViewModel associatio. That way, everythig that happes i the ViewModel is covered by a UoW trasactio. If I eed to work o a web applicatio, I try to get help from the HttpCotext object, ad store the UoW withi it. But remember, everythig depeds o the type of applicatio that you are writig; the lifecycle of the UoW is cotext sesitive. The Oracle guide for Database Trasactios ( web.1012/b15901/xactios002.htm#i ) defies the UoW as a busiess cotext that opes a trasactio as soo as the busiess activity begis ad cotrols this activity by committig or rollig back that trasactio. It s up to you to determie whe the busiess activity is complete ad whe you eed to commit ay chages. Idetify a Busiess Trasactio I a MVVM applicatio, the busiess trasactio is usually strictly related to the View/ ViewModel couplig, but some cases might ot satisfy this requiremet. For example, you might have a mai View that displays all the available customers. At the same time, you might have a Commad that allows users to add, modify, or remove a customer from that list. Because may views iclude subviews, there is usually a hierarchy of view models, as well; the associatio betwee a trasactio is usually at the scree level, which i this case might be composed of more tha oe child View/ViewModel couplig. Figure 4-4 displays a practical example i WPF.

124 The Uit of Work 103 Figure 4-4 A sample WPF MVVM Master Detail s applicatio. You ca see that there are two types of busiess trasactios here. The first oe occurs as soo as the mai view loads. At that poit, you call the UoW ad retrieve all the available data from the data store. You the display this data i the View usig your ViewModel. This trasactio is completed as soo as the data is displayed i the View. The secod trasactio might happe ay time you add, modify, or delete a customer. This trasactio is pretty simple but challegig at the same time. For example, clickig the Add Customer commad creates a ew View/ViewModel with a associated UoW that might or might ot be committed, depedig o a specific busiess logic. I the followig example, the persistece is committed i the commad call. Clickig the Save commad adds a ew customer to the curret sessio of the UoW. At that poit, you should commit the trasactio ad refresh the mai ViewModel. Is this a uique trasactio or is it a set of trasactios? Well, i busiess trasactio terms, this is just oe trasactio that icludes the followig steps: Usig (var uow = Cotaier.Resolve<IUitOfWork>()) try uow.begitrasactio(); var customer = CustomerViewModel.GetModel(); uow.saveorupdate(customer); MaiViewModel.Refresh(); uow.commit(); catch(exceptio ex) uow.rollback(); MaiViewModel.Refresh();

125 104 Chapter 4 The Data Access Layer The previous pseudo-code starts by gettig a Customer etity from the CustomerViewModel, ad the it tries to add or update this etity. Next, it refreshes the MaiViewModel. If somethig goes wrog, the code rolls back the etire trasactio ad refreshes the MaiViewModel which should ot display the ew customer because the trasactio failed. I coclusio, the busiess trasactio hadled i a UoW should ot be cosidered the same as a simple database trasactio; istead, cosider it as a set of operatios that will accomplish oe or more busiess steps. NHiberate s ITrasactio object, for example, ca hadle multiple SQL calls, executig them oly whe you call the Commit commad. At the same time, based o your cofiguratio, it will update the curret sessio, ad of course, the list of available customers to match the chages made through the UI. The Repository Patter I the previous sectio, you saw the core of a DAL, the UoW. Ufortuately, with the basic UoW patter, you ca oly add, remove, or update a etity ad execute a busiess trasactio, but to have a complete DAL, you eed more tha that. You eed to be able to retrieve a set of etities, to lazy-load related child ad paret etities, ad to be able to query ad page results without affectig database performace. For these ad other busiess requiremets of the DAL, you eed to use the Repository patter. Marti Fowler first itroduced the cocept of the Repository patter i his book, Patters of Eterprise Applicatio Architecture (see Chapter 2). A repository should act as a i-memory collectio of etities, ad it should facilitate the query ad retrieval processes for these etities without affectig database performace. A basic repository should support addig ad removig etities, ad updatig existig etities. It should also provide a easy way to retrieve ad query them. The followig pseudocode displays a commo Repository patter: iterface ICustomerRepository void AddCustomer(Customer customer); void RemoveCustomer(Customer customer); void UpdateCustomer(Customer customer); IQueryable<Customer> GetCustomers(); Customer GetCustomer(object primarykey); Usig the followig cotract, you ca implemet a cocrete CustomerRepository that will be able to execute ay type of Create, Read, Update, or Delete (CRUD) operatio agaist the data store usig the UoW. Of course, each of these operatios might be icluded i

126 The Repository Patter 105 oe or more busiess trasactios. I particular, ote the GetCustomers method, which, as you might have oticed, does t retur a real collectio at all; it returs a IQueryable<T> collectio. That s because IQueryable is the oly collectio type that is able to execute a call to the database whe you access oly oe of the items of the collectio. That meas you ca apply additioal LINQ filters to the collectio before the fial call to the database executes. For example, if you write the followig code, ad the O/RM is Etity Framework or NHiberate: var repository = Cotaier.Resolve<ICustomerRepository>(); var customers = repository.getcustomers().where(x => x.compay == "Microsoft).OrderBy(x => x.firstname); // call to the Db customers.tolist(); the fial T-SQL geerated from our O/RM, if well cofigured, will be somethig like this: SELECT * FROM TBL_CUSTOMER C WHERE C.COMPANY = Microsoft ORDER BY C.FIRSTNAME You ca see the IQueryable<T> collectio type aalyzed i more detail at microsoft.com/e-us/library/system.liq.iqueryable.aspx. IQueryable<T> is part of the System. Liq amespace, ad ot a part of the System.Collectios amespace like other collectios available i.net. Of course, to use it properly, you must be sure that your O/RM has full support for LINQ or oe of its providers. To keep this cocept geeral, you might cosider usig.net geerics ad creatig a more geeric Repository patter cotract, such as the followig: Iterface IRepository<T> void Add(T etity); void Remove(T etity); void Update(T etity); T Get(object primarykey); IQueryable<T> GetEtities(); This code creates a more geeric cotract that we ca recycle throughout our applicatios, ad that i cojuctio with a geeric UoW makes a very flexible ad reusable DAL. Later i this chapter, you ll build simple UoW ad IRepository classes usig geerics ad see how easy it is to plug these two powerful patters ito the same MVVM project by usig two differet O/RMs.

127 106 Chapter 4 The Data Access Layer A sample implemetatio of a geeric Repository should look like this: public GeericRepository<T> : IRepository<T> private IUitOfWork uow; public GeericRepository() this.uow = Cotaier.Resolve<uow>(); public void Add<T> (T etity) try uow.begitrasactio(); uow.add(etity); uow.commit(); catch (Exceptio ex) uow.rollback(); Test-Drive Developmet: The Data Layer I Chapter 2, I stressed how importat Test-Drive Developmet (TDD) is ad why you eed to itroduce it at the begiig of the developmet process. Of course, the Data Layer also eeds to be tested. To test the Data Layer, you should follow two differet directios, depedig o the compositio of the DAL. The first step is to test the mappig agaist the O/RM; you eed to be sure that the etity is mapped properly i the O/RM, ad that each field is mapped to the appropriate field i the database. For example, you do t wat the FirstName property of the Customer etity mapped to the LastName field of the Customer s table. To test the mappig, depedig o the O/RM you are usig, you should follow a few simple steps. First, you wat to esure that whe you create ad save a ew etity, for example, a Customer etity, that the values are persisted properly i the database. To accomplish this test, you simply eed to create a ew etity, save it, retrieve it, ad the check it agaist a static value. public void CaSaveFirstName() var firstname = "Joh"; var customer = Factory.Create<Customer>(); customer.firstname = firstname; GeericRepository<Customer>.Add(customer); var expected = GeericRepository<Customer>.Get(customer.PrimaryKey); Assert.AreEquals(expected.FirstName, firstname);

128 Test-Drive Developmet: The Data Layer 107 Such operatios ca be time-cosumig, but are ecessary whe you eed to be 100% sure that the mappig has bee doe properly ad that o property is missig. If you are usig Etity Framework, you might ot eed to execute this set of steps, because the UI desiger makes it easy to see whe the mappig has bee doe properly, especially if you geerate your domai startig from a existig database. If you re plaig to build a domai-first applicatio, ad you re writig the mappig for your POCO objects maually, you must guaratee the mappig validity by usig the TDD approach, which ca be very expesive i terms of time ad resources. You should also remember that the data store used for the TDD should ot be the same oe you use for the fial applicatio, or you will ed up with a set of fake records i the productio data store. The secod type of tests should be executed oly whe you are ot auto-mappig your model ad if you are specifyig differet ames for the data store fields tha the ames used for the etity fields. I my compay, for example, we work with very private iformatio, so we ca t use actual ames i the database fields, because that would be a potetial security breach. To accomplish this, we write tables ad fields usig umeric mappigs, as show i the followig table: Table Field Descriptio Tbl _1 Id Tbl _2 FirstName This type of amig ca be difficult to decode ad is also proe to error. For this reaso whe I create a mappig class or XML for a specific etity, I eed to be sure that the mappig is doe properly ad the oly way to do that is to execute a SELECT agaist the data store ad the check that the mapped field o my etity is the same as o the data store. If you re plaig to work with NHiberate, you might cosider usig a very hady tool for writig the mappig i C#, called FluetNHiberate (available at This tool makes extesive use of lambda expressios to create your mappig files. It s also a very useful TDD compoet that you ca use to verify correct mappig ad that the mappig works o the data store.

129 108 Chapter 4 The Data Access Layer The followig example shows how FluetNHiberate lets you write fluet mappig files: public class CatMap : ClassMap<Cat> public CatMap() Id(x => x.id); Map(x => x.name).legth(16).not.nullable(); Map(x => x.sex); Refereces(x => x.mate); HasMay(x => x.kittes); The ext code example shows you how to test your mappig agaist a data store usig the FluetNHiberate compoet. The code creates a ew Employee etity, persists it to the database, ad the verifies that the etity has bee persisted properly. [Test] public void CaCorrectlyMapEmployee() ew PersisteceSpecificatio<Employee>(sessio).CheckProperty(c => c.id, 1).CheckProperty(c => c.firstname, "Joh").CheckProperty(c => c.lastname, "Doe").VerifyTheMappigs(); Oe fial cosideratio: remember that the domai mappig for a ormal MVVM applicatio happes just oce durig the etire lifecycle of the applicatio. Of course, you will eed to chage ad modify the Domai ad the data store durig the applicatio s lifetime, but the mai schema should ot chage. A good TDD layer for the DAL will guaratee that every chage you make to the Domai will be properly reflected to the correspodig data store. Buildig a Distributed Data Layer with RIA ad WCF What you ve see so far is fie if your DAL is writte i C# or Visual Basic.NET, ad if it s used by a ormal.net applicatio that uses the commo CLR, such as a WPF Cliet applicatio. This meas that you ca write your custom ad geeric DAL oce ad reuse it repeatedly for your WPF applicatio, for your ASP.NET applicatio, or for a simple Widows Service applicatio. If you are usig a three-tier approach, the cocept becomes more complex. This is because you will eed to add a additioal abstractio usig a Widows Commuicatio Foudatio (WCF) or a web service techology that will provide the atomic methods to call the DAL stored at the applicatio server level.

130 Buildig a Distributed Data Layer with RIA ad WCF 109 Ufortuately, as soo as you jump ito a Silverlight applicatio, the process fails, because Silverlight rus uder a smaller ad less powerful versio of the CLR desiged solely for Silverlight, which is ot (curretly) able to ru DLLs compiled for the Commo CLR. Fortuately, the solutio is ot to re-compile all your layers to satisfy Silverlight s requiremets; otherwise, every time you chage somethig i the Domai or i the DAL you would also eed to recompile everythig just for your Silverlight applicatio. Microsoft itroduced the WCF RIA Service for Silverlight. The cocept carried by this service is simple but very potet. WCF is a powerful techology that allows you to commuicate betwee layers usig the Simple Object Access Protocol (SOAP) protocol (like a web service) ad to share data ad data structures betwee a Domai ad layers by usig XML. You ca capitalize o WCF RIA Services to share your DAL ad your Domai compiled for the Commo CLR with a Silverlight applicatio (see Figure 4-5), without the eed to recompile everythig for each chage. WCF RIA Services Class Lib.NET Class Lib1 DomaiService1 Shared code1 WCF RIA Services App Web App WCF RIA Services Class Lib.NET Class Lib2 DomaiService2 Shared code2 RIA Lik SL Class Lib1 DomaiCotext1 Shared code1 Silverlight App1 Silverlight App2 RIA Lik SL Class Lib2 DomaiCotext2 Shared code2 Figure 4-5 The core structure of WCF RIA Services. I Figure 4-5, you ca see that there are two distict boudaries, oe of which is the Silverlight applicatio itself alog with a cloe of the applicatio logic, shared by a web service, ad a secod boudary composed of the Data Layer ad the database, also shared usig the WCF Service. I this case, there are at least two differet tiers: oe is the MVVM Silverlight applicatio, ad oe is the data tier, composed of the data store ad the Data Layer.

131 110 Chapter 4 The Data Access Layer Figure 4-6 How to create a Silverlight Applicatio that icludes WCF RIA Services. You ca use WCF RIA Services i your WPF applicatios if you wat, but they were origially desiged to satisfy the problem of Silverlight geeratig code oly for the Silverlight CLR. To create a WCF RIA Applicatio, you eed a base Silverlight Cliet applicatio. This applicatio will have a Silverlight project ad a ASP.NET or ASP.NET MVC website that hosts the compiled Silverlight applicatio. After creatig the base Silverlight Cliet, you eed to add a ew WCF RIA Service to the web applicatio, as show i Figure 4-6. At this poit, you are able to share the DAL, Domai, ad aythig else you eed from your Commo CLR to the Silverlight applicatio. Figure 4-7 summarizes these steps, ad shows you how simple it is to use ad how simple it is to share a Domai across a Silverlight applicatio. Note To be precise, you d usually use this wizard whe creatig a Domai Model based exactly o the database schema of the table you choose, which is ot typical of what you would do i a real LOB applicatio.

132 Buildig a Distributed Data Layer with RIA ad WCF 111 Figure 4-7 Two easy steps to add a existig Domai to a WCF RIA Service. Havig added the refereces to the Silverlight applicatio, you are ready to query your Domai usig your existig DAL from the Silverlight code. Because RIA Services has full support for XAML code, this is a very good combiatio for the MVVM patter, as well. The followig code loads some data ito the ViewModel ad bids it to a grid i a Silverlight View: public class GridViewModel : ViewModel private CustomerDomaiCotext customercotext = ew CustomerDomaiCotext(); public LoadOperatio<Customer> VMDataSource; public GridViewModel() IitializeView(); VMDataSource = this. customercotext.load( this.customercotext.getcustomersbylastnameletterquery(lettervalue.text), CustomerLoadedCallback, ull); //XAML <Page.Resources> <vm:gridviewmodel /> </Page.Resources> <mygrid:datagrid DataSource="Bidig Path=VMDataSource"... Note WCF RIA Services work well with O/RM, Etity Framework, ad NHiberate. This listig itroduced a CustomerDomaiCotext a custom class that iherits from the DomaiCotext class ad is created by the WCF RIA Services Wizard. A domai cotext class is geerated i the cliet project for every domai service i the server project. You call methods o the domai cotext class that correspod to the domai service method that you wat to use.

133 112 Chapter 4 The Data Access Layer If you wat to keep a eye o WCF RIA Services, Microsoft has a official website for this techology ( where you ca fid a lot of useful code, samples, ad tutorials. If you have a existig DAL ad you are plaig to build your ext LOB applicatio usig Silverlight, you should defiitely cosider usig WCF RIA Services to save time ad work. Of course, if you pla to use this approach, you will eed to cosider additioal issues that accompay the SOA approach, such as records cocurrecy, data latecy, ad bottleecks across the etwork. Sample Code: The CRM Data Access Layer I the Sample Code sectio of Chapter 3, we created the Domai Model for the CRM example applicatio, which is composed of two mai groups of etities: the Perso etity ad the Order etity. I this chapter, we ll map that Domai to a database usig two differet O/RMs: Etity Framework ad NHiberate. A Flexible IUitOfWork Iterface Before creatig the domai mappig, you eed to create the basic IUitOfWork iterface, which will be used throughout the layers of the MVVM applicatio. The class diagram i Figure 4-8 illustrates a IUitOfWork iterface that is very close to the UoW explaied earlier i this chapter. The UoW will expose the three pricipal commads to chage the status of a etity (Create, Update, Delete) as well as fuctios to execute these commads i a trasactio cotext. The UoW will be specific to each O/RM because Etity Framework uses the ObjectCotext, while NHiberate uses the ISessio iterface. For this reaso, the IUitOfWork will ot expose the real DataCotext, oly the basic commads eeded to execute the SQL statemets. The applicatio uses the ISessioFactory iterface for the same reaso; depedig o the O/RM i use, we will create a specific cocrete UitOfWork that will have a O/RM-specific DataCotext. Fially, you ll eed a geeric Repository that will perform the CRUD operatios i a trasactioal cotext. The Repository will expose the curret IUitOfWork so that we will be able to execute specific commads as well as the predefied CRUD operatios available through the Repository.

134 Sample Code: The CRM Data Access Layer 113 Figure 4-8 The CRM.Dal abstract layer: the basic layer for ay DAL. You also eed to create two additioal layers: oe for Etity Framework, ad oe for NHiberate. As metioed earlier, this step is required because you ca choose which O/RM you wat to use, but you ca t apply the same cocrete UitOfWork to two differet O/RMs, because they maage etity persistece ad the data cotext i differet ways. The fial result should look like the diagram i Figure 4-9. Remember that all the code metioed i this book is available i the CRM example applicatio icluded i the dowloadable compaio cotet for this book. Figure 4-9 The CRM Domai with the complete Data Layer. Figure 4-9 shows that the Domai is totally uaware of the persistece techique i use. At the same time, the abstract Data Layer that you will use i your MVVM applicatio does t kow about the cocrete implemetatio. Mappig the Domai Model Usig Etity Framework Usig Etity Framework, you ca develop a Domai usig two differet DDD approaches: domai-first or database-first. As discussed i Chapter 3, you should avoid the database-first approach uless you are restricted to a specific legacy database. Because the CRM applicatio is ew, we will ot be boud to a specific database schema, so we will use the domaifirst approach here.

135 114 Chapter 4 The Data Access Layer Before.NET Framework 4.0, you were ot able to create a complete POCO Domai ad plug it ito a ew Etity Framework model, but with versio 4, you ca ow accomplish this task without the eed to rewrite everythig. Ufortuately, Etity Framework requires a set of proxy classes that act as mappers for the POCO Domai Etities. Therefore, you eed to implemet the same model you have i the Domai i the Etity Framework desiger. This madatory requiremet causes a major problem; Etity Framework eeds to kow how to perform lazy loadig ad how to persist a POCO etity. Because the etity is POCO, the oly way to do that is to create a proxy that overrides the POCO etity with the specific cofiguratio for the database. To start, create a ew project ad ame it CRM.Dal.EF. This will be a cocrete implemetatio of the Data Layer for Etity Framework. Next, add these three refereces: CRM.DAL (our base data layer), System.Data.Etity (Etity Framework) ad System.CompoetModel. Compositio (MEF for the Plug-I desig). Now, add a ew empty.edmx file (ADO.NET Etity Model). You eed to create the same etities that exist i your basic domai. This step is pretty frustratig ad overly time-cosumig, but to keep your domai POCO uaware of the Etity Framework, this is the oly solutio available right ow. The fial result should be similar to Figure POCO DOMAIN IN CRM.DOMAIN ENTITY FRAMEWORK MAPPING DOMAIN IN CRM.DAL.EF Figure 4-10 Class diagrams compariso: POCO Domai versus Etity Framework Domai. I have foud some custom tools at that might help you to geerate your custom Etity Framework mappig diagram from a existig POCO Domai. Of course, the best fit for this type of approach is to geerate your Etity Framework Model from a existig database ad the build proxies for your Domai Model. I this chapter, you saw the pros ad cos of this O/RM. You should ot use Etity Framework if you pla to keep a Domai Model totally POCO because the curret release (CTP 4) still lacks a mappig process betwee Etity Framework proxies ad POCO Domai Etities.

136 Creatig a Cocrete DAL for Etity Framework Sample Code: The CRM Data Access Layer 115 The ext step is to create a proxy ObjectCotext that will be able to persist the POCO etities. The followig code maps each Etity Framework proxy etity to its correspodig CRM. Domai etity. To do this you must add a referece to the CRM.DAL.EF layer that poits to the CRM.Domai. You will ot recycle this part of the DAL because it is specific to the sample MVVM applicatio for this specific Domai. amespace CRM.Dal.EF public class CRMObjectCotext : ObjectCotext public CRMObjectCotext(strig coectiostrig) : base(coectiostrig) /// Gets or sets the employees. /// <value>the employees.</value> public ObjectSet<Employee> Employees get; set; /// Gets or sets the customers. /// <value>the customers.</value> public ObjectSet<Customer> Customers get; set; Now that you have the ObjectCotext, you ca start to implemet the cocrete DAL for the Etity Framework side. The first class you eed to implemet is, of course, the UitOfWork, which will iherit from CRM.DAL.IUitOfWork. You eed to istruct MEF that you re usig a plug-i IUitOfWork by addig the [Export] attribute to the cocrete UitOfWork implemetatio, as show i the followig code: [Export(typeof(IUitOfWork))] public class UitOfWork : IUitOfWork private ObjectCotext orm; /// Iitializes a ew istace of the <see cref="uitofwork"/> class. /// <param ame="orm">the orm.</param> public UitOfWork(ObjectCotext orm) this.orm = orm; I the UoW costructor you will iject the curret ObjectCotext, which is the proxy used for your Domai Model.

137 116 Chapter 4 The Data Access Layer The ext short code example shows a simple Add method. Basically, you must add the etity to the ObjectCotext. The the CommitTrasactio method will try to update the Etity Framework sessio i a trasactioal cotext. If the Add operatio fails, Etity Framework does t eed a rollback method, because it will automatically roll back the etities status: /// Adds the specified etity. /// <typeparam ame="t"></typeparam> /// <param ame="etity">the etity.</param> public void Add<T>(T etity) try this.orm.addobject(etitysetname, etity); catch (Exceptio ex) throw ew Exceptio(strig.Format( "A error occurred durig the Add Etity.\r\0", ex.message)); /// Commits the trasactio. public void CommitTrasactio() try if (tx == ull) throw ew TrasactioExceptio( "The curret trasactio is ot started!"); orm.savechages(false); tx.complete(); orm.acceptallchages(); catch (Exceptio ex) throw ew Exceptio(strig.Format( "A error occurred durig the Commit trasactio.\r\0", ex.message)); fially tx.dispose(); The secod class you will implemet is the geeric Repository that iherits from CRM.DAL. IRepository ad that exposes all the available methods from the IRepository iterface. The Repository will also have a Export attribute so that you ca use MEF i the MVVM layer to load the selected O/RM o the fly.

138 Mappig the Domai Usig NHiberate 117 [Export(typeof(IRepository))] public class Repository : IRepository [Import] private IUitOfWork uow; /// Adds the etity. /// <typeparam ame="t"></typeparam> /// <param ame="etity">the etity.</param> /// <returs></returs> public T AddEtity<T>(T etity) try uow.begitrasactio(); uow.add(etity); uow.committrasactio(); retur etity; catch (Exceptio ex) uow.rollbacktrasactio(); throw ew Exceptio(strig.Format( "A error occurred durig the Add Etity method.", ex)); Note that the code marks the private field IUitOfWork with the [Import] attribute. MEF will use this attribute to realize the correspodig mapped cocrete UitOfWork at rutime whe you create a ew istace of the Repository class. All the other methods of the Repository should be implemeted similarly: you ope a trasactio, call the correspodig UitOfWork method, ad the call CommitTrasactio or RollbackTrasactio at the ed. That completes the UitOfWork implemetatio for the Etity Framework. You have a fully pluggable DAL for the Domai Model that is ot aware of the mappig model, which you desiged usig the.edmx desiger of the Etity Framework. Mappig the Domai Usig NHiberate The process to map the domai usig NHiberate is simpler ad should take less time but remember, everythig depeds o the type of DDD approach that you are usig. I this case, if you re usig a domai-first approach, NHiberate lets you auto-geerate everythig, from the mappig to the fial database schema. If you re usig the database-first approach, NHiberate will require more effort tha Etity Framework to geerate the mappig files.

139 118 Chapter 4 The Data Access Layer Gettig the Tools First, go to ad dowload the latest build or the last available Geeral Availability (GA) release. At the time of this writig, versio 3 has bee released i beta 2, ad it s already pretty stable. After you have dowloaded the versio that you wat to use, go to ad dowload the latest versio of FluetNHiberate so that you ca create the mappigs usig a few lies of code rather tha maually writig error-proe XML files. Create a ew solutio i Visual Studio ad call it CRM.DAL.NHiberate. Add these three refereces: CRM.DAL (the abstract DAL layer), CRM.Domai (The Domai Model) ad System. CompoetModel.Compositio (for MEF support). Fid the folder where you istalled NHiberate; you should see a set of assemblies that are madatory to ru this O/RM. To fully istall NHiberate, you should have dowloaded three differet packages: NHiberate[versio].GA, the core egie: LINQtoNHiberate[versio].GA, which supplies support for LINQ; ad FluetNHiberate, as discussed at the begiig of this sectio. You should referece all three packages i your NHiberate cocrete DAL. Refer to Figure 4-11 as a referece. Figure 4-11 The required assemblies for NHiberate. Before we begi, I ll briefly explai this list of assemblies. The folder amed Core cotais the NHiberate egie; Log4Net.dll, which is a ope-source log that s plugged ito this O/RM; Iesi.Collectio.dll is a proxy collectio used by the O/RM; ad Atlr3.Rutime.dll is a profiler for the O/RM. FluetNHiberate.dll is self-explaatory. The Proxies folder is oe of the available proxy egies for o-the-fly creatio of proxy classes. You ca choose from Castle, LiFu, or Sprig; ufortuately, Uity is ot available for this O/RM. Select the oe you prefer. For demostratio purposes here, I will use Castle, just because it s the simplest to cofigure.

140 Mappig the Domai Usig NHiberate 119 After referecig all the assemblies, you ca begi to build your NHiberate mappig ad sessio factory. Let s start with the UitOfWork. You wat to do the same thig you did for the Etity Framework DAL: create a ew UitOfWork that iherits from CRM.DAL. IUitOfWork ad implemet each cocrete method. The UitOfWork ad the ISessio The UitOfWork for NHiberate is slightly differet because there s o ObjectCotext object. Istead, we have a ISessio object geerated by the Sessio Factory. Here s how it works: [Export(typeof(IUitOfWork))] public class UitOfWork : IUitOfWork private ITrasactio tx; private ISessio orm; public UitOfWork(ISessio orm) this.orm = orm; The ISessio iterface is more powerful tha the ObjectCotext object provided by Etity Framework, ad it s also more flexible. Ufortuately, due to its characteristics you must provide all the ecessary code to execute a correct busiess trasactio. The ISessio itself will keep the trasactio alive as log as you wat. public void BegiTrasactio() if (tx!= ull) tx = orm.begitrasactio(); public void CommitTrasactio() if (tx == ull) throw ew Exceptio("The curret trasactio has ot bee iitialized."); tx.commit(); public void RollbackTrasactio() if (tx == ull) throw ew Exceptio("The curret trasactio has ot bee iitialized."); tx.rollback();

141 120 Chapter 4 The Data Access Layer The other methods are pretty close to what you ve already see with Etity Framework. The mai differece is that NHiberate does t eed to get attached to a existig etity if you disposed the ISessio. NHiberate s persistece igorace mechaism is able to uderstad whether a etity is a ew etity or a existig oe. NHiberate has very specific maagemet for the Domai Sessio, represeted by the Sessio Factory, a static class that is able to geerate all the required proxies ad coectios for the O/RM i oe shot. Your DAL will retrieve the Sessio from the Sessio Factory, which will retur a ew UoW. The sample code uses the FluetNHiberate plug-i, ad the short excerpt that follows shows you how to create a automatic mappig (Domai fields = database fields) with just oe call: [Export(typeof(ISessioFactory))] public class SessioFactory : ISessioFactory private IUitOfWork uow; public IUitOfWork CurretUoW get if (uow == ull) uow = GetUitOfWork(); retur uow; public SessioFactory() /// Gets the uit of work. /// <returs></returs> private IUitOfWork GetUitOfWork() var sessio = Fluetly.Cofigure().Database( MsSqlCofiguratio.MsSql2008.CoectioStrig(x => x.fromappsettig("databasecoectio"))).mappigs(m => m.automappigs.add(automap.assemblyof<perso>).add(automap.assemblyof<customer>).add(automap.assemblyof<employee>).buildcofiguratio(); var uow = ew UitOfWork(sessio); retur uow;

142 Summary 121 This sample created a ew SQL 2008 sessio which, like the Etity Framework sessio, will retrieve the coectio strig from the App.Cofig/Web.Cofig ad create a automappig for each etity added to the cofiguratio. That s it. Usig a domai-first approach you do t eed to do aythig else the ISessio is ready for use. The Repository I left the repository implemetatio util the ed of the tutorial because it should ot be differet betwee the two O/RMs. The oly differece is that i the Etity Framework, you will query the ObjectCotext object, while i NHiberate, you will query the ISessio object. The oly importat thig for takig advatage of lazy loadig ad dyamic SQL creatio is to always retur a IQueryable<T> collectio. The followig code uses the Etity Framework UitOfWork to retrieve a list of Customers: public IQueryable<T> GetList<T>() where T : class retur ((ObjectCotext)this.UoW.orm).CreateObjectSet<T>(); Here s the same code usig the NHiberate Repository: public IQueryable<T> GetList<T>() where T : class retur ((ISessio)this.UoW.orm).Liq<T>(); Both of these repositories allow you to write somethig such as this: var customers = GetList<Customer>().Where(c => c.firstname == "Joh").OrderBy(c => c.firstname) The implemetatio will be the same for all the repository implemetatios. I this way, we will use the IQueryable<T> objects without the eed to kow what DAL we are really usig i the MVVM layers. Summary I this chapter, you ve see a umber of cocepts, the O/RM beig amog them. If you have ot yet worked with a O/RM, you should review the sample code for this book ad sped some time ivestigatig documetatio ad tutorials based o the O/RM that you choose. The purpose of the exercise i this chapter is to show you how to write dyamic ad recyclable code. Of course, i a real-world MVVM LOB applicatio, you will probably ever eed

143 122 Chapter 4 The Data Access Layer to map your Domai Model to two differet O/RMs but the poit is that if you follow these techiques, you will be able to recycle parts of your code for your ext MVVM applicatio. You saw that we ca still use the classic style of writig custom T-SQL code or you ca sped less time ad focus more o the busiess logic of a applicatio by delegatig the hard work to a O/RM. A O/RM is othig more tha a applicatio framework used to help traslate a Domai Model ito somethig that the database uderstads, all without losig the powerful POCO cocepts of havig the Domai uaware of the persistece mechaism. There are other O/RMs available for the.net Framework, but the most popular (ad free) are the Etity Framework ad NHiberate. While the Etity Framework is desiged more for a database-first approach, NHiberate is more flexible whe used with a domai-first approach. However, you saw that either O/RM ca be used with either of these two DDD approaches.

144 Chapter 5 The Busiess Layer After completig this chapter, you will be able to: Create ad execute Busiess Rules. Create the correct Busiess Logic Layer. Apply the kowledge acquired to the sample applicatio. Itroductio Oe of the most time-cosumig tasks ad probably the most expesive i terms of maiteace is the Busiess Layer of your applicatio (provided, of course, that the applicatio you are workig o has oe). I both old-fashioed ad moder applicatios, the Busiess Layer is geerally composed of a ested set of classes. Some applicatios store the busiess logic i the Domai Layer; others store it i the database usig stored procedures or views. The worst applicatios store the busiess logic i a haphazard maer, scattered throughout the code. There are few thigs less ejoyable tha tryig to maitai a applicatio that has busiess logic strew all over. Not oly will you waste a lot of time just tryig to figure out how the code works, but every chage you make could cause uexpected behaviors i other sectios of the applicatio. I a clea, moder desig, the Busiess Layer should be a separate layer of your applicatio. It should be aware of the Domai Layer ad probably also the Data Layer. The Busiess Layer is the logical core of ay Lie of Busiess (LOB) applicatio, ad it should be the oly place where the busiess logic of your applicatio resides. It should also be easy to maitai ad self-documetig. I a Model View ViewModel (MVVM) applicatio, the Busiess Layer is composed of a set of Services ad Busiess Rules that defie the busiess processes which the program is desiged to perform. This layer is exposed ad used by the ViewModels that should iclude oly the presetatio logic. This scheme lets you maitai a loose couplig betwee the busiess logic ad the presetatio logic. 123

145 124 Chapter 5 The Busiess Layer Note While the term Busiess Rules is ofte used to mea ay o-ui logic, i this book, the term icludes oly logic that implemets busiess processes ad esures data itegrity. This code is idepedet of the cliet portio of the applicatio. Before explorig how to accomplish the goal of keepig the busiess logic separate from the views ad the domai etities i the sample CRM applicatio, I wat to explai the differece betwee validatio rules ad busiess rules. A Busiess Rule Is Not a Validatio Rule A Validatio Rule is ay criterio that describes how to validate a specific value of a specific object. Examples iclude the field legth costrait for a database table, or the Required Field messages displayed i a View. Validatio Rules are usually applied to a object that eeds to be validated before its value is saved to the data store or before it s processed by aother trasactio that requires the value to be valid. I cotrast, a Busiess Rule is ay rule that acts to chage the value of a object, based o a set of rules or based o a specific behavior. Ofte, Busiess Rules have the sole purpose of iformig users whether a actio ca or caot be executed after the evaluatio of specific objects ivolved i that trasactio. Note I have oticed that may people do ot make a distictio betwee Busiess Rules ad Validatio Rules. Because both serve the same master, you ca lump both types of rules together but you should be aware that there are two differet types of rules. The first type esures data itegrity ad validity, ad belog to what this book calls Validatio Rules, the secod type hadles busiess processes ad operatios; i this book, those are called Busiess Rules. Usually, you defie Validatio Rules i two distict layers: the Domai Model ad the UI. I the first case, you set up costraits to esure a Domai Etity is valid before savig it to a data store or processig it with aother compoet. You ca defie these rules maually usig procedural code, usig third-party frameworks, or through simple decoratio attributes. The followig code shows how you might validate a object usig the System. CompoetModel amespace available with the Microsoft.NET Framework: /// Gets or sets the first ame. /// <value>the first ame.</value> [Required(ErrorMessage = "The First Name ca t be ull or empty.")] [StrigLegth(50, ErrorMessage = "The First Name ca t be greater tha 50 characters.")] public strig FirstName get; set;

146 A Busiess Rule Is Not a Validatio Rule 125 The precedig code defied some simple validatio rules o the Perso Domai Etity, specifically, o its FirstName property. We wat to esure that the property value is t blak ad that it does t exceed 50 characters i legth. Each validatio error is associated with a specific error message. I Chapter 6, The UI Layer with MVVM, you ll see how you ca easily bid these properties to the ViewModel. A secod applicatio of this rule lies i the UI layer. For example, i a simple LOB Silverlight applicatio, you might ecouter validatio behavior whe tryig to log o usig improper credetials. Figure 5-1 shows a classic validatio rule applied to a Silverlight MVVM view. Figure 5-1 Silverlight view with a validatio message. A Busiess Rule uses a differet approach because it is composed of a set of rules that are t easily defied usig a simple attribute approach. Typically, you eed to write if/else statemets or switch statemets, depedig o the type of ruleset that you wat to verify. The.NET Framework icludes a free ad useful tool to accomplish this task: Widows Workflow Foudatio versio 4 (WF 4.0). Of course, the problem here is ot oly about writig complex if/else or switch statemets. It s about the applicatio logic you use to implemet a busiess process or to esure that a complex set of rules is applied, which you ca t express as a sigle attribute o a property. For example, you ca cosider the workflow show i Figure 5-2 as a set of rules.

147 126 Chapter 5 The Busiess Layer Figure 5-2 A custom workflow to create a order. The workflow i Figure 5-2 executes a set of Busiess Rules to verify that a submitted Order ca be fulfilled; for example, whether a requested product is i stock ad available to be shipped. If verificatio succeeds, the the Order will be created, ad a message will be set to the queue. Otherwise, the order will be discarded, ad a differet message will be set to the queue to iform the customer that the product is ot i stock. You ca also accomplish this process by usig the followig pseudo C# code: public class CustomRules [Import] private IRepository repository; public void CaAddAOrder(Order order, Customer customer) foreach (var orderlie i order.orderlies) var available = repository.getetity<product>(orderlie.product.primarykey).amoutistock; if (!available) RemoveOrder(order, customer); break;

148 Busiess Rules by Service 127 CofirmOrder(order, customer); private void RemoveOrder(Order order, Customer customer) private void CofirmOrder(Order order, Customer customer) This secod example demostrates that traslatig the ruleset to a programmig laguage is a potetially error-proe process. More tha that, this ruleset is totally icomprehesible to ayoe ot fluet i code, such as a aalyst or a accout maager, who also eed to kow how this ruleset works. I additio, the process of maitaiig up-to-date documetatio for such rules ca be time-cosumig. I cotrast, whe you use a graphical tool such as WF 4.0 to implemet a ruleset, you ca share the rules with programmers ivolved i the developmet process ad o-coders, alike. I other words, the visual represetatio makes your rule code more readable ad maitaiable to all participats. I this chapter, you ll see other third-party tools available for usig this workflow-by-desig approach, ad why that approach is much better tha havig custom C# code spread throughout the layers of your LOB applicatios. First, cosider the testability of your Busiess Rules; if they are part of a specific layer/compoet, you ca test them easily agaist a set of mockup data. Secod, cosider the documetatio: a visual workflow is also readable ad uderstadable by o-techical persos such as a operatios employee, or a auditor who might eed to verify the busiess logic applied to the applicatio. Busiess Rules by Service Busiess Rules eed to be stored iside a layer, ad probably the best place to do that is i a additioal assembly visible to the Busiess Layer. That is ot a additioal layer but a extesio of the Busiess Logic Layer (BLL) that icludes oly the physical workflows. It does t matter early as much which techology you use to create your busiess rules (whether workflows, procedural code, or XML files), but it s importat that you keep these rules separate from ay other code i your LOB applicatio so that you ca easily separate maiteace ad test processes. It s also useful to execute these rules with code that uses the same format throughout your LOB applicatio so that you ca easily recogize a call to a Busiess Rule ad apply them i a cosistet way. The Desig by Service is a desig patter itroduced by Marti Fowler, i which the core of your busiess trasactio rus i a service that kows everythig about the Model ad the Data Layer. It is also the oly object i charge of makig busiess decisios.

149 128 Chapter 5 The Busiess Layer By usig Desig by Service i the Busiess Layer, you delegate the executio of a rule or set of rules, object validatio, ad specific busiess trasactios to a service class that does t eed aythig more tha the objects ivolved i the process. The best way to do that is to create a set of service classes based o the busiess trasactios that your applicatio will execute. The more graular the codes i this part of the applicatio, the easier it will be to maitai this importat layer. Pseudo code for such a service class would look similar to this: var svc = Cotaier.Resolve<IService<Customer>>(); var order = svc.createprocess(processeum.createorder, myperso, myorderlies); var result = svc.verify(ruleseum.addorder, myperso, order); The precedig code is a simple geeric class that ca execute workflows based o the type of operatio that you wat to perform. The class is flexible, readable, ad easy to maitai. You ca defie the operatios usig a set of eumeratio values to add more readability to the code, ad the refer to a specific workflow with the same ame. The Facade Patter Aother iterestig way would be to use oe or more of the desig patters we saw i Chapter 2, The Desig Patters, to make the Busiess Layer more flexible. For example, the Facade patter would be a good match for the base service that exposes simple methods through a commo facade iterface, which hides the real iteractio betwee the systems. I the followig example, we wat to expose a AddOrder method withi our facade, but we do t wat to require developers to kow what is goig o behid that process. Figure 5-3 illustrates a classic Facade service layer. Each facade i this case uses geeric implemetatio to idetify the primary etity ivolved i the process, ad each service exposes some busiess methods that execute a set of trasactios that are ot visible outside the facade service. For example, the method CaAddOrder executes additioal methods iside its sigature, such as: IsProductAvailable IsOrderCompleted CaCustomerSubmitOrder Because these three additioal methods are marked as private, they are ot visible outside the Facade service. This way, you ca keep the code separate, but also make usig the service layer less error-proe, because it forces developers to call oly the exposed methods, such as CaAddOrder ad does t provide direct access to the shortcut methods used by the facade.

150 Busiess Rules by Workflow with WF Figure 5-3 A busiess service usig the Facade patter. Busiess Rules by Workflow with WF 4.0 Whe you build your Busiess Layer, it s importat that you provide a meas for o-techical but busiess-savvy people to read ad uderstad it just like the Domai Model. Usig the right combiatio of Domai Model ad Busiess Layer, a o-programmer should be able to uderstad the desig of your applicatio ad the busiess logic behid the applicatio. I the previous sectio, you leared that it s difficult to embed custom geeric logic i a C# procedure ad make it self-documetig. Of course, you ca write a ice, clea fluet iterface, but ofte that s ot eough, especially because the Busiess Layer ofte cotiues to grow ad chage throughout a applicatio s lifetime. WF 4.0, which ships with the.net Framework 4, has a updated workflow egie built aroud XAML code just like a ormal MVVM applicatio. This versio is completely differet from the previous versio; it s both very flexible ad allows you to build custom workflows ad rulesets for your Busiess Layer. The basic cocept of WF 4.0 is to simplify writig a procedural workflow that ca make decisios ad adapt, based o values it receives as iput parameters. Of course, these values ca be either from oe or more domai model etities, or just simple scalar values. The followig example uses a ew Workflow Activity Library project type, available with.net Framework 4 ad Microsoft Visual Studio I have added two refereces to the project: oe to the geeric Data Layer that you created i Chapter 4, The Data Layer, ad oe to the Domai Model that you created i Chapter 3, The Domai Model. This workflow is iteded to esure that a user ca add ad cofirm a Order. I this case, there will be two parameters: the curret Customer ad the Order to process.

151 130 Chapter 5 The Busiess Layer To begi, the workflow icludes oe if statemet to verify that the products i the Order are available. Each product has a AmoutIStock property that tells us how may items are i stock. Each OrderLie of a product has a Quatity property ad a Product property. The rule basically applies this cocept: If the amout requested is greater tha the availability i stock the Order ca t be processed. Figure 5-4 documets this process by usig WF 4.0. Figure 5-4 The workflow for the Add Order Busiess Trasactio. I this example, you are passig two iput parameters to the workflow: CurretCustomer ad CurretOrder. You retrieve a Boolea output parameter called CaAddOrder. Callig this from the fial code will look somethig like this: var customer = MVVMView.CurretCustomer; var order = MVVMView.CurretOrder; var caaddorder = OrderService.CaAddOrder(customer, order); if (caaddorder) customer.addorder(order); uow.save(customer); Of course, you should also start ad close a trasactio this code assumes that the Order ad the Customer have bee validated prior to the code begiig. Differet Ways of Ruig a Workflow WF 4.0 offers two ways to ru a workflow. A workflow by itself is othig more tha a XAML file compiled iside a.dll project (a Activities Library)..NET 4 ca read these special XAML files, deserialize them o the fly, ad the pass them to the WF egie executor, or it ca process a XAML file embedded i a class library by usig the Workflow Applicatio object.

152 WorkFlowIvoker Busiess Rules by Workflow with WF The first (ad simplest) method to ru a workflow (which was iherited from versio 3 of the Workflow egie) is called WorkflowIvoker. This class requires that the workflow you wat to ru is already i had, so you must either kow the real code file ame of the workflow or have the XAML code. It works i the followig way: // first of all you reder the workflow i memory Activity wf; usig (Stream xaml = File.OpeRead("CaAddOrder.xaml")) wf = ActivityXamlServices.Load(xaml); Next, you call the static Workflow Egie ad pass it ay iput ad output parameters iside a IDictioary<strig, object> collectio, where the key of the collectio is the parameter ame, ad the object is the curret value. var params = ew Dictioary<strig, object> "CurretCustomer", mycustomer, "CurretOrder", myorder, // execute the workflow var output = WorkflowIvoker.Ivoke(wf, params); // access the result Cosole.Writelie("Ca Execute? 0", output["caexecute"]); The WorkflowIvoker returs aother collectio of type <strig, object>, which icludes all the available output parameters. Pros ad Cos of the WorkflowIvoker The WorkflowIvoker is fairly simple ad easy to use. I fact, it s too simple; it does t give you much cotrol over the workflow. For example, you ca t track the status of the workflow, ad you ca t moitor the executio by usig evets. Therefore, you should use WorkflowIvoker oly for simple workflows such as CaExecute o a Cotext Meu or a Butto commad. You might also use it for testig your workflows before goig ito productio, but keep i mid that WorkflowIvoker is ot desiged for a more complex eviromet. WorkflowApplicatio ad WCF If you pla to build your MVVM applicatio s BLL usig WF 4.0, you should cocetrate o the more complex hostig egie, called WorkflowApplicatio. This compoet uses the same collectios of iput ad output parameters, but you also have access to specific evets ad asychroous calls by which you ca build a more complex ad sophisticated rule egie.

153 132 Chapter 5 The Busiess Layer To ru a workflow this way, you first eed to retrieve your curret workflow. To do that, you do t eed to kow the XAML path, just the class ame available i the DLL, as show i the followig example: WorkflowApplicatio wf = ew WorkflowApplicatio(ew CaAddOrder()); // parameters var params = ew Dictioary<strig, object> "CurretCustomer", mycustomer, "CurretOrder", myorder, The you create a ew istace of the o-static WorkflowApplicatio ad subscribe to all the available evets, so that you ca have full cotrol over the executio of the ruleset: wf.completed = delegate(workflowapplicatiocompletedevetargs e) // Hadle the executio Complete ; wf.aborted = delegate(workflowapplicatioabortedevetargs e) // hadle the executio aborted ; wf.ouhadledexceptio = delegate(workflowapplicatiouhadledexceptioevetargs e) // hadle the failure retur UhadledExceptioActio.Termiate; ; wf.ru(); Usig this approach, you ca execute the ruleset o a middle tier, for example, which might be faster ad more powerful tha the cliet s PC, or you ca simply moitor the executio of a workflow ad make busiess decisios without throwig exceptios i UI. AppFabric ad the WCF Executio Microsoft AppFabric is a set of itegrated techologies that make it easier to build, scale, ad maage web ad composite applicatios that ru o IIS ad Widows Server. Widows Server AppFabric is available at You ca dowload ad istall it through the easy-to-use web platform Istaller compoet. Oe feature of AppFabric is that it provides the possibility to host ad execute Widows Workflows through a set of WCF Services, so that the BLL of your applicatio ca be stored i a separate applicatio server. Because AppFabric is also based o.net Framework 4, it provides out of the box a set of persistece, moitorig, ad hostig fuctioalities that

154 Third-Party Toolkits 133 ca be useful whe you are buildig a applicatio server that eeds to host oe or more applicatio BLLs. AppFabric is a complex product that probably deserves a etire book, but the poit here is that AppFabric is absolutely the aswer for buildig a medium to complex BLL with a scalable ad maitaiable applicatio server. To support this claim ad to help you uderstad the product better, here is a list of features that Widows AppFabric server makes available: Deploymet ad maagemet of WCF ad WF Services hosted usig WAS Cofiguratio ad persistece of workflows, their statuses, ad their executio results Dedicated queryable storage for maagemet Full itegratio with Widows PowerShell Customizable moitorig of hosted services Pros ad Cos of WorkflowApplicatio If you pla to use the WorkflowApplicatio egie, the cosideratios are essetially the opposite of those for usig the WorkflowIvoker. The WorkflowApplicatio class requires more effort, but it allows you to write a more stable ad powerful workflow executor. At the same time, it provides more cotrol ad optios that you might eed if you pla to use WF as your uique ruleset egie. WF also offers may additioal features, such as hostig a workflow directly i your WPF applicatio, or persistig the status of a workflow i SQL, so you ca pause ad restore the workflow executio as required. For this ad other features, see the WF documetatio ad other iformatio available at Third-Party Toolkits I this case, the Busiess Layer will be very complex ad you will probably ot have the time to lear ad master a complex techology such as WF. You must also keep i mid that WF is a ope techology, so to customize it to satisfy your customer s eeds, you will eed to sped some time o it. I have also oticed that usually, i a big eviromet, the Busiess Layer is icorrectly left to the aalyst side, where they kow how to write the busiess rules, but ufortuately, most of the time, they do t kow how to traslate these rules ito somethig usable by a MVVM applicatio. I such cases, you should cosider usig a third-party tool which will alleviate the effort ivolved; you will just eed to plug this techology ito your BLL. There are usually suitable third-party tools that ca provide aalysts with a easy-to-use workflow desiger

155 134 Chapter 5 The Busiess Layer ad at the same time exted a powerful rule egie to developers that ca be plugged ito ay LOB applicatio. Techologies for the Data Validatio The Microsoft Eterprise Library, curretly at versio 5.0, will probably satisfy all your requiremets for addig data validatio to your Domai Etities. You ca obtai Eterprise Library here at Eterprise Library ships with a Validatio Applicatio Block (VAB); a useful framework that provides a default set of validatio rules, plus a powerful ad customizable rule egie. Note Remember that data validatio should be eforced ot oly o the Domai Model but also i the ViewModel of your MVVM UI, ad i ay place where data validatio is required by desig. Basically, VAB lets you decorate classes with the validatio rules provided by the Library or with custom rules that you provide. Later, you ca validate the object ad retrieve ay validatio errors. The followig code illustrates how to perform basic validatio usig the VAB library: usig Microsoft.Practices.EterpriseLibrary.Validatio; usig Microsoft.Practices.EterpriseLibrary.Validatio.Validators; public class Customer [StrigLegthValidator(0, 20)] public strig CustomerName; public Customer(strig customername) this.customername = customername; public class MyExample private ValidatorFactory factory; public MyExample(ValidatorFactory valfactory) factory = valfactory;

156 Third-Party Toolkits 135 public void MyMethod() Customer mycustomer = ew Customer("A ame that is too log"); Validator<Customer> customervalidator = factory.createvalidator<customer>(); // Validate the istace to obtai a collectio of validatio errors. ValidatioResults r = customervalidator.validate(mycustomer); if (!r.isvalid) throw ew IvalidOperatioExceptio("Validatio error foud."); VAB cotais a default set of validatio attributes that iclude the followig: Cotais Characters Validator Date Time Rage Validator Domai Validator Eum Coversio Validator Not Null Validator Object Collectio Validator Object Validator Or Composite Validator Property Compariso Validator Rage Validator Regular Expressio Validator Relative Date Time Validator Strig Legth Validator Type Coversio Validator Sigle Member Validators

157 136 Chapter 5 The Busiess Layer You might also be iterested i other third-party validatio frameworks; most of these are both reliable ad ope source, meaig that you do t eed to purchase liceses to use them i your MVVM applicatio. Additioal validatio frameworks that you wat to explore for.net are: EVIL ( A ope-source project that works much like the VAB library, usig decoratios ad rulesets. Active Record ( A ope-source plug-i for NHiberate that trasforms your domai ito a Active Record domai. Coditios ( Aother ope-source framework that uses the Fluet Iterface (see Chapter 2) istead of attributes. Rule Egie ad Busiess Rule Egie Whe you move to the cocepts of Busiess Rules, the argumet becomes more complex. A Busiess Rule egie should usually be able to execute custom rules, provide a fluet sytax that is uderstadable by o-techical users, ad provide a easy-to-read ad modifiable authorig tool. Of course, if you are lookig for all these requiremets i oe tool, ready to use, you will probably eed to test ad purchase a third-party Busiess Rule egie which wo t be free. The two tools you ll see here are the most popular for.net. That does t ecessarily mea that they are the best or the most flexible tools available for all purposes. I additio, these tools have a startig price close to 100,000 USD. There are various tools available olie; the oe show here ad the ext oe are just some of them, ad i o way does it mea that you should adopt this particular tool as your busiess rule egie. IRule for.net IRule is a very flexible ad easy to use Busiess Rules egie that you ca easily plug ito ay.net applicatio. It provides user cotrols for editig rules directly withi your applicatio, ad it has a straightforward, easy to uderstad ifrastructure. IRule might ot be the most scalable solutio, but the price is owhere ear as high as may other Busiess Rules egies. You ca dowload a demostratio versio of IRule from ad ru the available tutorials to see how to use the tool. Figure 5-5 shows a custom Silverlight applicatio usig IRule to edit some Busiess Rules.

158 Busiess Layer Cosideratios 137 Figure 5-5 The IRule Silverlight authorig tool. Busiess Layer Cosideratios I this chapter, you ve see how complex a Busiess Layer ca be ad why it s a requiremet for your MVVM applicatios. Of course, havig a Busiess Layer i your applicatio ca itroduce some problems that you eed to cosider. Whe Do I Need to Create a Busiess Layer? It s a good practice to always try to uderstad whether a feature is truly eeded i your MVVM applicatio so that you ca avoid over-egieerig. The Busiess Layer ca be less or more complicated, ad you should always keep i mid the followig otes before startig to create a BLL i your applicatio: If you eed to execute a sigificat umber of operatios ad/or busiess rules to persist ew data i your applicatio s data store, it s probably a good idea to create a BLL layer i your applicatio. O the other had, if you oly eed to save ad retrieve data from a database ad display it a UI, desigig ad usig a BLL is probably overkill. If you eed to validate your objects before savig them i your datastore or before movig to the ext step of your applicatio flow, a BLL is a good way to keep the validatio process isolated from the rest of the applicatio. However, whe you are workig with basic data that does t eed much or ay validatio, you do t eed a BLL. If the logic of your applicatio is dyamic, complex, ad icremetal (meaig that it will grow ad chage durig the developmet process) ad eeds to be documeted for auditig purposes, you must have a BLL ad you will probably also eed

159 138 Chapter 5 The Busiess Layer to cosider purchasig a Busiess Rules egie. By doig this, you will also be able to keep your BLL separated from the other applicatio compoets ad allow it to evolve idepedetly. To sum up, if your applicatio requires ay sigificat amout of busiess logic ad/or data validatio, you should cosider creatig a BLL to keep that fuctioality separate from the rest of your applicatio code. That will simplify both applicatio maiteace ad help with documetatio. Bad BLL Habits The last few words regardig BLLs are about bad habits I ve ecoutered that you should always avoid. First, the BLL is ot the Uit of Work (UoW) of your applicatio, ad it is ot the Repository for your Data Access Layer. The BLL has atomic methods that ca execute a set of busiess trasactios, such as: var result = BLL.CaAddOrderToCustomer(myCustomer, myorder); It s very likely that the CaAddOrderToCustomer method implemets a set of operatios that ivolve the UoW, the Repository, ad the Domai Model, such as i the followig example: public void CaAddOrderToCustomer(myCustomer, myorder) UitOfWork.StartTrasactio(); var available = repository.get<order>(myorder).amoutistock; if (available) mycustomer.orders.create(myorder); repository.update<customer>(mycustomer); This does t mea that a BLL should have a method like GetCustomer(it id), because this method should be exposed by the Repository, ot implemeted i the BLL. More tha likely, there will be aother place i the applicatio that does t eed to use BLL fuctioality but eeds to load a customer by ID. Secod, the BLL is the layer that you use to speak busiess laguage, so you should always use a clear ad eat amig covetio. A method that verifies whether a order ca be added should be called somethig like CaCustomerCreateOrder or CaItemBePurchased istead of the shorter but less uderstadable AddOrder or PurchaseItem. Remember that the BLL icludes the busiess logic of the applicatio, so you will evetually eed to chage or upgrade it, either because the busiess logic has bee revised or the process has chaged.

160 Sample Code: The Busiess Service Layer 139 Fially, test, test, ad test agai. You must test each method of the BLL with real data, especially if the BLL executes calculatios ad statistics. Every sigle method must be examied with a set of fully reliable tests that you ca ru i the future, whe you have to update the applicatio s busiess logic. Sample Code: The Busiess Service Layer Now that we have the Domai Model i place, ad we kow how to persist ad retrieve the Domai Model from the database, we eed a smart way to execute busiess logic rules agaist the Domai Model ad to validate the Domai Etities usig a specific set of Validatio Rules. For the validatio process, the example CRM applicatio will use the Eterprise Library 5.0; specifically, this example makes use of the VAB ad C# geerics to build a geeric validator. For Busiess Rules, the applicatio uses Widows WF 4.0. You ll also see how to create a simple FluetEgie that is able to ru ay workflow you wat. Data Validatio with the Eterprise Library 5.0 The first step is to dowload the latest versio of the Eterprise Library, which is available at The you eed to ru the Build commad available i the Eterprise Library 5.0 setup. You should ow have two folders (depedig o the setup optios you chose): oe cotaiig the Eterprise Library source code, ad oe with a compiled deployed versio. The DLL that you eed is amed Microsoft.Practices. EterpriseLibrary.Validatio.dll. Add a referece to this DLL i the CRM.Domai layer so that you ca add Data Validatio rules for each Domai etity. The followig code example shows the Perso etity with some basic data validatio rules applied: /// Gets or sets the first ame. /// <value>the first ame.</value> [NotNullValidator(ErrorMessage = "The First Name ca t be ull or empty.")] [StrigLegthValidator(50, ErrorMessage = "The First Name leght ca t be greater tha 50 characters.")] public strig FirstName get; set; /// Gets or sets the last ame. /// <value>the last ame.</value>

161 140 Chapter 5 The Busiess Layer [NotNullValidator(ErrorMessage = "The Last Name ca t be ull or empty.")] [StrigLegthValidator(50, ErrorMessage = "The Last Name leght ca t be greater tha 50 characters.")] public strig LastName get; set; /// Gets or sets the birth date. /// <value>the birth date.</value> [NotNullValidator(ErrorMessage = "The Birth Date ca t be ull or empty.")] [RelativeDateTimeValidator(18, DateTimeUit.Year,100,DateTimeUit.Year, ErrorMessage = "The Birth Date ca t be lower tha 18 years.")] public DateTime BirthDate get; set; The precedig code tries to reflect the database schema costraits i the Domai Etities so that the applicatio ca validate each etity before savig or retrievig it from the database. You ca the apply this step i the UoW so that every etity passed to it ca be self-validated before committig the trasactio. Now we eed to validate this etity, ad if it s ot valid, we should retur a Boolea result i cojuctio with a collectio of errors geerated by the validatio process. Every etity that is iherited from a Domai Base Object ca be validated, so there is o better place tha the Domai Object to itroduce this validatio process. By desig, the VAB exposes a collectio called ValidatioResults that cotais the results of a validatio process ad a Boolea property called IsValid. You ca retrieve the validatio collectio by usig the Validator class exposed by the applicatio block. First, let s ope the Domai Object class ad add a read-oly property that exposes the validatio results: /// Gets the validatio errors. /// <value>the errors.</value> public ValidatioResults Errors get; private set; Now, we eed to expose a IsValid property, which will fire the validatio process behid the scees. Before doig that, I wat to show you how you apply the Validatio Facade patter to the VAB. Whe you wat to validate a ew object, you ca simply use the Validatio Factory facade provided i the library. Ufortuately, the sytax of the Facade is as follows: // optio usig geerics var validator = ValidatioFactory.CreateValidator<T>(); // secod optio without geerics var validator = ValidatioFactory.CreateValidator(Type); This meas that you caot expose the method from the base class without exposig its geeric sigature; otherwise, whe you call this method from a iherited class, the validatio will validate oly the base class properties. A smart solutio might be:

162 Sample Code: The Busiess Service Layer 141 /// Gets or sets a value idicatig whether this istace is valid. /// <value><c>true</c> if this istace is valid; otherwise, <c>false</c>.</value> public virtual bool IsValid get; private set; /// Validates this istace. /// <typeparam ame="t"></typeparam> /// <returs></returs> protected bool Validate<T>() Errors = ValidatioFactory.CreateValidator<T>().Validate(this); retur Errors.IsValid; Now you ca override the validatio process if you wat (ote that the precedig chage marked the property as virtual, ad ot abstract). Whe you eed to implemet a validatio process, such as i the Perso class we previously decorated with the Eterprise Library attributes, you ca simply override the IsValid property i this way: /// Gets or sets a value idicatig whether this istace is valid. /// <value><c>true</c> if this istace is valid; otherwise, <c>false</c>.</value> public override bool IsValid get retur base.validate<perso>(); At this poit, you have a simple validator that you ca recycle throughout the Domai Model. Usig the same Facade patter, you ca validate the ViewModel i the same way. For more i-depth iformatio about Eterprise Library, dowload the complete documetatio i PDF form from the CodePlex website at view/ The documetatio icludes a wealth of samples ad tutorials. A Geeric Workflow Egie Earlier, this chapter showed how Workflow Foudatio ca be the perfect solutio for buildig a i-house Busiess Rules egie. While the sytax to load ad ru a workflow is ot ideal, by usig the Fluet Laguage patter that was preseted i Chapter 2, you ca create a fluet egie that s both easy to use ad able to process ay workflow. Remember, you have two optios for ruig a workflow: the skiy, static WorkflowIvoker, or the more complex WorkflowApplicatio. Usig the secod optio, you ca moitor the

163 142 Chapter 5 The Busiess Layer status of a workflow ad add custom rutime behaviors (such as writig to a specific log) or attach evets. Let s start by addig the ifrastructure to create the fluet sytax. The schema i Figure 5-6 shows the UML diagram for a Fluet Workflow Egie. Usig this egie, you ca load a assembly that cotais a set of Workflows, load a specific Workflow, create listeers for WF evets usig lambda sytax, ad of course, ru the workflow. Figure 5-6 The UML Schema for the Fluet Egie. Note If you do t remember how to build a fluet Iterface, review the DSL: Writig Fluet Code sectio o page 53, i Chapter 2. Here, I have created two iterfaces so that the fluet iterface will have two major steps. The first step loads ad iitializes a workflow. I the secod step, you cofigure the evets to which you wat to liste. Both iterfaces ca directly ru the workflow but if you do t at least liste for the ocomplete evet, you wo t kow whe workflow executio completes. The static class is used oly to create a more fashioable fluet sytax to avoid the ugly use of the ew keyword. The fial sytax used to ru a workflow should look somethig like the followig: //Iit the egie class FluetEgie.Iit() //load assembly ad workflow.loadassembly("myworkflowlibrary.dll").loadactivity("caaddaorder.xaml") //prepare the parameters collectio // it should cotais iput/output params.addparamters(ew Dictioary<strig, object>

164 Sample Code: The Busiess Service Layer 143 "Order", ull, "Customer", ull ).Cofigure() //whe the WF is doe.ocomplete(() => Cosole.WriteLie("Complete!"); ) //whe the WF raises a error.oerror((ex) => Cosole.WriteLie("Error: 0", ex); ).Ru(); You ca use this easy-to-read sytax i the MVVM applicatio to ru ad moitor a workflow. For more i-depth iformatio about the workflow egie, the project CRM.BL.WF cotais the Workflow Egie implemetatio ad all the workflows for the CRM applicatio example. Service for Busiess Trasactios With the base code i place, we eed to implemet the Facade patter for the BLL to prepare the services for use. I this sectio, you ll see how to implemet the process of addig a New Order service from begiig to ed. You ca the optioally create custom Busiess Rules or you ca simply ope the fial project ad see how I implemeted the BLL. The first importat cocept is the user story that will drive this Busiess Trasactio: As a User, I wat to be able to create a Order ad submit the Order by addig the Order to the correspodig Customer, ad the sed a cofirmatio. For each Product i the Order, I eed to verify that the Product is i stock. Figure 5-7 shows the workflow result of this user story, divided ito three sectios to make it easier to read.

165 144 Chapter 5 The Busiess Layer Check that each Product is available i Stock for the amout requested i the OrderLie If ot available, the previous for each loop will throw a exceptio ad we catch it here If the workflow arrives at this step, it meas that the Order is fie, so we submit the Order ad sed a Figure 5-7 The complete workflow to add a order. This workflow requires two iput parameters, a Customer ad a Order. It returs a Boolea result. The code to ru this workflow should look somethig like this: public bool CaAddAOrder(Customer customer, Order order) //Iit the egie class FluetEgie.Iit() //load assembly ad workflow.loadassembly("crm.bl.wf.dll").loadactivity("caaddaorder.xaml") //prepare the parameters collectio // it should cotais iput/output params.addparameters(ew Dictioary<strig, object> "Order", order, "Customer", customer, "CaAddOrder", false ).Cofigure() //whe the WF is doe.ocomplete((parm) => retur (bool)parm["caaddorder"]; )

166 Sample Code: The Busiess Service Layer 145 //whe the WF raises a error.oerror((ex) => retur false; ).Ru(); This workflow also satisfies the compliace office requiremets for documetig the code ivolved i a busiess trasactio. The previous code should be icluded i a Facade service. The oe used here has IUitOfWork ad the mai etity ivolved i the trasactios ijected at rutime. I the Busiess Layer, I have created a basic service that loads the correct IUitOfWork usig Maaged Extesibility Framework (MEF) (see Chapter 4) at rutime ad the correspodig etity usig geerics. Figure 5-8 shows the basic UML structure of the CRM.BL Layer. Figure 5-8 Structure of a Facade Busiess Service class. The code for the base class is pretty straightforward. You have a geeric class that requires the curret etity as a parameter, which must be of type DomaiObject, ad a IUitOfWork ijected at rutime by the MEF egie. public class BaseFacade<TEtity> where TEtity : DomaiObject /// Gets or sets the uit of work. /// <value>the uit of work.</value> [Import] public IUitOfWork UitOfWork get; private set; /// Gets or sets the etity. /// <value>the etity.</value> public TEtity Etity get; private set;

167 146 Chapter 5 The Busiess Layer /// Iitializes a ew istace of the <see cref="basefacade<tetity>"/> class. /// <param ame="etity">the etity.</param> public BaseFacade(TEtity etity) this.etity = etity; From this geeric service base class, you ca create a specific service class for each etity ad use the UoW or the refereced etity directly withi the service. The followig code, for example, is a Facade service for a Customer etity. It has a method called CaAddAOrder that requires oly the Order etity because the Customer etity is ijected i the costructor. MEF creates the IUitOfWork. Usig this solutio, you ca easily implemet the Trasactio patter, where for a series of busiess steps, you iclude everythig i a busiess trasactio, implemeted i this case by the UoW ad the Try/Catch statemet. public class CustomerFacade : BaseFacade<Customer> public CustomerFacade(Customer customer) : base(customer) public bool CaAddOrder(Order order) try bool result = false; UitOfWork.BegiTrasactio(); //previous code to execute the workflow // result = EXECUTE WORKFLOW if (result) Etity.AddOrder(order); UitOfWork.Update(Etity); UitOfWork.CommitTrasactio(); retur result; catch (Exceptio ex) UitOfWork.RollbackTrasactio(); throw ew ApplicatioExceptio( "The CaAddOrder process has throw a exceptio.", ex);

168 Summary 147 This example forms the startig poit for ay Busiess Service. By followig this approach, you will ed up with two layers; oe (CRM.BL i the sample code) will be the base layer, which cotais all the Facade service classes, the other will be the Workflow Layer (CRM.BL.WF i the sample code), which cotais all the Busiess Rules (Workflows or procedural C# code). I realize that there s a large effort ivolved i placig this logic outside the Domai or the Data Layer, but the advatage of this approach becomes clear as soo as you eed to chage somethig i the applicatio. Remember also that if you keep the busiess logic outside the UI ad outside the Domai, you might be able to recycle it for other applicatios, without the eed to rewrite ay code. Summary The Busiess Layer, also kow as the Busiess Logic Layer, is probably the most complex ad articulated layer of a LOB applicatio. The Busiess Logic Layer is usually divided ito two major parts: Validatio Rules ad Busiess Rules. This cocept is ofte misuderstood by developers, but the parts have two radically differet purposes. Validatio Rules are i charge of validatig the values of a object agaist a set of basic rules, such as regular expressios, ot ullable, strig legth, ad so o. Busiess Rules are composed of rulesets, which defie how a object should behave based o a set of circumstaces or values. You ca establish Validatio Rules easily usig the.net Framework s System.CompoetModel amespace or by usig ay ope source validatio library, such as the VAB from the Eterprise Library 5.0. To implemet Busiess Rules, you ca use oe of the full-featured (but expesive) thirdparty frameworks, or you ca customize the powerful ruleset egie provided with Widows Workflow Foudatio 4.0, as show i this chapter. Although buildig the flexible architecture for the Busiess Layer is time-cosumig, the time you sped buildig the layer is time that you will save i the future, durig applicatio maiteace.

169

170 Chapter 6 The UI Layer with MVVM After completig this chapter, you will be able to: Idetify the parts that compose the MVVM patter. Apply the commad patter ad the WeakEvet maager. Provide additioal services ad facilities for MVVM. I this chapter, you will fially delve ito the Model View ViewModel (MVVM) patter, ad see how it should be implemeted to maitai total separatio betwee the XAML-based UI declarative sytax ad the UI presetatio logic code. As I metioed i Chapter 1, Itroductio to Model View ViewModel ad Lie of Busiess Applicatios, Microsoft itroduced the MVVM patter a few years ago, ad it s still a hot topic of discussio i may user groups ad forums. This chapter icludes more tha just my persoal poit of view about how you should implemet MVVM to fulfill the basic rules that costitute this patter. You wat to implemet the MVVM patter i ay Lie of Busiess (LOB) applicatio built usig Silverlight or Widows Presetatio Foudatio (WPF) because: The whole cliet applicatio should be fully testable, ad to do that, the presetatio logic of the View should be separated from the declarative XAML code that composes it. Usig a presetatio patter such as MVVM puts more of the applicatio s behavior ito o-ui classes that ca be tested more easily. You wat to make the UI desiger s job easier by leavig developmet of the presetatio logic to a differet team/developer. Decouplig the UI logic from the UI declarative markup makes it easy to recycle the ViewModel (the model of the view) for differet views. You ca more easily evolve or chage the UI without chagig the uderlyig presetatio logic of the applicatio usig the power of the DataTemplate ad DataBidig egies provided by XAML markup. Due to its complex structure, a correct implemetatio of the MVVM patter requires a deep uderstadig of how the DataTemplate, DataBidig, Stylig, ad Depedecies mechaisms work i WPF ad Silverlight. However, the purpose of this book is to give you the guidelies for implemetig a LOB applicatio usig the MVVM patter explaiig how these mechaisms work o WPF or Silverlight is beyod the scope of this book. I will provide a 149

171 150 Chapter 6 The UI Layer with MVVM overview of how to use DataTemplate ad Commadig, for example, but if you do t kow these cocepts i depth, especially DataTemplate ad DataBidig, I suggest that you buy a book specifically about the techology you are plaig to use (WPF or Silverlight), ad the study ad experimet with these two complex XAML mechaisms before startig to struggle with the correct implemetatio of MVVM itself. Itroductio to the MVVM Patter Before startig to implemet the MVVM patter, we should see how it works ad what its pricipal compoets are. If you thik about a ormal layered applicatio, you will otice that the UI is composed of four major objects that costitute the lifecycle of a view (see Figure 6-1): the View, which is a graphical object; a Model, which bids to the view ad represets busiess cocepts or etities; a set of cotrols used for iteractios betwee the View ad the user, ad that display data from the Model usig a bidig mechaism; ad a set of evets raised either by the Model or by the user through the View. The View A Model exposed i the View A set of cotrols which display data A user that iteracts with the View FigURe 6-1 The geeral structure of a UI View. To traslate this cocept ito MVVM, you ca say that the View is the XAML UserCotrol/ Page/Widow, which cotais a set of cotrols ad the DataBidig egie. The Model is oe or more Domai Etities exposed by the ViewModel. The ViewModel ecapsulates presetatio logic i a way that s ot specific to the UI, while the View ecapsulates the UI itself. You ca uit test the ViewModel without the eed to resort to complex UI test haresses, because it is just code. Figure 6-2 shows a graphical represetatio of this cocept, usig a simple WPF view.

172 The View 151 The View The associated ViewModel The Routed Commads Figure 6-2 A simple WPF View with a associated ViewModel. Whe you bid the ViewModel to the View, you make the ViewModel s properties ad evets available to the UI so it ca provide a user iterface for them. Iteractios betwee the View ad the ViewModel occur through data bidigs, commads, ad so o. At this poit, the challege is to kow how to customize the DataTemplate of the View to bid these properties correctly, ad of course, which properties to expose i the ViewModel. Data templates are a specific way of defiig the UI without code-behid essetially a way to defie a View so that it is boud to a ViewModel automatically. Data templates are a way to costruct the UI, but they are ot the mai challege. The View I the MVVM patter, the View is the graphical iterface i charge of displayig data to users ad iteractig with them. If you re writig a WPF applicatio, the View might be a UserCotrol, a Widow, or a Page; however, i a Silverlight applicatio, the View will be a Silverlight User Cotrol or a Silverlight Page or a Silverlight Child Widow (a pop-up). To make the View MVVM compatible, you first eed to add a referece to the correspodig ViewModel i the DataCotext of the View. This allows you to start to bid the properties ad commads of the ViewModel to the correspodig cotrols exposed i the View. To do that, you just add a referece to the DataCotext usig a procedural approach, as i the followig code: /// Sets the data source. /// <param ame="datasource">the data source.</param> public void SetViewModel(PersoModel datasource) this.datacotext = datasource;

173 152 Chapter 6 The UI Layer with MVVM Alteratively, you ca add a referece to the DataSource by usig a XAML declarative approach, as i the followig XAML code: <Widow x:class="mvvm.maiwidow" xmls:vm="clr-amespace:mvvm" Title="MaiWidow" Height="250" Width="250"> <Widow.DataCotext> <vm:persoviewmodel /> </Widow.DataCotext> After accomplishig this step, you might safely leave the remaiig work of creatig the layout ad assigig the bidig of the ViewModel properties to the View Cotrols to a UI desiger. Ufortuately, this example does t truly ucouple the View from the ViewModel, ad it also itroduces a costrait betwee the real ViewModel ad the ViewModel the desiger is usig because i this example, they are the same object. A better approach is to create a dummy ViewModel just for the desigers so that they ca cotiue to tweak the UI while you (or somebody else) ca still work o the presetatio logic for that view. Of course, the properties, evets, commads, ad so o provided by the ViewModel represet a cotract to the View. The View ad ViewModel are ot completely ucoupled; they are loosely coupled. If you defie the cotract up frot, the you ca mock out the ViewModel so that the UI desiger ca focus o the UI desig while the developer focuses o implemetig ad uit testig the ViewModel. Bledability: A Dummy ViewModel Before you had off the resposibility of creatig the bidigs to the desigers, you ca make their jobs easier while stayig firmly o the MVVM track by itroducig Microsoft Expressio Bled ad the Expressio SDK ito your process. By doig so, you ca achieve Bledability. Of course, this is just a facy term for eablig desigers to see a accurate preview of their Views i Microsoft Visual Studio ad/or Expressio Bled. Microsoft itroduced a ew amespace for WPF ad Silverlight desigers, which is available at Expressio Bled is a UI desig tool. It has a SDK that provides extesible behaviors. Behaviors are a way to package iteractivity ito re-usable compoets that ca be dragged oto the UI. Expressio Bled also provides a sample data feature that lets desigers desig the UI agaist dummy data. I terms of the MVVM patter, the dummy data provides a mocked-up ViewModel. The followig code adds this amespace to the View usig the des (for desig) prefix: xmls:des=" des:desigwidth="300" des:desigheight="300" des:datacotext="bidig SampleViewModel"

174 The View 153 The code des:datacotext simply allows you to specify a data cotext that will be used at desig time; the real data cotext will be used at rutime. With this techique you ca apply a dummy ViewModel at desig time so that a desiger ca create the UI desig based o dummy data, which of course will be replaced with real data at rutime. The previous code bids the desig-time data cotext of the View to a class called SampleViewModel, Expressio Bled creates a SampleDataSource object that s basically a collectio of properties, which you ca defie, thus allowig the desiger to create a dummy ViewModel with the same properties as the real ViewModel but usig dummy data values. To do that, you eed to create a additioal XAML file to act as the dummy ViewModel, ad the populate it with dummy data (that closely reflects data from the real ViewModel). Desigers use this dummy data file to proceed with the presetatio logic developmet process. For example, the followig is a sample XAML Dummy ViewModel for the Perso view: <vm:customer xmls:vm="clr-amespace:crm.domai.domai;assembly=crm.domai" Title="Mr." FirstName="Joh" LastName="Smith" BirthDate="12/31/1970" IsActive="True"> <vm:customer.cotacts> <vm:cotact Name="Home Phoe" CotactType="Phoe" Number=" " IsDefault="True" /> <vm:cotact Name="Office Phoe" CotactType="Phoe" Number=" " IsDefault="False" /> <vm:cotact Name=" " CotactType=" " Number="joh.smith@ .com" IsDefault="False" /> </vm:customer.cotacts> <vm:customer.addresses> <vm:address AddressLie1="4 Mai Street" City="New York" Coutry="USA" State="NY" ZipCode="11040" /> <vm:address AddressLie1="54 The Road" City="Seattle" Coutry="USA" State="WA" ZipCode="12000" /> </vm:customer.addresses> </vm:customer> The example creates a Customer model istace, because the ViewModel will expose oe istace of this class with its related lists of cotacts ad addresses. The first lie adds a istace of the CRM.Domai.Customer class usig the clr-amespace declaratio that is available i XAML; you use the same declaratio to add a referece i the XAML-based View. Because the Customer model has some child collectios required for the fial View, those are also icluded ad populated with some dummy data. This gives desigers everythig they eed to create the View i Expressio Bled.

175 154 Chapter 6 The UI Layer with MVVM Now that the desigers have everythig i place, they ca bid the dummy ViewModel to the View ad work o the bidig process, the DataTemplate, ad the styles without iterruptig developer work o other parts of the applicatio. The followig code shows the bidig sytax used i the XAML View to cosume the previously created dummy data: <UserCotrol x:class="crm.mvvm.wpf.detailsview.customerdetails" <! OMITTED --> xmls:d=" mc:igorable="d" d:desigheight="500" d:desigwidth="500" DataCotext="Bidig" d:datacotext="d:desigdata Source=/DesigData/CustomerSampleData.xaml"> <UserCotrol.Resources> <! OMITTED --> <StackPael> <TextBlock>First Name :</TextBlock> <TextBox Text="Bidig FirstName"/> <TextBlock>Last Name :</TextBlock> <TextBox Text="Bidig LastName"/> <TextBlock Text="Data of Birth :" /> <DatePickerTextBox Text="Bidig Path=BirthDate.Date, StrigFormat=\0:d\" /> <TextBlock>Is Active :</TextBlock> <CheckBox IsChecked="Bidig IsActive" /> </StackPael> Usig this approach, the desiger ca work directly i either Expressio Bled or Visual Studio to test the UI without actually ruig the applicatio, because the UI reder egie available i Expressio Bled ad Visual Studio ca reder the data at desig time, as show i Figure 6-3. Figure 6-3 A desig-time XAML View usig the DesigData dummy ViewModel. This approach looks pretty coveiet at first glace, so it s worth otig a few possible disadvatages to usig it.

176 The Model 155 First, if you ited to tweak the UI usig the fial ViewModel structure, you eed to create a desig-time ViewModel that represets all the properties, commads, ad behaviors that you pla to expose i the fial ViewModel. Secod, you eed to keep i mid that for huge ViewModels for example a ViewModel that exposes 30 properties, plus commads ad validatio rules creatig a dummy ViewModel will take sigificat time. Fially, remember that it might ot be possible to create a dummy value that matches each property, commad, or behavior if your real ViewModel is complex, so you might eed to thik about other solutios. For example, you might create a complex dummy ViewModel composed of paret ad child ViewModels. Such complexity might be difficult to represet usig XAML markup. The Model As you might have oticed, this chapter has discussed the ViewModel ot the Model discussed i Chapter 3. I fact, the Model is a Domai Etity, declared ad exposed i the Domai Model, ad it should ot be cofused with the ViewModel, which is exposed i the View. Expadig o that further, the Model is the etity i charge of movig data to ad from the data store; that s the object kow to the Data Layer ad the Busiess Layer. By cotrast, the ViewModel is the Model for a View the part of Model exposed for that specific View, icludig the validatio ad behaviors eeded i that specific UI circumstace, plus all the presetatio logic. Figure 6-4 shows the flow of a Model ad why it is ofte so differet from a ViewModel. The view which kows the ViewModel but ot the Model The ViewModel which kows the Model ad how to update it The Model which does t kow the View or the ViewModel The DAL which kows how to save the Model Figure 6-4 The flow used i a MVVM applicatio. Cosider that you will ever implemet a ICommad i the Model, because the Model is ot related to the UI, but you will probably expose the Model directly from the ViewModel to make it easier to create a custom DataTemplate for a specific Domai Etity from your Domai Model. This is a problem that we will aalyze right ow. A commo mistake I ve see

177 156 Chapter 6 The UI Layer with MVVM i MVVM implemetatios is that they pass the Model to the View from the ViewModel, so that (for example) the bidig path of a FirstName property i the Perso model would be exposed i the View i this way: <TextBox Grid.Colum="2" Grid.Row="1" Text="Bidig PersoModel.FirstName" /> I my opiio, rather tha lettig the View bid to the property from the Model directly, the ViewModel should expose its ow, separate property called FirstName that represets the FirstName of the Perso Model: <TextBox Grid.Colum="2" Grid.Row="1" Text="Bidig FirstName" /> Usig this approach, the ViewModel becomes the Model for the View, maskig the real Model. That improves the safety of the applicatio because you re ot exposig the whole Model directly to the View. I additio, it helps ucouple the View from the Model, because the View o loger eeds to kow aythig about the Model directly. Exposig the Model i the ViewModel I have had this discussio i the past with may people. The solutio of exposig the Model directly from the ViewModel, as a public property, ad the bidig it directly to the View is probably the easiest ad fastest solutio but it does t represet the purist way of implemetig a separated presetatio patter, i which the View should be oly loosely coupled to the Model through a specific ViewModel. Istead, the ViewModel should declare its ow properties, hidig the specifics of the Model from the View. This provides the greatest flexibility, ad it helps to prevet ViewModel-type issues from leakig ito the Model classes. You eed to remember that if you pla to expose your Model properties directly ito the View by exposig the Model as a property of the ViewModel, you should implemet the INotifyPropertyChaged iterface i the Domai Etity object, as well, ad ot oly i the ViewModel; otherwise, whe the View chages the Model, the ViewModel will ot be able to see the chage because the bidig egie of WPF or Silverlight will raise a otificatio of the chage. O the other side, usig the approach of rewritig each property of the Model (icludig child ad paret relatioships) iside the correspodig ViewModel is a dautig, time-cosumig, ad error-proe task, which also adds additioal work i terms of testig ad maiteace.

178 The Commad i WPF ad Silverlight 157 At this poit, you re probably woderig which is the best approach. Quite hoestly, there is t a best approach; there are oly differet approaches to the same problem. If you wat to expose the Model directly to the View so that you ca easily write a DataTemplate that represets a Domai Etity, you will eed to pollute your Domai Etities with the INotifyPropertyChaged iterface. O the other had, if you wat to follow the purist way, you will wid up with a lot more code that must be writte ad tested. I would say that the best approach depeds o the complexity ad architecture of your applicatio. The Commad i WPF ad Silverlight Oe of the most iterestig features i WPF ad Silverlight is the ICommad iterface ad how it works. The ICommad iterface exposes Execute ad CaExecute methods that let you cotrol the commad executio. By usig the bidig egie i WPF or Silverlight ad the ICommad implemetatio, you are able to place a ViewModel that exposes ICommad commads i the View, ad bid cotrols such as Butto, Lik, ad so o to these commads. The ICommad lets you cotrol commad executio based o chages that might occur i the ViewModel. For example, you might eable the Save commad o a View oly after the ViewModel has fired the OPropertyChaged() method at least oce. Usually, you will eed to expose these commads i the ViewModel as public properties to properly create the bidig betwee the View ad the ViewModel. Exposig a ICommad property from the ViewModel allows the View to bid to the commad proffered by the ViewModel. You ca implemet the ICommad iterface i a umber of ways. You also eed to implemet some presetatio logic i your ViewModel to decide whether the commad ca or caot be executed. The commo solutio is to simply create a public property of type ICommad i the ViewModel with a private accessor that ca evaluate some presetatio logic iside the ViewModel itself. Aother possible implemetatio is to create a custom class for each commad that iherits from the ICommad iterface ad exposes it i the ViewModel but of course, you would the eed to create a custom commad class for each commad available i the applicatio. You might thik that this approach is time-cosumig ad couterproductive, but for shared commads, such as New, Save, Delete, Udo, or Redo, you will eed to write the custom implemetatio of these commads oly oce. For other commads, you might wish to use the MVVM Commad approach, which is explaied i the ext sectio.

179 158 Chapter 6 The UI Layer with MVVM A Workaroud: A MVVM Commad Silverlight 3 had o support for the Commadig feature that is available i WPF. Ufortuately, Silverlight 4 does t support Commadig i the same way that WPF does, either. But thaks to the ICommad iterface you saw earlier, you ca easily bid a commad to a Meu i Silverlight ad recycle the same commad to bid to a Butto i WPF, without the eed to rewrite ay code. Some third-party tools, such as Prism (Microsoft patters & practices framework), MVVM Light Toolkit (Lauret Bugio's framework), ad Calibur (CodePlex project) have their ow implemetatios of ICommad that you ca recycle i both Silverlight ad WPF applicatios. The code you ll see i this sectio does the same thig by creatig a MVVMCommad that you ca expose i ViewModels rather tha hard-codig a ICommad implemetatio. First, create a ew CRM.MVVM project, which will be the utility framework for the MVVM patter. This is where the project stores some utility classes, which iclude MVVM commad implemetatios for WPF ad Silverlight. The first class we will build is MvvmCommad, which must implemet the ICommad iterface. It defies a geeric Fuctio<T> for the CaExecute evaluatio ad a Delegate<T> for the Execute implemetatio. These methods are ijected ito the costructor of the commad usig the followig code: /// Custom MVVM commad public class MvvmCommad : ICommad private readoly Fuc<object, bool> caexecute; private readoly Actio<object> executeactio; private bool caexecutecache; /// Iitializes a ew istace of the <see cref="mvvmcommad"/> class. /// <param ame="executeactio">the execute actio.</param> /// <param ame="caexecute">the ca execute.</param> public MvvmCommad(Actio<object> executeactio, Fuc<object, bool> caexecute) this.executeactio = executeactio; this.caexecute = caexecute; Of course, this type of implemetatio forces you to implemet the executio logic of the Execute ad the CaExecute method outside of the commad itself probably directly ito the ViewModel that exposes them.

180 The Commad i WPF ad Silverlight 159 First, you implemet the CaExecute method, which evaluates whether a commad ca or caot be executed. This actio is supported by both the WPF ad Silverlight egies but i differet ways. For example, WPF has a Commad Maager class that re-evaluates the UI (ad of course, the boud ViewModel) every time the UI chages. The UI chage fires the reevaluatio of the CaExecute actio automatically. I cotrast, the Silverlight egie does t have a commad maager, so you eed to implemet the re-evaluatio yourself. The followig code represets a simple CaExecute implemetatio that raises a evet every time the commad is re-evaluated: /// Defies the method that determies whether the commad /// ca execute i its curret state. /// <param ame="parameter">data used by the commad. If the commad /// does ot require data to be passed, this object ca be set to ull.</param> /// <returs> /// true if this commad ca be executed; otherwise, false. /// </returs> public bool CaExecute(object parameter) if (CaExecuteChaged!= ull) CaExecuteChaged(this, ew EvetArgs()); retur caexecute(parameter); public evet EvetHadler CaExecuteChaged; Now that you ca evaluate commad executio, you ca simply associate the executio delegate provided i the costructor to the oe required by the ICommad iterface, as follows: /// Defies the method to be called whe the commad is ivoked. /// <param ame="parameter">data used by the commad. If the commad /// does ot require data to be passed, this object ca be set to ull.</param> public void Execute(object parameter) executeactio(parameter); As it is set up here, you ca declare a commad o the ViewModel with a private accessor ad assig two lambda expressios to get a cocrete implemetatio of the MVVM commad i this way: public sealed class PersoViewModel : BaseViewModel<Perso> public ICommad SavePerso get; private set; /// Iitializes a ew istace of the <see cref="persoviewmodel"/> class.

181 160 Chapter 6 The UI Layer with MVVM /// <param ame="model">the model.</param> public PersoViewModel(Perso model) : base(model) /// Iits the commads. private void IitCommads() SavePerso = ew MvvmCommad( (parm) => // execute PersoService.Save(model);, (parm) => // caexecute, ca save if // the model is valid... retur model.isvalid; ); Now, every time you chage the Perso (i this specific case), the UI will re-evaluate the Save commad, ad if the Perso model is ot valid, it will disable the Save butto. You eed oly a fial tweak to fix the problem of Silverlight ot havig a Commad Maager. Re-evaluate ICommad Executio What we ve doe up util ow is pretty cool, flexible, ad testable; we ca create a geeric MvvmCommad, expose it as a ICommad iterface object ad declare the code to execute ad to evaluate the executio usig the aoymous delegate, which is also facy ad pretty readable. At this poit, you'll probably try to create a basic ViewModel object that exposes a couple of properties ad a ICommad property, like the oe i the followig listig, ad you'll bid these properties to a View. What you wat is to eable the FormatCommad property oly if the text i the TextBox is ot ull. The CaExecute method of a ICommad object is executed oly whe the DataBidig egie creates the bidig betwee the UI elemet ad the commad, ad the the commad executio is re-evaluated oly if somethig chages ad the CommadMaager is listeig for that chage. For example, whe you chage the text i the TextBox, the CommadMaager is uaware of the chage, ad it does t update the commad, so the Butto remais disabled.

182 The ViewModel 161 If the code were ot i a ViewModel but i the code-behid for a specific Widow or UserCotrol, you could call the static method CommadMaager.IvalidateRequerySuggested method that raises the RequerySuggested evet, which the re-evaluates all the commads iside the CommadMaager. Ufortuately, if you call this method iside the ViewModel object, it simply does t work because you do t have access directly to the View CommadMaager object. Aother big disadvatage of usig the CommadMaager is that it does t re-evaluate just the executio of oe commad; istead it re-evaluates all the commads attached to the CommadBidig collectio. A possible alterative is to maually re-evaluate the commad each time the OrigialText property chages, such as i the followig code: public strig OrigialText get retur origialtext; set origialtext = value; OPropertyChaged(vm => vm.origialtext); (FormatCommad as MvvmCommad).OCaExecuteChaged(); Aother iterestig alterative would be to make the commad aware of chages that might happe i the ViewModel ad re-execute the OCaExecuteChaged() method if this chage happes i the ViewModel. I other words, that meas makig the ICommad liste for the PropertyChaged evet raised by the ViewModel. The ViewModel Recall that the classic defiitio of a ViewModel i the MVVM patter is that the ViewModel is the Model provided for the View, which is ot ecessarily sufficiet to describe the power this object might acquire durig a applicatio s developmet process. The ViewModel should satisfy four pricipal requiremets: Provide the data that must be exposed i the View Provide a set of commads available i the View Implemet the INotifyPropertyChaged iterface Implemet the IDataErrorIfo iterface Of course, ot all ViewModel implemetatios must satisfy all four requiremets. Depedig o the situatio, it might ot be ecessary for a ViewModel to expose a set of ICommad

183 162 Chapter 6 The UI Layer with MVVM commads, or implemet the IDataErrorIfo iterface (used for UI validatio), or the INotifyPropertyChaged iterface (which raises otificatios about UI chages). The implemetatio of ay give ViewModel depeds upo specific use cases. But all ViewModels will expose at least some values. The previous sectio discussed the pros ad cos of exposig the Model from the ViewModel. For explaatory purposes, I will expose the sample applicatio Domai Etities directly from the ViewModel i the View but that does t mea that you must expose data i your ViewModel usig this approach. The ext sectios explai how you should implemet the four ViewModel requiremets ad how to create some custom base ViewModels that you ca the recycle i your future MVVM applicatios. The INotifyPropertyChaged Iterface The INotifyPropertyChaged iterface has bee available sice the.net Framework versio 2.0. It resides i the System.dll ad is exposed through the amespace System. CompoetModel. INotifyPropertyChaged provides a mechaism for otifyig a cliet or ay other listeer that the value of a property (or of a etire object) has chaged. It exposes a PropertyChaged evet that requires a custom implemetatio i iheritig classes. If you bid a object that implemets this iterface to a XAML datasource, for example, the View will receive a otificatio each time the object chages. I the same way, if you bid such a object to a Widows Form data source, the same behavior will occur without the eed to modify ay code because of the chaged data source. At this poit, you ca thik of ay object that implemets the iterface INotifyPropertyChaged as a Observable object, which is a abstract object type that you ll create here for your MVVM toolkit. The oly requiremet is that the observable object must implemet the INotifyPropertyChaged iterface, which is abstract because it s a base class; you do t wat it to be used directly. Fially, you wat to defie the property that has chaged usig lambda expressios. To start, create a ew class i the CRM.MVVM project ad call it ObservableObject, as show here: public abstract class ObservableObject<T> : INotifyPropertyChaged Every object that implemets this iterface will use itself as <T>. I this way, you ca ow use a lambda expressio trick to auto-resolve the property ame. The ext step is the iterface implemetatio:

184 The ViewModel 163 #regio Implemetatio of INotifyPropertyChaged /// Occurs whe a property value chages. public evet PropertyChagedEvetHadler PropertyChaged; /// Called whe [property chaged]. /// <param ame="property">the property.</param> protected virtual void OPropertyChaged(Expressio<Fuc<T, object>> property) if (property == ull property.body == ull) retur; var memberexp = property.body as MemberExpressio; if (memberexp == ull) retur; PropertyChagedEvetHadler hadler = PropertyChaged; if (hadler!= ull) hadler(this, ew PropertyChagedEvetArgs(memberExp.Member.Name)); #edregio The precedig code declares a PropertyChaged evet, which requires a PropertyChagedEvetArgs argumet that holds the ame of the property that has chaged. The we have the sigature of the OPropertyChaged delegate, which is the method that will be called each time a property chages. Note that this code does t use a compiled lambda expressio result (which is slower), because we wat to read oly the value of the body of the lambda expressio; this techique will ot affect the rutime performace. If there are ay subscribers to the evet, you raise the evet, icludig the property ame. Now we ca implemet this class i our base ViewModel i the followig way: public class BaseViewModel<T> : ObservableObject<BaseViewModel<T>> where T : class public T model; /// Gets or sets the model. /// <value>the model.</value> public T Model

185 164 Chapter 6 The UI Layer with MVVM get retur model; set if (model == value) retur; model = value; OPropertyChaged(vm => vm.model); This example shows a base ViewModel class that requires a geeric <T> model. This is the model that you will expose i the View usig the XAML DataBid egie. If the model chages, it will otify the UI by firig the OPropertyChaged evet. You ca do the same thig with simple properties such as a strig or iteger property exposed through the ViewModel. The IDataErrorIfo Iterface The IDataErrorIfo iterface also resides i the System.CompoetModel amespace. It s iteded to provide specific error iformatio for a object boud to a cliet iterface (a View). This iterface has bee exposed by the.net Framework sice versio 1.0 (although with a differet structure), but it became famous oly whe WPF ad Silverlight appeared. However, you ca easily use it i a Widows cliet or ASP.NET applicatio to implemet data validatio i a View. The iterface exposes two properties: Error ad Item. The Error property represets the curret validatio error. This is most commoly implemeted i the cliet, so you wo t implemet this property i the sample toolkit, because you ll display validatio errors usig the XAML data template, istead. The Item property is ivoked each time a item i the View (which has validatio eabled, so a chage triggers the validatio egie) chages its value ad/or requires validatio. A simple implemetatio of this iterface i the base ViewModel should look somethig like this: /// Gets the <see cref="system.strig"/> with the specified colum ame. /// <value></value> public virtual strig this[strig columname] get var errormessage = strig.empty;

186 switch (columname) case "Model": if (this.model == ull) errormessage = "The View ca t be boud to a empty model."; break; retur errormessage; The ViewModel 165 It should be virtual so that you ca override the implemetatio i each cocrete ViewModel. For example a PersoViewModel might have differet validatio rules. This process is ot terribly productive, it s time-cosumig, ad it s probably redudat, because you might already have some validatio rules applied to the uderlyig model. A smarter way to accomplish this task is to use the Microsoft Eterprise Library that you saw i Chapter 5, The Busiess Layer, to self-validate both the ViewModel ad the uderlyig model, which already has validatio rules. To do that, you first eed a ViewModelValidator class that you ca call wheever you eed to validate a ViewModel property or validate a etire object. The Validatio Applicatio Block (VAB) provided with the Eterprise Library offers a eat ad easy way to validate a object, so I suggest that you use it, ad verify that ay validatio errors that occur are related to the property we are tryig to validate. Here s the code for validatig a field: public sealed class ViewModelValidator /// Validates the field. /// <param ame="etity">the etity.</param> /// <param ame="field">the field.</param> /// <returs></returs> public static strig ValidateField<T>(T etity, strig field) var validatioresults = ValidatioFactory.CreateValidator<T>().Validate(etity); var errormessage = ew StrigBuilder(); // if the etity is valid we do t go ahead if (validatioresults.isvalid) retur errormessage.tostrig(); // verify that the errors are for this field var errors = validatioresults.where(x => x.key == field); if (errors.cout() > 0)

187 166 Chapter 6 The UI Layer with MVVM foreach (var validatioresult i errors) errormessage.appedlie(validatioresult.message); // retur the error message as a strig with \r\ retur errormessage.tostrig(); Ad this is the chage i the base ViewModel: /// Gets the <see cref="system.strig"/> with the specified colum ame. /// <value></value> public virtual strig this[strig columname] get retur ViewModelValidator.ValidateField(this, columname); Now the trick is to bid the ViewModel to a View ad create a specific visual method for example a TextBox to display ay errors geerated durig the validatio process. Figure 6-5 presets a fuctioal validatio style that uses a WPF TextBox. Figure 6-5 Validatio template applied o a WPF TextBox. To see more iformatio about the validatio template, examie the Validatio.ErrorTemplate attached property. This property lets you defie a specific template for a cotrol to display a validatio error.

188 DataTemplate i WPF ad Silverlight 167 Of course, to raise the validatio i the first place, you eed to defie the bidig as show i the followig code example, specifyig the ValidatesODataErrors ad ValidateOExceptios attributes to make the bidig egie aware of the validatio availability i the DataCotext: <TextBox Text=" Bidig ValidatesODataErrors=True, Path=FirstName, ValidatesOExceptios=True "> </TextBox> DataTemplate i WPF ad Silverlight Aother importat aspect of the WPF/Silverlight UI egie is the DataTemplate, which describes how to reder data that is boud to a cotrol by specifyig how the data will be redered. Widows Forms does t have a easy way to customize the items exposed by a list cotrol, such as a Listbox, so you had to create a custom property i the Model exposed i the DataSource of the cotrol i order to use it as a Display property of that cotrol. With WPF or Silverlight, however, you ca easily bid a Perso class to a UserCotrol, ad bid a collectio property from that class, such as a list of addresses, to a Listbox. By customizig the data template, you ca cause the ListBox UI to look like a simple Grid ad avoid usig a more complex Grid cotrol. The followig code uses a DataTemplate to display three properties of a Address etity i a ListBox: <ListBox ItemsSource="Bidig Cotacts" Grid.Colum="5" Grid.ColumSpa="3" Grid.Row="2" Grid.RowSpa="3"> <ListBox.ItemTemplate> <DataTemplate> <StackPael Orietatio="Horizotal"> <TextBlock Text="Bidig Name" /> <TextBlock Text=" : " /> <TextBlock Text="Bidig Number" /> </StackPael> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Aother iterestig approach would be to have a IList<ICommad> exposed i the ViewModel. The, usig the DataTemplate, you could create a dyamic list of buttos or a list of commads i a Commad Bar, resultig i a extremely dyamic View.

189 168 Chapter 6 The UI Layer with MVVM DataTemplate ad MVVM Why is the DataTemplate so importat for the MVVM Patter? The pricipal purpose of the MVVM patter or more accurately, oe of the primary reasos for usig the MVVM patter is to separate presetatio logic from UI logic so that your ViewModels ca be loosely coupled ad reusable. If you use a DataTemplate to display the data exposed by the ViewModel i the View, you ll wid up with more flexibility i the future for chagig ad adaptig that View to a ew desig requiremet or to a ew cliet techology, such as from WPF to Silverlight. Also, because a DataTemplate is essetially a View without code-behid, you ca bid the UI directly agaist a ViewModel ad apply a DataTemplate, which the becomes the View to the ViewModel. Refer back to Figure 6-3, which represets a Customer Details View boud to a CustomerViewModel. How may times are you likely to use this View? I a real-world CRM applicatio, you would probably use this View several times; for example, to represet a selected customer, to create a ew customer, to display the customer details i a order view, ad so o. You ca see that this approach could be very time-cosumig; you would eed to apply the same validatio rules ad write the same XAML view repeatedly. Usig a DataTemplate, you ca create a simple UserCotrol i both Silverlight ad WPF, bid it to a CustomerViewModel, ad the add a referece to that DataTemplate to ay View that requires it, thus savig time ad makig the code more reusable. WeakEvets ad Messages If you are familiar with evet programmig with.net, you might already kow what a evet is ad how paiful it ca be to create ad destroy evets attached to a specific form. With WPF ad.net Framework 4, Microsoft has itroduced a ew type of evet called WeakEvet, which implemets the Weak Evet desig patter a mechaism that is able to self-maage the evet subscriptio ad cacellatio process. You ca accomplish the same result i Silverlight, as you ll see later i this sectio. The WeakEvet Patter I the old-fashioed style of maagig evets, the lifecycle of a object that listes for a evet (the listeer) might be differet tha expected because it s drive by the lifecycle of the object raisig the evet (the source). I this case, the oly possible solutio is to remove the listeer from the source declaratively, by detachig the evet hadler from the source.

190 WeakEvets ad Messages 169 With.NET 4 you ca ow use two differet objects to implemet the WeakEvet patter: WeakEvetMaager, a class that you should iherit to create a custom evet maager, ad IWeakEvetListeer, a iterface that ay listeer for a weak evet should implemet. Figure 6-6 displays the basic implemetatio of the WeakEvet patter i.net. FigURe 6-6 WeakEvet patter implemetatio. As illustrated i Figure 6-6, this implemetatio is both time-cosumig ad verbose, especially whe you realize that this implemetatio should be applied to every evet that you wat to liste for from the UI. At this poit, you will probably wat to move to a more geeric solutio (available i the dowloadable compaio source code for this book) ad create a factory that is able to subscribe ad remove listeers to a evet usig lambda expressios ad delegates. The fial result looks like this: MyEvetFactory.Liste<MyEvetHadler>( () => // implemet evet here ); Ufortuately, that solutio rus ito aother.net problem, because it s difficult (if ot impossible) to subscribe ad usubscribe to a evet eve a weak evet usig lambda expressio sytax. So you might wat to skip this altogether ad cosider adoptig a more reliable solutio: the Messagig patter. The EvetAggregator Patter I always followed with pleasure ay guidace provided by Microsoft s patters & practices team, especially the Smart Cliet Software Factory (SCSF). I kow it was desiged

ODBC. Getting Started With Sage Timberline Office ODBC

ODBC. Getting Started With Sage Timberline Office ODBC ODBC Gettig Started With Sage Timberlie Office ODBC NOTICE This documet ad the Sage Timberlie Office software may be used oly i accordace with the accompayig Sage Timberlie Office Ed User Licese Agreemet.

More information

BaanERP. BaanERP Windows Client Installation Guide

BaanERP. BaanERP Windows Client Installation Guide BaaERP A publicatio of: Baa Developmet B.V. P.O.Box 143 3770 AC Bareveld The Netherlads Prited i the Netherlads Baa Developmet B.V. 1999. All rights reserved. The iformatio i this documet is subject to

More information

Baan Service Master Data Management

Baan Service Master Data Management Baa Service Master Data Maagemet Module Procedure UP069A US Documetiformatio Documet Documet code : UP069A US Documet group : User Documetatio Documet title : Master Data Maagemet Applicatio/Package :

More information

Domain 1: Identifying Cause of and Resolving Desktop Application Issues Identifying and Resolving New Software Installation Issues

Domain 1: Identifying Cause of and Resolving Desktop Application Issues Identifying and Resolving New Software Installation Issues Maual Widows 7 Eterprise Desktop Support Techicia (70-685) 1-800-418-6789 Domai 1: Idetifyig Cause of ad Resolvig Desktop Applicatio Issues Idetifyig ad Resolvig New Software Istallatio Issues This sectio

More information

Engineering Data Management

Engineering Data Management BaaERP 5.0c Maufacturig Egieerig Data Maagemet Module Procedure UP128A US Documetiformatio Documet Documet code : UP128A US Documet group : User Documetatio Documet title : Egieerig Data Maagemet Applicatio/Package

More information

PUBLIC RELATIONS PROJECT 2016

PUBLIC RELATIONS PROJECT 2016 PUBLIC RELATIONS PROJECT 2016 The purpose of the Public Relatios Project is to provide a opportuity for the chapter members to demostrate the kowledge ad skills eeded i plaig, orgaizig, implemetig ad evaluatig

More information

(VCP-310) 1-800-418-6789

(VCP-310) 1-800-418-6789 Maual VMware Lesso 1: Uderstadig the VMware Product Lie I this lesso, you will first lear what virtualizatio is. Next, you ll explore the products offered by VMware that provide virtualizatio services.

More information

Professional Networking

Professional Networking Professioal Networkig 1. Lear from people who ve bee where you are. Oe of your best resources for etworkig is alumi from your school. They ve take the classes you have take, they have bee o the job market

More information

Domain 1: Designing a SQL Server Instance and a Database Solution

Domain 1: Designing a SQL Server Instance and a Database Solution Maual SQL Server 2008 Desig, Optimize ad Maitai (70-450) 1-800-418-6789 Domai 1: Desigig a SQL Server Istace ad a Database Solutio Desigig for CPU, Memory ad Storage Capacity Requiremets Whe desigig a

More information

Building Enterprise Applications with Windows* Presentation Foundation and the Model View ViewModel Pattern

Building Enterprise Applications with Windows* Presentation Foundation and the Model View ViewModel Pattern Microsoft* Building Enterprise Applications with Windows* Presentation Foundation and the Model View ViewModel Pattern Raffaele Garofalo Contents at a Glance 1 Introduction to Model View ViewModel and

More information

*The most important feature of MRP as compared with ordinary inventory control analysis is its time phasing feature.

*The most important feature of MRP as compared with ordinary inventory control analysis is its time phasing feature. Itegrated Productio ad Ivetory Cotrol System MRP ad MRP II Framework of Maufacturig System Ivetory cotrol, productio schedulig, capacity plaig ad fiacial ad busiess decisios i a productio system are iterrelated.

More information

IT Support. 020 8269 6878 n www.premierchoiceinternet.com n support@premierchoiceinternet.com. 30 Day FREE Trial. IT Support from 8p/user

IT Support. 020 8269 6878 n www.premierchoiceinternet.com n support@premierchoiceinternet.com. 30 Day FREE Trial. IT Support from 8p/user IT Support IT Support Premier Choice Iteret has bee providig reliable, proactive & affordable IT Support solutios to compaies based i Lodo ad the South East of Eglad sice 2002. Our goal is to provide our

More information

CCH Accountants Starter Pack

CCH Accountants Starter Pack CCH Accoutats Starter Pack We may be a bit smaller, but fudametally we re o differet to ay other accoutig practice. Util ow, smaller firms have faced a stark choice: Buy cheaply, kowig that the practice

More information

CREATIVE MARKETING PROJECT 2016

CREATIVE MARKETING PROJECT 2016 CREATIVE MARKETING PROJECT 2016 The Creative Marketig Project is a chapter project that develops i chapter members a aalytical ad creative approach to the marketig process, actively egages chapter members

More information

Configuring Additional Active Directory Server Roles

Configuring Additional Active Directory Server Roles Maual Upgradig your MCSE o Server 2003 to Server 2008 (70-649) 1-800-418-6789 Cofigurig Additioal Active Directory Server Roles Active Directory Lightweight Directory Services Backgroud ad Cofiguratio

More information

Business Rules-Driven SOA. A Framework for Multi-Tenant Cloud Computing

Business Rules-Driven SOA. A Framework for Multi-Tenant Cloud Computing Lect. Phd. Liviu Gabriel CRETU / SPRERS evet Traiig o software services, Timisoara, Romaia, 6-10 dec 2010 www.feaa.uaic.ro Busiess Rules-Drive SOA. A Framework for Multi-Teat Cloud Computig Lect. Ph.D.

More information

A guide to School Employees' Well-Being

A guide to School Employees' Well-Being A guide to School Employees' Well-Beig Backgroud The public school systems i the Uited States employ more tha 6.7 millio people. This large workforce is charged with oe of the atio s critical tasks to

More information

INVESTMENT PERFORMANCE COUNCIL (IPC) Guidance Statement on Calculation Methodology

INVESTMENT PERFORMANCE COUNCIL (IPC) Guidance Statement on Calculation Methodology Adoptio Date: 4 March 2004 Effective Date: 1 Jue 2004 Retroactive Applicatio: No Public Commet Period: Aug Nov 2002 INVESTMENT PERFORMANCE COUNCIL (IPC) Preface Guidace Statemet o Calculatio Methodology

More information

SECTION 1.5 : SUMMATION NOTATION + WORK WITH SEQUENCES

SECTION 1.5 : SUMMATION NOTATION + WORK WITH SEQUENCES SECTION 1.5 : SUMMATION NOTATION + WORK WITH SEQUENCES Read Sectio 1.5 (pages 5 9) Overview I Sectio 1.5 we lear to work with summatio otatio ad formulas. We will also itroduce a brief overview of sequeces,

More information

In nite Sequences. Dr. Philippe B. Laval Kennesaw State University. October 9, 2008

In nite Sequences. Dr. Philippe B. Laval Kennesaw State University. October 9, 2008 I ite Sequeces Dr. Philippe B. Laval Keesaw State Uiversity October 9, 2008 Abstract This had out is a itroductio to i ite sequeces. mai de itios ad presets some elemetary results. It gives the I ite Sequeces

More information

Desktop Management. Desktop Management Tools

Desktop Management. Desktop Management Tools Desktop Maagemet 9 Desktop Maagemet Tools Mac OS X icludes three desktop maagemet tools that you might fid helpful to work more efficietly ad productively: u Stacks puts expadable folders i the Dock. Clickig

More information

TruStore: The storage. system that grows with you. Machine Tools / Power Tools Laser Technology / Electronics Medical Technology

TruStore: The storage. system that grows with you. Machine Tools / Power Tools Laser Technology / Electronics Medical Technology TruStore: The storage system that grows with you Machie Tools / Power Tools Laser Techology / Electroics Medical Techology Everythig from a sigle source. Cotets Everythig from a sigle source. 2 TruStore

More information

Unicenter TCPaccess FTP Server

Unicenter TCPaccess FTP Server Uiceter TCPaccess FTP Server Release Summary r6.1 SP2 K02213-2E This documetatio ad related computer software program (hereiafter referred to as the Documetatio ) is for the ed user s iformatioal purposes

More information

Agenda. Outsourcing and Globalization in Software Development. Outsourcing. Outsourcing here to stay. Outsourcing Alternatives

Agenda. Outsourcing and Globalization in Software Development. Outsourcing. Outsourcing here to stay. Outsourcing Alternatives Outsourcig ad Globalizatio i Software Developmet Jacques Crocker UW CSE Alumi 2003 jc@cs.washigto.edu Ageda Itroductio The Outsourcig Pheomeo Leadig Offshore Projects Maagig Customers Offshore Developmet

More information

Making training work for your business

Making training work for your business Makig traiig work for your busiess Itegratig core skills of laguage, literacy ad umeracy ito geeral workplace traiig makes sese. The iformatio i this pamphlet will help you pla for ad build a successful

More information

How to use what you OWN to reduce what you OWE

How to use what you OWN to reduce what you OWE How to use what you OWN to reduce what you OWE Maulife Oe A Overview Most Caadias maage their fiaces by doig two thigs: 1. Depositig their icome ad other short-term assets ito chequig ad savigs accouts.

More information

Domain 1: Configuring Domain Name System (DNS) for Active Directory

Domain 1: Configuring Domain Name System (DNS) for Active Directory Maual Widows Domai 1: Cofigurig Domai Name System (DNS) for Active Directory Cofigure zoes I Domai Name System (DNS), a DNS amespace ca be divided ito zoes. The zoes store ame iformatio about oe or more

More information

Determining the sample size

Determining the sample size Determiig the sample size Oe of the most commo questios ay statisticia gets asked is How large a sample size do I eed? Researchers are ofte surprised to fid out that the aswer depeds o a umber of factors

More information

Example 2 Find the square root of 0. The only square root of 0 is 0 (since 0 is not positive or negative, so those choices don t exist here).

Example 2 Find the square root of 0. The only square root of 0 is 0 (since 0 is not positive or negative, so those choices don t exist here). BEGINNING ALGEBRA Roots ad Radicals (revised summer, 00 Olso) Packet to Supplemet the Curret Textbook - Part Review of Square Roots & Irratioals (This portio ca be ay time before Part ad should mostly

More information

Ideate, Inc. Training Solutions to Give you the Leading Edge

Ideate, Inc. Training Solutions to Give you the Leading Edge Ideate, Ic. Traiig News 2014v1 Ideate, Ic. Traiig Solutios to Give you the Leadig Edge New Packages For All Your Traiig Needs! Bill Johso Seior MEP - Applicatio Specialist Revit MEP Fudametals Ad More!

More information

leasing Solutions We make your Business our Business

leasing Solutions We make your Business our Business if you d like to discover how Bp paribas leasig Solutios Ca help you to achieve your goals please get i touch leasig Solutios We make your Busiess our Busiess We look forward to hearig from you you ca

More information

AGC s SUPERVISORY TRAINING PROGRAM

AGC s SUPERVISORY TRAINING PROGRAM AGC s SUPERVISORY TRAINING PROGRAM Learig Today...Leadig Tomorrow The Kowledge ad Skills Every Costructio Supervisor Must Have to be Effective The Associated Geeral Cotractors of America s Supervisory

More information

Digital Enterprise Unit. White Paper. Web Analytics Measurement for Responsive Websites

Digital Enterprise Unit. White Paper. Web Analytics Measurement for Responsive Websites Digital Eterprise Uit White Paper Web Aalytics Measuremet for Resposive Websites About the Authors Vishal Machewad Vishal Machewad has over 13 years of experiece i sales ad marketig, havig worked as a

More information

Flood Emergency Response Plan

Flood Emergency Response Plan Flood Emergecy Respose Pla This reprit is made available for iformatioal purposes oly i support of the isurace relatioship betwee FM Global ad its cliets. This iformatio does ot chage or supplemet policy

More information

Amendments to employer debt Regulations

Amendments to employer debt Regulations March 2008 Pesios Legal Alert Amedmets to employer debt Regulatios The Govermet has at last issued Regulatios which will amed the law as to employer debts uder s75 Pesios Act 1995. The amedig Regulatios

More information

Handling. Collection Calls

Handling. Collection Calls Hadlig the Collectio Calls We do everythig we ca to stop collectio calls; however, i the early part of our represetatio, you ca expect some of these calls to cotiue. We uderstad that the first few moths

More information

Enhancing Oracle Business Intelligence with cubus EV How users of Oracle BI on Essbase cubes can benefit from cubus outperform EV Analytics (cubus EV)

Enhancing Oracle Business Intelligence with cubus EV How users of Oracle BI on Essbase cubes can benefit from cubus outperform EV Analytics (cubus EV) Ehacig Oracle Busiess Itelligece with cubus EV How users of Oracle BI o Essbase cubes ca beefit from cubus outperform EV Aalytics (cubus EV) CONTENT 01 cubus EV as a ehacemet to Oracle BI o Essbase 02

More information

Authentication - Access Control Default Security Active Directory Trusted Authentication Guest User or Anonymous (un-authenticated) Logging Out

Authentication - Access Control Default Security Active Directory Trusted Authentication Guest User or Anonymous (un-authenticated) Logging Out FME Server Security Table of Cotets FME Server Autheticatio - Access Cotrol Default Security Active Directory Trusted Autheticatio Guest User or Aoymous (u-autheticated) Loggig Out Authorizatio - Roles

More information

Domain 1 Components of the Cisco Unified Communications Architecture

Domain 1 Components of the Cisco Unified Communications Architecture Maual CCNA Domai 1 Compoets of the Cisco Uified Commuicatios Architecture Uified Commuicatios (UC) Eviromet Cisco has itroduced what they call the Uified Commuicatios Eviromet which is used to separate

More information

PENSION ANNUITY. Policy Conditions Document reference: PPAS1(7) This is an important document. Please keep it in a safe place.

PENSION ANNUITY. Policy Conditions Document reference: PPAS1(7) This is an important document. Please keep it in a safe place. PENSION ANNUITY Policy Coditios Documet referece: PPAS1(7) This is a importat documet. Please keep it i a safe place. Pesio Auity Policy Coditios Welcome to LV=, ad thak you for choosig our Pesio Auity.

More information

Confidence Intervals for One Mean

Confidence Intervals for One Mean Chapter 420 Cofidece Itervals for Oe Mea Itroductio This routie calculates the sample size ecessary to achieve a specified distace from the mea to the cofidece limit(s) at a stated cofidece level for a

More information

A Balanced Scorecard

A Balanced Scorecard A Balaced Scorecard with VISION A Visio Iteratioal White Paper Visio Iteratioal A/S Aarhusgade 88, DK-2100 Copehage, Demark Phoe +45 35430086 Fax +45 35434646 www.balaced-scorecard.com 1 1. Itroductio

More information

InventoryControl. The Complete Inventory Tracking Solution for Small Businesses

InventoryControl. The Complete Inventory Tracking Solution for Small Businesses IvetoryCotrol The Complete Ivetory Trackig Solutio for Small Busiesses Regular Logo 4C Productivity Solutios for Small Busiesses Logo Outlie Get i cotrol of your ivetory with Wasp Ivetory Cotrol the complete

More information

Introducing Rational Suite

Introducing Rational Suite Itroducig Ratioal Suite Product Versio Ratioal Suite 2000.02.10 Release Date April 2000 Part Number 800-023314-000 support@ratioal.com http://www.ratioal.com IMPORTANT NOTICE Copyright Notice Copyright

More information

CHAPTER 3 THE TIME VALUE OF MONEY

CHAPTER 3 THE TIME VALUE OF MONEY CHAPTER 3 THE TIME VALUE OF MONEY OVERVIEW A dollar i the had today is worth more tha a dollar to be received i the future because, if you had it ow, you could ivest that dollar ad ear iterest. Of all

More information

A GUIDE TO BUILDING SMART BUSINESS CREDIT

A GUIDE TO BUILDING SMART BUSINESS CREDIT A GUIDE TO BUILDING SMART BUSINESS CREDIT Establishig busiess credit ca be the key to growig your compay DID YOU KNOW? Busiess Credit ca help grow your busiess Soud paymet practices are key to a solid

More information

To c o m p e t e in t o d a y s r e t a i l e n v i r o n m e n t, y o u n e e d a s i n g l e,

To c o m p e t e in t o d a y s r e t a i l e n v i r o n m e n t, y o u n e e d a s i n g l e, Busiess Itelligece Software for Retail To c o m p e t e i t o d a y s r e t a i l e v i r o m e t, y o u e e d a s i g l e, comprehesive view of your busiess. You have to tur the decisio-makig of your

More information

Creating an Agile BI Environment

Creating an Agile BI Environment White Paper Creatig a Agile BI Eviromet The rapidly chagig IT ecoomy has iflueced the Busiess Itelligece (BI) systems to look at iovative ways to be equally fast ad flexible. There is a eed to be more

More information

INDEPENDENT BUSINESS PLAN EVENT 2016

INDEPENDENT BUSINESS PLAN EVENT 2016 INDEPENDENT BUSINESS PLAN EVENT 2016 The Idepedet Busiess Pla Evet ivolves the developmet of a comprehesive proposal to start a ew busiess. Ay type of busiess may be used. The Idepedet Busiess Pla Evet

More information

For customers Key features of the Guaranteed Pension Annuity

For customers Key features of the Guaranteed Pension Annuity For customers Key features of the Guarateed Pesio Auity The Fiacial Coduct Authority is a fiacial services regulator. It requires us, Aego, to give you this importat iformatio to help you to decide whether

More information

STUDENTS PARTICIPATION IN ONLINE LEARNING IN BUSINESS COURSES AT UNIVERSITAS TERBUKA, INDONESIA. Maya Maria, Universitas Terbuka, Indonesia

STUDENTS PARTICIPATION IN ONLINE LEARNING IN BUSINESS COURSES AT UNIVERSITAS TERBUKA, INDONESIA. Maya Maria, Universitas Terbuka, Indonesia STUDENTS PARTICIPATION IN ONLINE LEARNING IN BUSINESS COURSES AT UNIVERSITAS TERBUKA, INDONESIA Maya Maria, Uiversitas Terbuka, Idoesia Co-author: Amiuddi Zuhairi, Uiversitas Terbuka, Idoesia Kuria Edah

More information

HP Asset Manager. Software version: 5.20. Service Asset and Configuration Management

HP Asset Manager. Software version: 5.20. Service Asset and Configuration Management HP Asset Maager Software versio: 5.20 Service Asset ad Cofiguratio Maagemet Documet Release Date: 01 October 2009 Software Release Date: October 2009 Legal Notices Copyright Notices Copyright 1994-2009

More information

Neolane Leads. Neolane v6.1

Neolane Leads. Neolane v6.1 Neolae Leads Neolae v6.1 This documet, ad the software it describes, are provided subject to a Licese Agreemet ad may ot be used or copied outside of the provisios of the Licese Agreemet. No part of this

More information

optimise your investment in Microsoft technology. Microsoft Consulting Services from CIBER

optimise your investment in Microsoft technology. Microsoft Consulting Services from CIBER optimise your ivestmet i Microsoft techology. Microsoft Cosultig Services from Microsoft Cosultig Services from MICROSOFT CONSULTING SERVICES ca help with ay stage i the lifecycle of adoptig Microsoft

More information

One Goal. 18-Months. Unlimited Opportunities.

One Goal. 18-Months. Unlimited Opportunities. 18 fast-track 18-Moth BACHELOR S DEGREE completio PROGRAMS Oe Goal. 18-Moths. Ulimited Opportuities. www.ortheaster.edu/cps Fast-Track Your Bachelor s Degree ad Career Goals Complete your bachelor s degree

More information

CCH Accounts Production

CCH Accounts Production CCH Accouts Productio accouts productio facig today s challeges Preparig statutory ad fiacial accouts is a core activity for our practice, as it is for may professioal firms. Although legislatio ad accoutig

More information

Conversion Instructions:

Conversion Instructions: Coversio Istructios: QMS magicolor 2 DeskLaser to QMS magicolor 2 CX 1800502-001A Trademarks QMS, the QMS logo, ad magicolor are registered trademarks of QMS, Ic., registered i the Uited States Patet ad

More information

Safety Requirements engineering and Proof of implementation

Safety Requirements engineering and Proof of implementation Presetatio to DVClub commuity October 20 th 2015 Safety Requiremets egieerig ad Proof of implemetatio Test ad Verificatio Solutios Deliverig Tailored Solutios for Hardware Verificatio ad Software Testig

More information

WindWise Education. 2 nd. T ransforming the Energy of Wind into Powerful Minds. editi. A Curriculum for Grades 6 12

WindWise Education. 2 nd. T ransforming the Energy of Wind into Powerful Minds. editi. A Curriculum for Grades 6 12 WidWise Educatio T rasformig the Eergy of Wid ito Powerful Mids A Curriculum for Grades 6 12 Notice Except for educatioal use by a idividual teacher i a classroom settig this work may ot be reproduced

More information

Comparing Credit Card Finance Charges

Comparing Credit Card Finance Charges Comparig Credit Card Fiace Charges Comparig Credit Card Fiace Charges Decidig if a particular credit card is right for you ivolves uderstadig what it costs ad what it offers you i retur. To determie how

More information

Supply Chain Management

Supply Chain Management Supply Chai Maagemet LOA Uiversity October 9, 205 Distributio D Distributio Authorized to Departmet of Defese ad U.S. DoD Cotractors Oly Aim High Fly - Fight - Wi Who am I? Dr. William A Cuigham PhD Ecoomics

More information

Mathematical goals. Starting points. Materials required. Time needed

Mathematical goals. Starting points. Materials required. Time needed Level A1 of challege: C A1 Mathematical goals Startig poits Materials required Time eeded Iterpretig algebraic expressios To help learers to: traslate betwee words, symbols, tables, ad area represetatios

More information

Agency Relationship Optimizer

Agency Relationship Optimizer Decideware Developmet Agecy Relatioship Optimizer The Leadig Software Solutio for Cliet-Agecy Relatioship Maagemet supplier performace experts scorecards.deploymet.service decide ware Sa Fracisco Sydey

More information

The Big Picture: An Introduction to Data Warehousing

The Big Picture: An Introduction to Data Warehousing Chapter 1 The Big Picture: A Itroductio to Data Warehousig Itroductio I 1977, Jimmy Carter was Presidet of the Uited States, Star Wars hit the big scree, ad Apple Computer, Ic. itroduced the world to the

More information

Get advice now. Are you worried about your mortgage? New edition

Get advice now. Are you worried about your mortgage? New edition New editio Jauary 2009 Are you worried about your mortgage? Get advice ow If you are strugglig to pay your mortgage, or you thik it will be difficult to pay more whe your fixed-rate deal eds, act ow to

More information

Information about Bankruptcy

Information about Bankruptcy Iformatio about Bakruptcy Isolvecy Service of Irelad Seirbhís Dócmhaieachta a héirea Isolvecy Service of Irelad Seirbhís Dócmhaieachta a héirea What is the? The Isolvecy Service of Irelad () is a idepedet

More information

Information for Programs Seeking Initial Accreditation

Information for Programs Seeking Initial Accreditation Iformatio for Programs Seekig Iitial Accreditatio Aswers to Frequetly- Asked-Questios (from www.abet.org/ew-to-accreditatio/) Assurig Quality l Stimulatig Iovatio This documet iteds to aswer may of the

More information

WE KEEP GOOD COMPANY REVITALIZING STORES FOR BIG BRAND FRANCHISES CFG. Recapitalization. Growth Capital CAROLINA FINANCIAL GROUP

WE KEEP GOOD COMPANY REVITALIZING STORES FOR BIG BRAND FRANCHISES CFG. Recapitalization. Growth Capital CAROLINA FINANCIAL GROUP REVITALIZING STORES FOR BIG BRAND FRANCHISES Recapitalizatio Frachise ad Restaurats Growth Capital I ve spet my career buildig valuable restaurat frachises for some of the top QSR brads i America. We eeded

More information

ContactPro Desktop for Multi-Media Contact Center

ContactPro Desktop for Multi-Media Contact Center CotactPro Desktop for Multi-Media Cotact Ceter CCT CotactPro (CP) is the perfect solutio for the aget desktop i a Avaya multimedia call ceter eviromet. CotactPro empowers agets to efficietly serve customers

More information

Best of security and convenience

Best of security and convenience Get More with Additioal Cardholders. Importat iformatio. Add a co-applicat or authorized user to your accout ad you ca take advatage of the followig beefits: RBC Royal Bak Visa Customer Service Cosolidate

More information

E-Plex Enterprise Access Control System

E-Plex Enterprise Access Control System Eterprise Access Cotrol System Egieered for Flexibility Modular Solutio The Eterprise Access Cotrol System is a modular solutio for maagig access poits. Employig a variety of hardware optios, system maagemet

More information

6. p o s I T I v e r e I n f o r c e M e n T

6. p o s I T I v e r e I n f o r c e M e n T 6. p o s I T I v e r e I f o r c e M e T The way positive reiforcemet is carried out is more importat tha the amout. B.F. Skier We all eed positive reiforcemet. Whether or ot we are cosciously aware of

More information

7.1 Finding Rational Solutions of Polynomial Equations

7.1 Finding Rational Solutions of Polynomial Equations 4 Locker LESSON 7. Fidig Ratioal Solutios of Polyomial Equatios Name Class Date 7. Fidig Ratioal Solutios of Polyomial Equatios Essetial Questio: How do you fid the ratioal roots of a polyomial equatio?

More information

CDs Bought at a Bank verses CD s Bought from a Brokerage. Floyd Vest

CDs Bought at a Bank verses CD s Bought from a Brokerage. Floyd Vest CDs Bought at a Bak verses CD s Bought from a Brokerage Floyd Vest CDs bought at a bak. CD stads for Certificate of Deposit with the CD origiatig i a FDIC isured bak so that the CD is isured by the Uited

More information

GOOD PRACTICE CHECKLIST FOR INTERPRETERS WORKING WITH DOMESTIC VIOLENCE SITUATIONS

GOOD PRACTICE CHECKLIST FOR INTERPRETERS WORKING WITH DOMESTIC VIOLENCE SITUATIONS GOOD PRACTICE CHECKLIST FOR INTERPRETERS WORKING WITH DOMESTIC VIOLENCE SITUATIONS I the sprig of 2008, Stadig Together agaist Domestic Violece carried out a piece of collaborative work o domestic violece

More information

FIRE PROTECTION SYSTEM INSPECTION, TESTING AND MAINTENANCE PROGRAMS

FIRE PROTECTION SYSTEM INSPECTION, TESTING AND MAINTENANCE PROGRAMS STRATEGIC OUTCOMES PRACTICE TECHNICAL ADVISORY BULLETIN February 2011 FIRE PROTECTION SYSTEM INSPECTION, TESTING AND MAINTENANCE PROGRAMS www.willis.com Natioal Fire Protectio Associatio (NFPA) #25 a mai

More information

Patentability of Computer Software and Business Methods

Patentability of Computer Software and Business Methods WIPO-MOST Itermediate Traiig Course o Practical Itellectual Property Issues i Busiess November 10 to 14, 2003 Patetability of Computer Software ad Busiess Methods Tomoko Miyamoto Patet Law Sectio Patet

More information

Business Application Services. Business Applications that provide value to your enterprise.

Business Application Services. Business Applications that provide value to your enterprise. Busiess Applicatio Services Busiess Applicatios that provide value to your eterprise. Sesiple s expertise ca help orgaizatio decode the performace issues ad trasform them ito valuable beefits that meet

More information

client communication

client communication CCH Portal cliet commuicatio facig today s challeges Like most accoutacy practices, we ow use email for most cliet commuicatio. It s quick ad easy, but we do worry about the security of sesitive data.

More information

Setting Up a Contract Action Network

Setting Up a Contract Action Network CONTRACT ACTION NETWORK Settig Up a Cotract Actio Network This is a guide for local uio reps who wat to set up a iteral actio etwork i their worksites. This etwork cosists of: The local uio represetative,

More information

Here are a couple of warnings to my students who may be here to get a copy of what happened on a day that you missed.

Here are a couple of warnings to my students who may be here to get a copy of what happened on a day that you missed. This documet was writte ad copyrighted by Paul Dawkis. Use of this documet ad its olie versio is govered by the Terms ad Coditios of Use located at http://tutorial.math.lamar.edu/terms.asp. The olie versio

More information

How to set up your GMC Online account

How to set up your GMC Online account How to set up your GMC Olie accout Mai title Itroductio GMC Olie is a secure part of our website that allows you to maage your registratio with us. Over 100,000 doctors already use GMC Olie. We wat every

More information

Analyzing Longitudinal Data from Complex Surveys Using SUDAAN

Analyzing Longitudinal Data from Complex Surveys Using SUDAAN Aalyzig Logitudial Data from Complex Surveys Usig SUDAAN Darryl Creel Statistics ad Epidemiology, RTI Iteratioal, 312 Trotter Farm Drive, Rockville, MD, 20850 Abstract SUDAAN: Software for the Statistical

More information

summary of cover CONTRACT WORKS INSURANCE

summary of cover CONTRACT WORKS INSURANCE 1 SUMMARY OF COVER CONTRACT WORKS summary of cover CONTRACT WORKS INSURANCE This documet details the cover we ca provide for our commercial or church policyholders whe udertakig buildig or reovatio works.

More information

How To Write A Privacy Policy For A Busiess

How To Write A Privacy Policy For A Busiess Office of the Privacy Commissioer of Caada PIPEDA Privacy Guide for Small Busiesses: The Basics Privacy is the best policy Hadlig privacy cocers correctly ca help improve your orgaizatio s reputatio. Whe

More information

hp calculators HP 12C Statistics - average and standard deviation Average and standard deviation concepts HP12C average and standard deviation

hp calculators HP 12C Statistics - average and standard deviation Average and standard deviation concepts HP12C average and standard deviation HP 1C Statistics - average ad stadard deviatio Average ad stadard deviatio cocepts HP1C average ad stadard deviatio Practice calculatig averages ad stadard deviatios with oe or two variables HP 1C Statistics

More information

Rational Suite Tutorial

Rational Suite Tutorial Ratioal Suite Tutorial Product Versio Ratioal Suite 2000.02.10 Release Date April 2000 Part Number 800-023316-000 support@ratioal.com http://www.ratioal.com IMPORTANT NOTICE Copyright Notice Copyright

More information

BaanERP 5.0c. EDI User Guide

BaanERP 5.0c. EDI User Guide BaaERP 5.0c A publicatio of: Baa Developmet B.V. P.O.Box 143 3770 AC Bareveld The Netherlads Prited i the Netherlads Baa Developmet B.V. 1999. All rights reserved. The iformatio i this documet is subject

More information

PUBLIC RELATIONS PROJECT 2015

PUBLIC RELATIONS PROJECT 2015 PUBLIC RELATIONS PROJECT 2015 Supported by MARKETING The purpose of the Public Relatios Project is to provide a opportuity for the chapter members to demostrate the kowledge ad skills eeded i plaig, orgaizig,

More information

Serial ATA PCI Host Adapter AEC-6290/6295

Serial ATA PCI Host Adapter AEC-6290/6295 Serial ATA PCI Host Adapter AEC-6290/6295 User s Maual Versio:1.0 Copyright 2003 ACARD Techology Corp. Release: April 2003 Copyright ad Trademarks The iformatio of the product i this maual is subject to

More information

insight reporting solutions

insight reporting solutions reportig solutios Create ad cotrol olie customized score reports to measure studet progress ad to determie ways to improve istructio. isight Customized Reportig empowers you to make data-drive decisios.

More information

Ken blanchard college of business

Ken blanchard college of business Ke blachard College of BUSINESS a history of excellece Established i 1949, Grad Cayo Uiversity has more tha a 60-year track record of helpig studets achieve their academic goals. The Ke Blachard College

More information

Math C067 Sampling Distributions

Math C067 Sampling Distributions Math C067 Samplig Distributios Sample Mea ad Sample Proportio Richard Beigel Some time betwee April 16, 2007 ad April 16, 2007 Examples of Samplig A pollster may try to estimate the proportio of voters

More information

Soving Recurrence Relations

Soving Recurrence Relations Sovig Recurrece Relatios Part 1. Homogeeous liear 2d degree relatios with costat coefficiets. Cosider the recurrece relatio ( ) T () + at ( 1) + bt ( 2) = 0 This is called a homogeeous liear 2d degree

More information

Security Functions and Purposes of Network Devices and Technologies (SY0-301) 1-800-418-6789. Firewalls. Audiobooks

Security Functions and Purposes of Network Devices and Technologies (SY0-301) 1-800-418-6789. Firewalls. Audiobooks Maual Security+ Domai 1 Network Security Every etwork is uique, ad architecturally defied physically by its equipmet ad coectios, ad logically through the applicatios, services, ad idustries it serves.

More information

Trustwave Leverages OEM Partnerships to Deepen SIEM Market Penetration

Trustwave Leverages OEM Partnerships to Deepen SIEM Market Penetration Trustwave Leverages OEM Parterships to Deepe SIEM Market Peetratio Accelerated lauch of ew security appliaces delivers reveue growth with assist from UNICOM Egieerig ad Dell OEM Solutios Itroductio Trustwave

More information

Baan Finance Accounts Payable

Baan Finance Accounts Payable Baa Fiace Accouts Payable Module Procedure UP035A US Documetiformatio Documet Documet code : UP035A US Documet group : User Documetatio Documet title : Accouts Payable Applicatio/Package : Baa Fiace Editio

More information

2010 Disaster Recovery Guide

2010 Disaster Recovery Guide SharePoit R 2010 Disaster Recovery Guide Joh L. Ferriger Sea P. McDoough Course Techology PTR A part of Cegage Learig Australia. Brazil. Japa. Korea. Mexico. Sigapore. Spai. Uited Kigdom. Uited States

More information

BEA elink Adapter for Kenan Arbor/BP. User Guide

BEA elink Adapter for Kenan Arbor/BP. User Guide BEA elik Adapter for Kea Arbor/BP User Guide BEA elik Adapter for Kea Arbor/BP Versio 1.1 Documet Editio 1.1 April 2000 Copyright Copyright 2000 BEA Systems, Ic. All Rights Reserved. Restricted Rights

More information

Simple Annuities Present Value.

Simple Annuities Present Value. Simple Auities Preset Value. OBJECTIVES (i) To uderstad the uderlyig priciple of a preset value auity. (ii) To use a CASIO CFX-9850GB PLUS to efficietly compute values associated with preset value auities.

More information