may 2010

Download May 2010

If you can't read please download the document

Upload: aspnetpk

Post on 17-May-2015

8.930 views

Category:

Documents


9 download

DESCRIPTION

MSDN Magazine, May 2010

TRANSCRIPT

  • 1. THE MICROSOFT JOURNAL FOR DEVELOPERSMAY 2010 VOL 25 NO 5 NOW PLAYING COLUMNS Building Custom Players with the SilverlightCUTTING EDGE Dynamic Keyword in C# 4.0 Media Framework Dino Esposito page 6 Ben Rush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 CLR INSIDE OUT Production Diagnostics SILVERLIGHT SECURITYJon Langdon page 12 Securing Your Silverlight ApplicationsDATA POINTS LINQ Projection in WCF Services Josh Twist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Julie Lerman page 23RIA SERVICES TEST RUN Combinations and Permutations with F# Enterprise Patterns with WCF RIA Services James McCaffrey page 68 Michael D. Brown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 FOUNDATIONS Service Bus Buffers WORKFLOW SERVICES Juval Lowy page 74 Visual Design of Workows with WCF and WF 4 SECURITY BRIEFS DoS Attacks and Defenses Leon Welicki . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Bryan Sullivan page 82THE WORKING PROGRAMMER Going NoSQL with MongoDB Ted Neward page 86UI FRONTIERS Thinking Outside the Grid Charles Petzold page 90DONT GET ME STARTED Fundamental Laws David Platt page 96

2. Sure, Visual Studio 2010 has a lot of great functionalitywere excited that its only making our User Interface components even better! Were here to help you go beyond what Visual Studio 2010 gives you so you can createKiller Apps quickly, easily and without breaking a sweat! Go to infragistics.com/beyondthebox today to expand your toolbox with the fastest, best-performing and most powerfulUI controls available. Youll be surprised by your own strength! Infragistics Sales 800 231 8588Infragistics Europe Sales +44 (0) 800 298 9055Infragistics India +91-80-6785-1111 twitter.com/infragisticsCopyright 1996-2010 Infragistics, Inc. All rights reserved. Infragistics and the Infragistics logo and NetAdvantage are registered trademarks of Infragistics, Inc. 3. MAY 2010 VOLUME 25 NUMBER 5magazine LUCINDA ROWLEY Director DIEGO DAGUM Editorial Director KERI GRASSL Site ManagerKEITH WARD Editor in Chief TERRENCE DORSEY Technical Editor DAVID RAMEL Features Editor WENDY GONCHAR Managing Editor MARTI LONGWORTH Associate Managing EditorSCOTT SHULTZ Creative Director JOSHUA GOULD Art Director ALAN TAO Senior Graphic Designer CONTRIBUTING EDITORS K. Scott Allen, Dino Esposito, Julie Lerman, Juval Lowy, Dr. James McCaffrey, Ted Neward, Charles Petzold, David S. Platt Henry Allain President, Redmond Media Group Matt Morollo Vice President, Publishing Doug Barney Vice President, Editorial Director Michele Imgrund Director, Marketing Tracy Cook Online Marketing Director ADVERTISING SALES: 508-532-1418/[email protected] Matt Morollo VP Publishing, Chris Kourtoglou Regional Sales Manager William Smith National Accounts Director Danna Vedder Microsoft Account Manager Jenny Hernandez-Asandas Director Print Production Serena Barnes Production Coordinator/[email protected] Neal Vitale President & Chief Executive Officer Richard Vitale Senior Vice President & Chief Financial Officer Michael J. Valenti Executive Vice President Abraham M. Langer Senior Vice President, Audience Development & Digital Media Christopher M. Coates Vice President, Finance & Administration Erik A. Lindgren Vice President, Information Technology & Application Development Carmel McDonagh Vice President, Attendee Marketing David F. Myers Vice President, Event Operations Jeffrey S. Klein Chairman of the BoardMSDN Magazine (ISSN 1528-4859) is published monthly by 1105 Media, Inc., 9201 Oakdale Avenue, Ste. 101, Chatsworth, CA 91311. Periodicals postage paid at Chatsworth, CA 91311-9998, and at additional mailing offices. Annual subscription rates payable in U.S. funds: U.S. $35; Canada $45; International $60. Single copies/back issues: U.S. $10, all others $12. Send orders with payment to: MSDN Magazine, P Box 3167, Carol Stream, IL 60132, e-mail [email protected] or.O. call 847-763-9560. POSTMASTER: Send address changes to MSDN Magazine, P Box 2166, Skokie, .O. IL 60076. Canada Publications Mail Agreement No: 40612608. Return Undeliverable Canadian Addresses to Circulation Dept. or IMS/NJ. Attn: Returns, 310 Paterson Plank Road, Carlstadt, NJ 07072.Printed in the U.S.A. Reproductions in whole or part prohibited except by written permission. Mail requests to Permissions Editor, c/o MSDN Magazine, 16261 Laguna Canyon Road, Ste. 130, Irvine, CA 92618.Legal Disclaimer: The information in this magazine has not undergone any formal testing by 1105 Media, Inc. and is distributed without any warranty expressed or implied. Implementation or use of any information contained herein is the readers sole responsibility. While the information has been reviewed for accuracy, there is no guarantee that the same or similar results may be achieved in all environments. Technical inaccuracies may result from printing errors and/or new developments in the industry.Corporate Address: 1105 Media,Inc.,9201 Oakdale Ave.,Ste 101,Chatsworth,CA 91311,www.1105media.comMedia Kits: Direct your Media Kit requests to Matt Morollo, VP Publishing, 508-532-1418 (phone), 508-875-6622 (fax), [email protected]: For single article reprints (in minimum quantities of 250-500), e-prints, plaques and posters contact: PARS International, Phone: 212-221-9595, E-mail: [email protected], www.magreprints.com/ QuickQuote.aspList Rental: This publications subscriber list, as well as other lists from 1105 Media, Inc., is available for rental. For more information, please contact our list manager, Merit Direct. Phone: 914-368-1000; E-mail: [email protected]; Web: www.meritdirect.com/1105All customer service inquiries should be sent to [email protected] or call 847-763-9560.Printed in the USA 4. S N A PI T 5. EDITORS NOTE KEITH WARD This Way-Cool Internet Doohickey Hey, have you heard about this groovy new thing called thesized (and -weight) devices with long antennas, and you couldnt Internet? Some people call it the World Wide Web, or Web fordo anything with them but call people. short, although I think the Web is just part of it.Those days now belong to the archives, and that Internet thingy Anyway, its a way that your computer connects to other computers.continues to mature and grow. Rich Internet Applications, like Its mostly done by visiting these things called Web sites. Web sites Silverlight 4, continue to push forward like Lewis and Clark, exploring can be almost anythingplaces to chat with friends, stores that new ways to build and deliver apps. Thats our focus this month. only exist on computers (special ones called servers), newspapers that you can read with a computer or even just some guy who has Product Reviews from Readers, for Readers posted tons of stuff about that TV show Baywatch. When youre In much the same way, MSDN Magazine is similarly moving ahead. there, its called being online. You can buy books and clothes andWere going to be adding something special to both the print and cars and even trade junk with other people. online versions of MSDN Magazine, starting in a few months. And Ive even heard that eventually stuff like video and audio will bewe want youneed you, in factto be a part of it. available on this Internet thingy. Pretty cool, huh? Were going to start running product reviews written by our readers. So if youre a developer using something you think is exceptionallyRich Internet Applications, like cool, let us know about how you use it and what it does for you. On the other hand, if youre using something that just doesnt work, orSilverlight 4, continue to push work well, thats valuable information, too. Wed love to hear from you.Were looking for articles in the range of 500 to 1,000 words. The forward like Lewis and Clark, products can be from Microsoft or another sourceanything you use to help you in your job. Were looking for honest, open and clear reviews. exploring new ways to buildYou dont have to be a published author to write a review. Were looking for passionate developers who have something interestingand deliver apps. to say and want to share their experiences with their colleagues.Authors will be paid for articles. The reviews will appear both in the print issue of the magazine and the online version.Bet you havent had a conversation like that in a while, eh? In One thing to note: we will verify the authenticity of all authors reality (you know, non-geek years), the Internetas a commercialand products. That means if youre a vendor posing as an author, and social mediumhasnt been around all that long. I rememberwith the goal of touting your latest ground-breaking product by working as a news director at a Baltimore TV stations Web site indisguising it as a review, well find out about it. Remember that 2000. It was my first real exposure to the day-to-day workings of these reviews are only as valuable as the honesty of the reviewer, the Web. I remember learning about things called HTML and so please avoid any of those types of shenanigans. Cascading Style Sheets and alt tags and wondering what the For more information about the process, and guidelines for the heck I was getting myself into. review, contact us at [email protected]. Make sure you putNow here we are a decade later, and its hard to remember theReader Product Reviews in the subject line, so well be sure to flag it. days when I got my news from the plastic-wrapped paper deposited Were looking forward to on my front yard every morning. Or had to drive to a bookstorehearing from you! to get the latest Stephen King novel. Portable phones were brick-Visit us at msdn.microsoft.com/magazine. Questions, comments or suggestions for MSDN Magazine? Send them to the editor: [email protected]. 2010 Microsoft Corporation. All rights reserved.Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, you are not permitted to reproduce, store, or introduce into a retrieval system MSDN Magazine or any part of MSDNMagazine. If you have purchased or have otherwise properly acquired a copy of MSDN Magazine in paper format, you are permitted to physically transfer this paper copy in unmodified form. Otherwise, you are not permitted to transmitcopies of MSDN Magazine (or any part of MSDN Magazine) in any form or by any means without the express written permission of Microsoft Corporation.A listing of Microsoft Corporation trademarks can be found at microsoft.com/library/toolbar/3.0/trademarks/en-us.mspx. Other trademarks or trade names mentioned herein are the property of their respective owners.MSDN Magazine is published by 1105 Media, Inc. 1105 Media, Inc. is an independent company not affiliated with Microsoft Corporation. Microsoft Corporation is solely responsible for the editorial contents of this magazine. Therecommendations and technical guidelines in MSDN Magazine are based on specific environments and configurations. These recommendations or guidelines may not apply to dissimilar configurations. Microsoft Corporation does not makeany representation or warranty, express or implied, with respect to any code or other information herein and disclaims any liability whatsoever for any use of such code or other information. MSDN Magazine, MSDN, and Microsoft logos areused by 1105 Media, Inc. under license from owner. 4 msdn magazine 6. CUTTING EDGE DINO ESPOSITOUsing the Dynamic Keyword in C# 4.0The introduction of static type checking represented an importantindividual features of a programming language than to the lan- milestone in the history of programming languages. In the 1970s, guage as a whole. languages such as Pascal and C started enforcing static types and Lets briefly consider Python and PHP. Both are dynamic languages, strong type checking. With static type checking, the compiler will let you use variables, and allow the runtime environment to figure produce an error for any call that fails to pass a method argument out the actual type stored in it. But with PHP you can store, say, of the appropriate type. Likewise, you should expect a compilerintegers and strings in the same variable in the same scope. In this error if you attempt to call a missing method on a type instance.regard, PHP (like JavaScript) is a weakly typed, dynamic language.Other languages that push forward the opposite approach On the other hand, Python gives you only one chance to set the dynamic type checkinghave come along over the years. Dynamictype of a variable, which makes it more strongly typed. You can type checking contradicts the idea that the type of a variable has dynamically assign the type to a variable and have the runtime to be statically determined at compile time and can never change infer it from the assigned value. After that, though, youre not while the variable is in scope. Note, however, that dynamicallowed to store any value of an inappropriate type in that variable. type checking doesnt confer wholesale freedom to mix types, pretending theyre the same. For example, even with dynamicDynamic Types in C# type checking, you still cant add a Boolean value to an integer. TheC# 4.0 has features that make it both dynamic and static, as well as difference with dynamic type checking is that the check occurs both weakly and strongly typed. Though born as a statically typed when the program executes rather than when it compiles.language, C# becomes dynamically typed in any context in whichyou use the dynamic keyword, such as this: Statically Typed or Dynamically Typeddynamic number = 10; Visual Studio 2010 and C# 4.0 provide a new keyword, dynamic,Console.WriteLine(number); that enables dynamic typing in what has traditionally been a stat-And because dynamic is a contextual keyword, not a reserved one, ically typed language. Before diving into the dynamic aspects of this still holds if you have existing variables or methods named dynamic. C# 4.0, though, we need to get some basic terminology down. Note that C# 4.0 doesnt force you to use dynamic, in the same Lets define a variable as a storage location thats restrictedway that C# 3.0 didnt force you to use var, lambdas or object ini- to values of a particular type. Next, lets specify four fundamental tializers. C# 4.0 provides the new dynamic keyword specifically to properties of a statically typed language: make a few well-known scenarios easier to deal with. The language Every expression is of a type known at compile time. remains essentially statically typed, even though it has added the Variables are restricted to a type known at compile time.ability to interact in a more effective way with dynamic objects. The compiler guarantees that type restrictions on assignments ofWhy would you want to use a dynamic object? First, you may expressions into variables meet the restrictions on the variables. not know the type of the object youre dealing with. You may have Semantic analysis tasks, such as overload resolution, occurclues but not the certainty to statically type a given variable at compile time and the results are baked into the assembly. which is just what happens in many common situations, such as A dynamic language has the opposite properties. Not everywhen you work with COM objects, or when you use reflection to expression is of a known type at compile time, nor is every variable.grab instances. In this context, the dynamic keyword makes some Storage restrictions, if any, are checked at run time and ignored at situations less painful to deal with. Code written with dynamic is compile time. Semantic analysis occurs only at run time. easier to read and write, making for an application thats easier to A statically typed language does let you make some operationsunderstand and maintain. dynamic. The cast operator exists so you can attempt a type conversionSecond, your object may have an inherently changing nature. as a runtime operation. The conversion is part of the program code,You may be working with objects created in dynamic programming and you can summarize the semantic expressed by the cast operatorenvironments such as IronPython and IronRuby. But you can also as dynamically check the validity of this conversion at run time.use this functionality with HTML DOM objects (subject to expando However, concerning attributes such as dynamic and staticproperties) and the Microsoft .NET Framework 4 objects specifi- (or perhaps strong and weak): Today theyre better applied tocally created to have dynamic natures.6 msdn magazine 7. Your best source for software development tools! LEADTOOLS RecognitionMulti-EditX NEW VMware vSphere SDK v16.5by Multi Edit SoftwareRELEASE!Put time back into your day.by LEAD TechnologiesMulti-EditX is The Solution Your business depends on how you spendDevelop robust 32/64 bit document your time. You need to manage IT costsfor your editing needs with without losing time or performance. Withimaging and recognition functionality intosupport for over 50 languages.your applications with accurate and proven cost-effective virtualization solutionshigh-speed multi-threaded Forms, OCR, Edit plain text, ANY Unicode, hex,from VMware, you can:OMR, and 1D/2D barcode engines. XML, HTML, PHP, Java, Javascript, Increase the productivity of your existing VMware Supports text, OMR, image, andPerl and more! No more file sizestaff three times over Advancedbarcode fieldslimitations, unlimited line length, Control downtimewhether plannedAcceleration Kit Auto-registration and clean-up to any file, any size Multi-EditX is or notimprove recognition results 1-49 Users for 6 processors Provided as both high and lowThe Solution! Paradise # Save more than 50% on the cost of Paradise #level interfaceA30Z10101A01 managing, powering and cooling serversV55 78101A01 Paradise # Pre-Order Your Copy and Save! L05 26301A01 Includes comprehensive confidence$ 198.40 Make your time (and money) count forreports to assess performance more with virtualization from VMware.$9,234.99 $3,214.99 programmers.com/LEAD programmers.com/multieditprogrammers.com/vSpherePragma Fortress SSHSSHCamtasia Studio 7 Server & Client for WindowsPowerful Screen Recording andNEWBUILD ONEditing for High-quality Videos RELEASE VMWARE ESXi by Pragma Systems !by TechSmithContains SSH, SFTP, SCP servers and clients AND VSPHEREfor Windows.Delight audiences near or far withtraining videos, presentations, demos,for Centralized Management, Certified for Windows Server 2008R2 and screencasts that get results andContinuous Application Compatible with Windows 7 look fantastic. Availability, and Maximum High-performance servers withEasily record onscreen activity in front of a Operational Efficiency in Your Certified centralized management for Windows Active Directory & GSSAPI authenticationlive audience or from your desk. CaptureWindowsVirtualized Datacenter.7/2008 R2 PowerPoint presentations, webcam video, Programmers Paradise invites you to take advantage Supports over 1000 sessions Single Useraudio and more. Produce and share high- of this webinar series sponsored by our TechXtend Offers FIPS modequality videos at any screen size instantlyParadise # Hyper-V and PowerShell supportT08 10501A01solutions division. Paradise # to YouTube, portable devices and more. P35 04201A01 Runs in Windows 2008R2/2008/2003/7/ Make them wonder how you did it. $ 274.99 FREE VIRTUALIZATION WEBINAR SERIES: Vista/XP/2000REGISTER TODAY! TechXtend.com/Webinars $ 550.99programmers.com/pragmaprogrammers.com/techsmithActiveReports 6CA ERwin Data ModelerTX Text Control 15.1 by GrapeCity r7.3 Product Plus 1 YearWord Processing ComponentsNEWEnterprise MaintenanceTX Text Control is royalty-free,RELEASE! Integrate Business Intelligence/Reporting/Data Analysis into your .NET applications using the by CA robust and powerful word processing NEW ActiveReports 6. software in reusable component form.CA ERwin Data Modeler is a data modeling Fast and Flexible reporting engine solution that enables you to create and .NET WinForms control for VB.NET and C# Data Visualization and Layout Controls suchmaintain databases, data warehouses ActiveX for VB6, Delphi, VBScript/HTML, ASP as Chart, Barcode and Table Cross Sectionand enterprise data resource models. File formats DOCX, DOC, RTF, HTML, XML, TXT NEW Controls These models help you visualize data PDF and PDF/A export, PDF text importProfessional EditionVERSION structures so that you can effectively Wide range of Export and Preview formats organize, manage and moderate data Tables, headers & footers, text frames, Paradise # 6! including Windows Forms Viewer, Webcomplexities, database technologies bullets, structured numbered lists, multiple T79 02101A02 Paradise # Professional Ed.Viewer, Adobe Flash and PDFand the deployment environment. undo/redo, sections, merge fields, columns Paradise # Royalty-Free Licensing for Web andP26 04201E01 Ready-to-use toolbars and dialog boxes $ 848. 99D03 04301A01 Windows applications $3,931.99Download a demo today. $ 1,310.99 programmers.com/grapecity programmers.com/ca programmers.com/theimagingsourceAdminStudio & ApplicationgDoc Fusion DONT BE LEFT BEHIND! Virtualization Packby Global GraphicsSTAY ON THE CUTTING EDGE OF TECHNOLOGY:by Flexera Software gDoc Fusion is the easiest way to NEW! MICROSOFT VISUAL STUDIOOne Application Software Deployment Toolassemble information from a range of2010 MAKES IT EASY!for Reliable MSI Packaging, Application sources and formats and quickly createVirtualization, and Windows 7 Migration.enterprise-quality PDF, XPS or Microsoft Set your ideas freeTop choice of Microsoft, Novell, LANDesk Word documents for sharing, printing Simplicity through integrationand other software management solutions.or collaboration. Quality tools helpCut MSI packaging time by up to 70%, One-click PDF/XPS creation 2010ensure quality results Professional Deploy software to desktops with 99% Upgrade from Merge and combine documents quickly 1-4 Users Includessuccess or better. AdminStudio is the onlyDISCOVER MICROSOFT any Active AS Flick through large documents like Maint & Support*MSI packaging solution to support multipleVISUAL STUDIO 2010... Pro + Silver Mtn virtualization formats, including Microsofta book Paradise # Paradise # App-V, VMware ThinApp and F39 ZSP0008TAKE YOUR DEVELOPMENT Context sensitive text editingTEAM TO THE NEXT LEVEL! I21 09401S05 Citrix XenApp. $181.99Call your Programmers Paradise* Price per user. $ 4,228. 99 programmers.com/flexeraprogrammers.com/globalgraphicsRepresentative Today!866-719-1528 programmersparadise.comPrices subject to change. Not responsible for typographical errors. 8. Figure 1 Using dynamic in the Signature of a Function System.Object. The dynamic keyword enables scenarios that werentclass Program { possible without it.static void Main(string[] args) {// The dynamic variable gets the return// value of a function call and outputs it. dynamic vs. System.Objectdynamic x = DoubleIt(2); Until the .NET Framework 4, having a method return differ-Console.WriteLine(x); ent types according to different conditions was possible only by// Stop and wait resorting to a common base class. Youve probably solved this problemConsole.WriteLine("Press any key");Console.ReadLine(); by resorting to System.Object. A function that returns System.Ob-}ject makes available to the caller an instance that can be cast to nearly// The function receives and returns a dynamic object anything. So how is using dynamic better than using System.Object?private static dynamic DoubleIt(dynamic p) {In C# 4, the actual type behind the variable thats declared// Attempt to "double" the argument whatever// that happens to produce dynamic is resolved at run time, and the compiler simply assumes that the object in a variable declared dynamic just supports anyreturn p + p;} operations. This means you can really write code that calls a method}on the object you expect to be there at run time, as illustrated here:dynamic p = GetSomeReturnValue();Using dynamicp.DoSomething(); In C# 4.0, the compiler wont complain about that code. The analo- Its important to understand the concept that in the C# typegous code using System.Object wont compile and requires some hacks system, dynamic is a type. It has a very special meaning, but itson your ownreflection or adventurous castingin order to work. definitely a type and its important to treat it as such. You can in- dicate dynamic as the type of a variable you declare, the type of var vs. dynamic items in a collection or the return value of a method. You can also The keywords var and dynamic are only apparently similar. Var use dynamic as the type of a method parameter. Conversely, youindicates that the type of the variable has to be set to the compile- cant use dynamic with the typeof operator and you cant use it astime type of the initializer. the base type of a class.But dynamic means that the type of the variable is the dynamic The following code shows how to declare a dynamic variable in type as available in C# 4.0. In the end, dynamic and var have quite the body of a method: opposite meanings. Var is about reinforcing and improving static public void Execute() { dynamic calc = GetCalculator(); typing. It aims to ensure that the type of a variable is inferred by the int result = calc.Sum(1, 1);compiler looking at the exact type being returned by the initializer. }The keyword dynamic is about avoiding static typing altogether.If you know enough about the type of the object being returned When used in a variable declaration, dynamic instructs the compiler by the GetCalculator method, you can declare the variable calc of to stop working out the type of the variable at all. The type has to be that type, or you can declare the variable as var, letting the compiler intended as the type it happens to have at run time. With var, your figure out the exact details. But using var or an explicit static type code is as statically typed as it would have been had you opted for would require you to be certain that a method Sum exists on the the classic approach of using explicit types in a variable declaration. contract exposed by the type GetCalculator returns. If the methodAnother difference between the two keywords is that var can doesnt exist, you get a compiler error. only appear within a local variable declaration. You cant use varWith dynamic, you delay any decision about the correctness to define a property on a class, nor can you use it to specify the of the expression at execution time. The code compiles and is return value or a parameter of a function. resolved at run time as long as a method Sum is available on theAs a developer, you use the dynamic keyword with variables type stored in the variable calc. expected to contain objects of uncertain type such as objects re-You can also use the keyword to define a property on a class. In turned from a COM or DOM API; obtained from a dynamic lan- doing so, you can decorate the member with any visibility modi- guage (IronRuby, for example); from reflection; from objects built fier you like, such as public, protected, and even static. dynamically in C# 4.0 using the new expand capabilities.Figure 1 shows the versatility of the dynamic keyword. In theThe dynamic type doesnt bypass type checks, though. It only main program I have a dynamic variable instantiated with the moves them all to run time. If type incompatibilities are discovered return value of a function call. That would be no big deal if it at run time, then exceptions are thrown. werent for the fact that the function receives and returns a dynamic object. Its interesting to see what happens when, as in the example, DINO ESPOSITO is the author of the upcoming Programming ASP.NET MVC you pass a number, then try to double it within the function. from Microsoft Press and coauthor of Microsoft .NET: Architecting ApplicationsIf you feed in a value of 2 and try this code, you receive a value for the Enterprise (Microsoft Press, 2008). Esposito, who is based in Italy, is a frequent of 4. If you feed in 2 as a string, youll get 22 instead. Within the speaker at industry events worldwide. You can join his blog at weblogs.asp.net/despos. function, the + operator is resolved dynamically based on the run time type of the operands. If you change the type to System.Object, THANKS to the following technical expert for reviewing this article: you get a compile error, because the + operator isnt defined onEric Lippert8 msdn magazine Cutting Edge 9. CLR INSIDE OUT JON LANGDON Production Diagnostics Improvements in CLR 4 On the Common Language Runtime (CLR) team, we have a grouptaking to solve them and the types of tools they enable. Specifically,whose focus is providing APIs and services that enable othersI will explain how weve evolved the debugging API to supportto build diagnostics tools for managed code. The two biggest dump debugging for application-crash and -hang scenarios, andcomponents we own (in terms of engineering resources dedicated)how weve made it easier to detect when hangs are caused by multi-are the managed debugging and profiling APIs (ICorDebug* and threading issues.ICorProfiler*, respectively). I will also describe how adding the ability to attach profiling tools Like the rest of the CLR and framework teams, our value isto an already-running application will further ease troubleshootingrealized only through the applications built on top of our contribu- these same scenarios, and greatly reduce the amount of time it takestions. For example, Visual Studio teams consume these debuggingto diagnose problems caused by excessive memory consumption.and profiling APIs for their managed debugger and performance Finally, I will briefly explain how we made profiling tools easierprofiling tools, and a number of third-party developers are building to deploy by removing the dependency on the registry. Through-tools with the profiling API.out, the focus is primarily on the types of new tools our work For the past 10 years, much of the focus in this area, for both the enables, but where applicable I have included references toCLR and Visual Studio, has been on enabling developer desktopadditional resources that will help you understand how you canscenarios: source-stepping in a debugger to find code errors; launch-take advantage of our work through Visual Studio.ing an application under a performance profiler to help pinpointslow code paths; edit-and-continue to help reduce time spent inDump Debuggingthe edit-build-debug cycle; and so on. These tools can be useful One popular feature were delivering with Visual Studio 2010 isfor finding bugs in your applications after theyve been installed managed dump debugging. Process dumps, typically referredon a users machine or deployed to a server (both cases hereafterto just as dumps, are commonly used in production debuggingreferred to as production), and we do have a number of third-par-scenarios for both native and managed code. A dump is essentiallyty vendors building world-class production diagnostics tools ona snapshot of a process state at a given point in time. Specifically,top of our work. its the contents of the processs virtual memory (or some subset thereof) dumped into a file. Prior to Visual Studio 2010, in order to debug managed code Bugs are more costly to xin dumps you needed to use the specialized Windows Debugger extension sos.dll to analyze the dumps, instead of more familiarthe later theyre found in the tools like Visual Studio (where you probably wrote and debugged your code during product development). Our goal for the high-level application lifecycle.experience we want you to have when using a dump to diagnose issues in Visual Studio is that of stopped-state live debugging: what you experience when youre debugging code and stoppedHowever, we consistently get feedback from customers and these at a breakpoint.vendors stressing the importance of making it even easier to findThe most common point in time to collect a dump is when theresbugs throughout the life of an application. After all, software bugs an unhandled exception in an applicationa crash. You use theare generally considered to be more costly to fix the later theyredump to figure out why the crash occurred, typically starting byfound in the application lifecycle.looking at the call stack of the faulting thread. Other scenarios whereCLR 4 (the runtime underlying the Microsoft .NET Framework dumps are used are application hangs and memory-usage issues.4) is the first release in which weve made a significant effort to This article discusses prerelease versions of the Microsoft .NET Framework 4address that feedback and to begin expanding the scenarios our and Visual Studio 2010. All information is subject to change.diagnostic APIs support toward the production end of the spectrum. Post your questions and comments on the CLR Team blog atIn this article, I will take a look at some of the scenarios weblogs.msdn.com/clrteam.understand to be particularly painful today, the approach were12 msdn magazine 10. For example, if your Web site has stopped processing requests, you CLR 4 schedule to build new APIs that give debuggers the abilitymight attach a debugger, gather a dump and restart the application. to inspect the managed heap in the way this scenario requires.Offline analysis of the dump might show, for example, that all of Moving forward, as we continue to expand the production diag-your threads processing requests are waiting on a connection to the nostics scenarios we support, I expect this is something we willdatabase, or perhaps you find a deadlock in your code. Memory-add. Later in the article I discuss other work weve done to helpusage issues can manifest in various ways from an end usersaddress that scenario.perspective: the application slows down because of excessiveId also like to explicitly call out that this work supports bothgarbage collection; service is interrupted because the application32- and 64-bit targets and both managed-only and mixed-moderan out of virtual memory and needed to be restarted; and so forth. (native and managed) debugging. Visual Studio 2010 provides Through CLR 2, the debugging APIs provided support for mixed-mode for dumps containing managed code.debugging running processes only, which made it difficult fortools to target the scenarios just described. Basically, the API wasMonitor Lock Inspectionnot designed with dump debugging scenarios in mind. The factMulti-threaded programming can be difficult. Whether you arethat the API uses a helper thread running in the target process toexplicitly writing multi-threaded code or leveraging frameworks orservice debugger requests underscores this point. libraries that are doing it for you, diagnosing issues in asynchronous For example, in CLR 2, when a managed debugger wants to walk and parallel code can be quite challenging. When you have a logicala threads stack, it sends a request to the helper thread in the processunit of work executing on a single thread, understanding causalitybeing debugged. The CLR in that process services the request andis much more straightforward and can often be determined byreturns the results to the debugger. Because a dump is just a file, simply looking at the threads call stack. But when that work istheres no helper thread to service requests in this case.divided among multiple threads, tracing the flow becomes muchharder. Why is the work not completing? Is some portion of itblocked on something?A dump is essentially a snapshot With multiple cores becoming commonplace, developers arelooking more and more to parallel programming as a means forof a process state at a givenperformance improvement, rather than simply relying on chipspeed advancements. Microsoft developers are included in thispoint in time.lot, and over the past few years weve been significantly focused onmaking it easier for developers to be successful in this area. Froma diagnostics perspective, weve added a few simple-yet-helpful To provide a solution for debugging managed code in a dump file, APIs that enable tools to help developers better cope with thewe needed to build an API that did not require running code in thecomplexities of multi-threaded code.target to inspect managed-code state. Yet because debugger writers To the CLR debugger APIs weve added inspection APIs for(primarily Visual Studio) already have a significant investment monitor locks. Simply put, monitors provide a way for programs toin the CLR debugging API to provide live debugging, we did notsynchronize access to a shared resource (some object in your .NETwant to force the use of two different APIs.code) across multiple threads. So while one thread has the resource Where we landed in CLR 4 was reimplementing a number of thelocked, another thread waits for it. When the thread owning the lockdebugger APIs (primarily those required for code and data inspec- releases it, the first thread waiting may now acquire the resource.tion) to remove the use of the helper thread. The result is that the In the .NET Framework, monitors are exposed directly through theexisting API no longer needs to care whether the target is a dump System.Threading.Monitor namespace, but more commonly throughfile or a live process. In addition, debugger writers are able to use the the lock and SyncLock keywords in C# and Visual Basic, respectively.same API to target both live and dump debugging scenarios. When Theyre also used in the implementation of synchronized methods, thelive debugging specifically for execution controlsetting breakpoints Task Parallel Library (TPL) and other asynchronous programmingand stepping through codethe debugging API still uses a helper models. The new debugger APIs let you better understand whatthread. Over the long term, we intend to remove the dependencyobject, if any, a given thread is blocked on and what thread, if any,for these scenarios as well. Rick Byers (a former developer on theholds a lock on a given object. Leveraging these APIs, debuggers candebugging services API) has a useful blog post describing this work help developers pinpoint deadlocks and understand when multiplein more detail at blogs.msdn.com/rmbyers/archive/2008/10/27/icordebug-re- threads contending for a resource (lock convoys) may be affecting anarchitecture-in-clr-4-0.aspx. applications performance. You can now use ICorDebug to inspect managed code and dataFor an example of the type of tools this work enables, checkin a dump file: walk stacks, enumerate locals, get the exceptionout the parallel debugging features in Visual Studio 2010. Danieltype and so on. For crashes and hangs, theres often enough Moth and Stephen Toub provided a great overview of these incontext available from the thread stacks and ancillary data to find the September 2009 issue of MSDN Magazine (msdn.microsoft.com/the cause of the issue. magazine/ee410778). While we know the memory diagnostics and other scenariosOne of the things that excites us the most about the dump debuggingare also important, we simply did not have enough time in the work is that building an abstracted view of the debug target means14 msdn magazineCLR Inside Out 11. new inspection functionality is added, such as the monitor-lock-In contrast, the debugger API reports every event to an out-of-inspection feature, which provides value for both live and dumpprocess debugger, when attached, and suspends the runtime ondebugging scenarios. While I expect this feature to be extremely each event. These are just a couple of the reasons the profiling APIvaluable for developers while theyre initially developing anis an attractive option for building online diagnostics tools targetingapplication, its the dump debugging support that makes monitor- production environments.lock inspection a compelling addition to the production diagnosticfeatures in CLR 4. Proler Attach and Detach Tess Ferrandez, a Microsoft support engineer, has a Channel 9 video While several vendors are building always-on, production-application-(channel9.msdn.com/posts/Glucose/Hanselminutes-on-9-Debugging-Crash-Dumps- monitoring tools via IL instrumentation, we do not have many toolswith-Tess-Ferrandez-and-VS2010/) in which she simulates a lock-convoyleveraging the performance- and memory-monitoring facilities inscenario common to what she has found when troubleshooting the profiling API to provide reactive diagnostics support. The maincustomer applications. She then walks through how to use Visualimpediment in this scenario has been the inability to attach CLRStudio 2010 to diagnose the problem. Its a great example of the profiling API-based tools to an already-running process.types of scenarios these new features enable. In versions preceding CLR 4, the CLR checks during startup to see if a profiler was registered. If it finds a registered profiler, theBeyond Dumps CLR loads it and delivers callbacks as requested. The DLL is neverWhile we believe the tools these features enable will help decrease theunloaded. This is generally fine if the tools job is to build an end-amount of time it takes developers to resolve issues in production,to-end picture of application behavior, but it does not work forwe do not expect (nor want) dump debugging to be the only wayproblems you didnt know existed when the application started.to diagnose production issues.Perhaps the most painful example of this is the memory-usage- In the case of diagnosing issues of excessive memory use issues, we diagnostics scenario. Today, in this scenario we often find that theusually start with a list of object instances grouped by type with their pattern of diagnostics is to gather multiple dumps, look at the differ-count and aggregate size and progress toward understanding objectences in allocated types between each, build a timeline of growth, andreference chains. Shuttling dump files containing this information then find in the application code where the suspicious types are beingbetween production and development machines, operationsreferenced. Perhaps the issue is a poorly implemented cachingstaff, support engineers and developers can be unwieldy andscheme, or maybe event handlers in one type are holding referencestime-consuming. And as applications grow in sizethis is to another type thats otherwise out of scope. Customers and supportespecially prevalent with 64-bit applicationsthe dump files alsoengineers spend a lot of time diagnosing these types of issues.grow in size and take longer to move around and process. It was withFor starters, as I briefly mentioned earlier, dumps of largethese high-level scenarios in mind that we undertook the profiling processes are large themselves, and getting them to an expert forfeatures described in the following sections.diagnosis can introduce long delays in the time to resolution. Further, there is the problem that you have to involve an expert, primarilyProling Tools due to the fact that the data is only exposed via a Windows DebuggerThere are a number of different types of tools built on top of the extension. Theres no public API that allows tools to consume theCLRs profiling API. Scenarios involving the profiling API gener-data and build intuitive views on top of it or integrate it with otherally focus on three functional categories: performance, memory tools that could aid in analysis.and instrumentation. Performance profilers (like the one that ships in some of the VisualStudio versions) focus on telling you where your code is spendingMulti-threaded programmingtime. Memory profilers focus on detailing your applications memoryconsumption. Instrumenting profilers do, well, everything else.can be difcult. Let me clarify that last statement a bit. One of the facilities theprofiling API provides is the ability to insert intermediate language(IL) into managed code at run time. We call this code instrumentation.To ease the pain of this scenario (and some others), we added a newCustomers use this functionality to build tools that deliver a API that allows profilers to attach to a running process and leveragewide range of scenarios from code coverage to fault injection to a subset of the existing profiling APIs. Those available after attachingenterprise-class production monitoring of .NET Framework-to the process allow sampling (see VS 2010: Attaching the Profilerbased applications.to a Managed Application at blogs.msdn.com/profiler/archive/2009/12/07/ One of the benefits the profiling API has over the debuggingvs2010-attaching-the-profiler-to-a-managed-application.aspx) and memoryAPI is that it is designed to be extremely lightweight. Both are diagnostics: walking the stack; mapping function addresses toevent-driven APIsfor example, there are events in both forsymbolic names; most of the Garbage Collector (GC) callbacks;assembly load, thread create, exception thrown and so onbut withand object inspection.the profiling API you register only for the events you care about.In the scenario I just described, tools can leverage this functionalityAdditionally, the profiling DLL is loaded inside the target process, to allow customers to attach to an application experiencing slowensuring fast access to run time state.response times or excessive memory growth, understand whats16 msdn magazineCLR Inside Out 12. currently executing, and know what types are alive on the managed some interesting conversations with some of our support engineersheap and whats keeping them alive. After gathering the information,and tools vendors. The feedback we received was that, when facedyou can detach the tool and the CLR will unload the profiler DLL. with an application failure in production, customers often care lessWhile the rest of the workflow will be similarfinding where theseabout impact to the application (its already failing; they just want totypes are referenced or created in your codewe expect tools of thisget the diagnostic information and move on) and more about impactnature to have a sizeable impact on the mean-time-to-resolution to the state of the machine. Many customers go to great lengthsfor these issues. Dave Broman, developer on the CLR profiling to document and police the configuration of their machines, andAPI, discusses this and other profiling features in more depth on introducing changes to that configuration can introduce risk.his blog (blogs.msdn.com/davbr). So, with respect to the CLRs part of the solution, we wanted to I do, however, want to call out two limitations explicitly in this make it possible to enable xcopy-deployable diagnostics tools toarticle. First, memory-diagnostics on attach is limited to non-con- both minimize the risk of state changes and to reduce the time itcurrent (or blocking) GC modes: when the GC suspends executiontakes to get the tools up and running on the machine.of all managed code while performing a GC. While concurrentIn CLR 4 we removed the need to register the COM profilerGC is the default, ASP.NET uses server-mode GC, which is a non- DLL in the registry. We still require environment variables if youconcurrent mode. This is the environment in which we see most want to launch your application under the profiler, but in theof these issues. We do appreciate the usefulness of attach-profilingattach scenarios detailed previously, there is no configurationdiagnostics for client applications and expect to deliver this in a required. A tool simply calls the new attach API, passes the pathfuture release. We simply prioritized the more common case for CLR 4. to the DLL and the CLR loads the profiler. Moving forward, were Second, you are unable to use the profiling API to instrument IL looking into ways to further simplify profiler configuration asafter attach. This functionality is especially important to our enterprise- customers still find the environment-variable solution challengingmonitoring tool vendors who want to be able to change their in some scenarios.instrumentation dynamically in response to runtime conditions. Combined, the two profiling features I just discussed enableWe commonly refer to this feature as re-JIT. Today, you have onea class of low-overhead tools that customers can, in the case ofopportunity to change the IL body of a method: when its firstunexpected failures, quickly deploy to a production machine tobeing JIT-compiled. We expect delivering re-JIT to be a significant gather performance or memory diagnostic information to helpand important undertaking and are actively investigating both the pinpoint the cause of the problem. Then, just as quickly, the usercustomer value and technical implications as we consider delivering can return the machine to its original state.the work in a future release.Wrapping UpRegistry-Free Activation for Prolers Working on diagnostics features for the CLR is bittersweet. I seeProfiler attach and the supporting work of enabling specificmany examples of how much customers struggle with certain issues,profiling APIs after attach was the biggest piece of work we did in the and yet theres always cool work we can do to help ease developmentCLR profiling API for CLR 4. But we were delighted to find anotherand make customers happier. If that list of issues challenging ourvery small (in terms of engineering cost) feature that has a surprisingly customers isnt changingthat is, were not removing items fromlarge impact on customers building production-class tools.itthen were not succeeding. In CLR 4 I think we built features that not only provide immediate Memory prolers focus onvalue in addressing some top customer problems, but also lay a foun-dation upon which we can continue to build in the future. Moving detailing your applicationsforward, we will continue to invest in APIs and services that make iteven easier to expose meaningful diagnostic information in all phasesmemory consumption.of an applications life so you can focus more time on building newfeatures for your customers and less time debugging existing ones. If youre interested in providing us feedback on diagnostics work Prior to CLR 4, for a tool to get its profiler DLL loaded in a man-were considering for our next release, weve posted a survey ataged application it had to create two key pieces of configuration surveymonkey.com/s/developer-productivity-survey. As we are now about to shipinformation. The first was a pair of environment variables that toldCLR 4, were focusing much of our time on planning for upcomingthe CLR to enable profiling and what profiler implementation to releases and data from the survey will help us prioritize our efforts.load (its CLSID or ProgID) when the CLR starts up. Given that If you have a few minutes, we would love to hear from you.profiler DLLs are implemented as in-process COM servers (withthe CLR being the client), the second piece of configuration data J ON L ANGDON is a program manager on the CLR team where he focuseswas the corresponding COM registration information stored in theon diagnostics. Prior to joining the CLR team, he was a consultant withregistry. This basically told the runtime, by way of COM, where toMicrosoft Services, helping customers diagnose and fix problems with large-scale,enterprise applications.find the DLL on disk. During CLR 4 planning, while trying to understand how we could THANKS to the following technical expert for reviewing this article:make it easier for vendors to build production-class tools, we hadRick Byers18 msdn magazine CLR Inside Out 13. AMCOM Software 14. Internet Connectivity for the Enterprise Since 1994, Dart has been a leading provider of high quality, high performance Internet connectivity components supporting a wide range of protocols and platforms. Darts three product lines offer a comprehensive set of tools for the professional software developer. PowerSNMP for ActiveX and .NET PowerTCP for ActiveX and .NET Create custom Manager, Agent and Trap applications with a setAdd high performance Internet connectivity to your ActiveX, .NET of native ActiveX, .NET and Compact Framework components.and Compact Framework projects. Reduce integration costs with SNMPv1, SNMPv2, SNMPv3 (authentication/encryption) and detailed documentation, hundreds of samples and an expert ASN.1 standards supported. in-house support staff.PowerWEB for ASP.NET SSHFTPSMTP DNS TelnetUDPSFTP IMAP RloginVT Emulation AJAX enhanced user interface controls for responsive ASP.NETTCPHTTP S/MIME Rsh ZIP Compression applications. Develop unique solutions by including streaming file upload and interactive image pan/zoom functionality within a page. SSLPOPPing Rexec more...Ask us about Mono Platform support. Contact [email protected]. Download a fully functional product trial today! 15. DATA POINTS JULIE LERMAN LINQ Projection Queries and Alternatives in WCF Services The presenter at my local .NET user group was writing a LINQ When youre working with services, there are many scenarios query during his session last month when I asked him, How didwhere you want to work with a particular view of data without we ever live without LINQ? I have no idea, he replied. paying the price of moving larger types across the wire.Its true. Since it was introduced in Visual Studio 2008, LINQIt turns out, there are more options besides creating an extra type has made such a difference in how we code in the Microsoft .NET in your domain to satisfy this temporary need. Framework. In combination with the many new language features that were introduced in Visual Basic and C#, its a consistent problemNew Projection Capability in WCF Data Services solver for querying in-memory objects and data sources. The Data Services Update for the .NET Framework 3.5 SP1 intro-One of LINQs abilities that is both a blessing and an occasionalduces a handful of powerful features for WCF Data Services, which source of frustration is that it can project randomly shaped data are also part of the .NET Framework 4. Among these features is the into anonymous types. When you simply need to grab a specialability to use projections in queries against the data services. I highly view of your data, without having to declare a new class for this recommend checking out the WCF Data Services team blog post on all throwaway type, anonymous types are a great solution. LINQthats new in this update at blogs.msdn.com/astoriateam/archive/2010/01/27/ projections and anonymous types have certainly spoiled us. So why data-services-update-for-net-3-5-sp1-available-for-download.aspx. do I say they can also be a source of frustration? The $select operator has been added to the data services URI syn-If you have ever used a LINQ projection in a method that tax. It allows for property and even navigation property projection. needs to return data to another methodor worse, used a LINQ Heres a simple example of a projection that gets a few scalar projection in a Windows Communication Foundation (WCF)properties for a customer along with the SalesOrderHeaders service operationyou may understand. navigation property:Because anonymous types are throwaway types, they have nohttp://localhost /DataService.svc/Customers(609) ?$select=CustomerID,LastName,FirstName,SalesOrderHeaders&$expand= declaration and are understood only within the method where SalesOrderHeaders theyre created. If you write a query that returns a list of anony-The expand operator forces the results to include not just a link mous types, theres no way to define a method argument to say to those orders, but the data for each order as well. Im going to return a list of because theres no way to express Figure 1 shows the results of this query. The expanded Sales- of anonymous types. OrderHeaders (which contains only a single order) is highlightedHeres a LINQ to Entities query with a simple projection:in yellow while the customer information is highlighted in green.var custQuery = from c in context.Customersselect new {c.CustomerID, Name=c.LastName.Trim() +The LINQ to REST feature in the .NET Framework and Silver-", " + c.FirstName}; light client APIs for WCF Data Services has been updated toAt run time, the custQuery variable will actually be anallow projections as well: ObjectQuery. var projectedCust = (from c in context.Customers where c.CustomerID==609The var (and the alternate use of Visual Basic Dim) allows us to get select new {c.CustomerID, c.LastName}) away with not having (or needing) a way to express this non-type. .FirstOrDefault();If you want to return the results of that query from a method,ProjectedCust is now an anonymous type I can use in my the only reasonable solution is to create a class to represent theclient application. type being returned. Doing this, however, renders the beauty ofIts also possible to project into known entity types, and in some the anonymous type moot. Now you have to write more code, cases, the DataContext can keep track of changes made by the define classes and (possibly) new projects to house the new classes,client and these changes can be persisted back through the services ensure the various assemblies using these classes haveSaveChanges method. Be aware that any missing properties will access to them and so on. get populated with their defaults (or null if theyre nullable) andUntil recently, data services provided an additional conundrum.be persisted to the database. In order to project data, you had to create a custom operation in a service, execute your own query and then return some type ofCode download available at code.msdn.microsoft.com/mag201005DataPoints. pre-defined class that could be understood by the client.May 2010 23 16. Building a QueryView Before creating a QueryView, you need to create an entity in the model that represents the shape of the view youre aiming forfor example, the CustomerNameAndID entity. But you cant map this entity directly to the Customer table in SSDL. Mapping both the Customer entity and the CustomerNameAnd- ID entity to the tables CustomerID column would create a conflict. Instead, just as you can create a view of a table in your database, you can create a view of the SSDL Cus- tomer directly in the metadata. A QueryView is literally an Entity SQL expression over the SSDL. Its part of the mapping specification language (MSL) metadata of the model. There is no designer support to create the QueryView, so youll need to type it directly in the XML. Because youll be mapping to the store schema of the table, its a good idea to see what that looks like. Figure 3 lists the SSDL description of the Customer data- base table, which looks similar to theFigure 1 Results of a Data Services Query Projection Requesting Three Customer PropertiesCustomer entity in the conceptualand the Customers SalesOrderHeaders models metadata, except for the use of provider data types.Enabling Projected Strong Types from an EDMAnother important element for the QueryView will be the storeIf youre using an Entity Framework Entity Data Model (EDM), theres schemas namespace, ModelStoreContainer. Now you have thea convenient way to avoid being stuck with anonymous types when pieces necessary to construct the QueryView expression. Heres ayou need to pass them out of the method in which they were created. QueryView that projects the three required fields from the SSDLThe EDM has a mapping called QueryView. Ive pointed many into the CustomerNameAndID entity that I created in the model:clients to this in the past, prior to data services projection support. SELECT VALUE AWModel.CustomerNameAndID(c.CustomerID, c.FirstName,c.LastName) FROM ModelStoreContainer.Customer as cNot only does it solve the problem nicely for data services, but forcustom WCF Services and RIA Services as well.Translating the Entity SQL to English: Query the CustomerWhat is a QueryView? Its a special type of mapping in the Entity in the store schema, pull out these three columns and give themFramework metadata. Typically, you map properties of an entity back to me as a CustomerNameAndID entity. AWModel is theto database tables or view columns as theyre described in thestore modelStorage Schema Definition Language (SSDL)ofmetadata, as shown in Figure 2.A QueryView, however, lets you create a view over those SSDL tablecolumns rather than map directly to them. There are many reasons touse a QueryView. Some examples include: to expose your entities asread-only, to filter entities in a way that conditional mapping does notallow or to provide different views of the data tables from the database.Its the last of these purposes that I will focus on as an alternativeto the anonymous types you frequently find yourself projecting inyour application. One example would be a pick list. Why return anentire customer type for a drop-down that needs only an ID andthe customers name? Figure 2 Mapping Table Columns Directly to Entity Properties24 msdn magazine Data Points 17. Connect legacy technologies affordably with the complete set of data integration tools from AltovaExperience how the Altova MissionKit, the integrated suite of XML, data mapping, and database tools, can help you leverage existing technology and business software investments while integrating modern technologies without breaking your budget. The Altova MissionKit includes multiple intelligent tools for data integration:MapForce Graphical data mapping, transformation, & conversion tool Drag-and-drop data conversion with instanttransformation & code generation Support for mapping XML, DBs, EDI, XBRL, 010: Excel2007+, XBRL, text files, Web servicesersion 2 N ew in V XMLSpy XML editor and Web services toolversion pping 64-bitg & ma SDL 2.0 editining rt for Wta mapp XML editor with strong database integration Suppo ts for da ha ncemen rous enapping, Web services tool, JSON XML converter Nume ating, m izations for cre OptimL dataing XBRDatabaseSpy multi-database query, & tra nsform ion conversdesign, comparison tooliting &J SON edries 6.1M iSe Supp ort for IB Support for all major relational databases andtranslation between DB types SQL editor, graphical database design& content editor Download a 30 day free trial!Try before you buy with a free, fully functional, trial from www.altova.com 18. Figure 3 The SSDL Description of the Database Customer Table No messy projections. Better yet, you can create service opera- tions in your custom WCF Services that are now able to return this strongly typed object without having to define new types in your application and project into them. GetCustomerPickList() StoreGeneratedPattern="Identity" /> { using (var context = new AWEntities()) return context.CustomerNameAndIDs.OrderBy( c => c.LastName).ToList(); } Because of the limitation that prevents us from concatenating the first and last names in the QueryView, its up to the developers who consume the service to do this concatenation on their end. WCF RIA Services can also benefit from the QueryView. You from your domain service. Rather than having to create an extraclass in the domain service to represent the projected properties,this RestaurantPickList entity is backed by a QueryView in thenamespace of the conceptual models entity container. Youremodel, which makes it easy to provide this data:required to use the strongly typed names of both the Conceptualpublic IQueryable GetRestaurantPickList() {Schema Definition Language (CSDL) and SSDL types that arereturn context.RestaurantPickLists;referenced in the expression.} As long as the results of the projection (an integer, a string and astring) match the schema of the target entity, the mapping will suc-QueryViews or Projectionsceed. Ive tried to use functions and concatenation within the projec-Weve Got You Coveredtionfor example, (c.CustomerID, c.FirstName + c.LastName)butHaving the ability to project views over your data types is a hugethis fails with an error stating that FUNCTIONs are not allowed.benefit in querying, and its a great addition to WCF Data Services.So Im forced to use the FirstName and LastName properties andEven so, there are times when having access to these views, withoutlet the client deal with concatenation. having to project and without having to worry about sharing theresult, will simplify some of your coding tasks.Placing the QueryView into the MetadataOne last note: With the introduction of foreign keys in the .NETYou must place the QueryView expression within the Entity-Framework 4 version of Entity Framework, QueryView pick listsSetMapping element for the entity that goes inside the Entity-make even more sense because you can return read-only entitiesContainerMapping in the metadata. Figure 4 shows this QueryView and simply use their properties to update foreign key properties(highlighted in yellow) in the raw XML of my EDMX file. in the entities youre editing.Now my CustomerNameAndIDis part of my model and will beavailable to any consumer. And there is another advantage to theJULIE LERMAN is a Microsoft MVP, .NET mentor and consultant who lives in theQueryView. Even though the goal of this QueryView is to create ahills of Vermont. You can find her presenting on data access and other Microsoftread-only reference list, you can also update entities that are mapped.NET topics at user groups and conferences around the world. Lerman blogs atusing QueryViews. The context will track changes to Customer- thedatafarm.com/blog and is the author of the highly acclaimed book, ProgrammingNameAndID objects. Although Entity Framework is not able to Entity Framework (OReilly Media, 2009). Follow her on Twitter: julielerman.auto-generate insert, update and delete commands for this entity,you can map stored procedures to it.THANKS to the following technical expert for reviewing this article:Alex JamesReaping the Benets ofthe QueryViewNow that you have the QueryViewin the model, you dont need todepend on projections or anony-mous types to retrieve these viewsof your data. In WCF Data Services,CustomerNameAndIDs becomesa valid entity set to query against,as shown here:List custPickList =context.CustomerNameAndIDs.ToList(); Figure 4 A QueryView in the Mappings Section 26 msdn magazineData Points 19. 1987-2010 ComponentOne LCC. All rights reserved. iPhone and iPod are trademarks of Apple Inc. All other product and brand names are trademarks and/or registered trademarks of their respective holders. 20. ComponentOne Sales: 1.800.858.2739 or 1.412.681.4343 21. N O W P L AY I N GBuilding CustomPlayers with the SilverlightMedia FrameworkBen RushStreaming media has become ubiquitous on the Web. than they were even a couple years ago. As a result, developersIt seems like everyonefrom news sites to social networks to your need a robust framework on which they can build their players.next-door neighboris involved in the online video experience. DueThe Silverlight Media Framework (SMF) is an open sourceto this surge in popularity, most sites want to present high-qualityproject that was released by Microsoft at the 2009 Microsoftvideoand often high-quality bandwidth-aware videoto their Professional Developers Conference. It is an extensible and highlyconsumers in a reliable and user-friendly manner. scalable Silverlight video framework that directly answers the needA key element in the online media delivery experience is the player for a stable core upon which developers and designers can createitself. The player is what the customer interacts with, and it drives their own players. The code at the center of the Silverlight Mediaevery element of the users online experience. With so much attention Framework has been refined based on lessons learned from thecentered on the player, its no surprise that modern, Web-based media NBC Olympics and Sunday Night Football Web video projects.players have become a great deal more complicated to implementThis article will explain the basic elements of SMF, demonstratehow you can integrate SMF into your own player projects and walkThis article is based on the Smooth Streaming Player Developmentyou through a simple project that uses SMF to create a customKit beta 2. All information is subject to change. player experience. Ill show you how to use the logging, settings,This article discusses: and event-handling features of SMF. Finally, Ill create a player Getting started with SMFapplication that displays suggested videos for further viewing whenthe current video ends. Creating and displaying the player Logging, settings and events Showing recommended video buttonsGetting Started with SMFTo get started, the first thing youll want to do is download theTechnologies discussed: framework from Codeplex (smf.codeplex.com). You also need toSilverlight Media Framework, Smooth Streaming Playerdownload the Smooth Streaming Player Development Kit (iis.net/Development Kit expand/smoothplayer) and reference it in any projects using SMF. TheCode download available at: Smooth Streaming Player Development Kit is not part of SMFits acompletely separate, closed-source component. However, SMFcode.msdn.microsoft.com/mag201005CustPlayleverages a core set of functionality from the kit, in particular the 30 msdn magazine 22. video player itself. As of the writing of this article, the SmoothSmooth StreamingPlayerMicrosoft.SilverlightMediaFramework.Player Streaming Player Development Kit is in beta 2. Development KitSMF consists of a number of Microsoft .NET assemblies (as shown in Figure 1), each a different functional part of the overall framework.The core assembly is Microsoft.SilverlightMediaFramework.dll,Microsoft.SilverlightMediaFramework.LoggingMicrosoft.SilverlightMediaFrameworkwhich comprises a number of utility classes and types referenced throughout the rest of the framework. When using any aspect of SMF, you must also reference the Microsoft.SilverlightMedia-Microsoft.SilverlightMediaFramework.Data Framework.dll assembly.The Microsoft.SilverlightMediaFramework.Data namespaceFigure 1 The Silverlight Media Framework Assemblies provides helper classes for consuming data external to the player and for encapsulating data within the player. The data can be The next step is to create your own separate Silverlight proj- general, with any form, but it can also be settings information forect and leverage SMF from within it. In Visual Studio click the player itself. Theres another namespace, Microsoft.Silverlight- File | New | Project | Silverlight Application. Call the solution MediaFramework.Data.Settings, for types representing and dealing SMFPlayerTest and click OK. A modal dialog will pop up, ask- with player settings.ing whether you wish to host the Silverlight application in aApart from data used for settings, the type within the Data new Web site. Click OK and youll see a basic Silverlight appli- namespace youll most likely interact with is the out-of-streamcation solution consisting of two projects, SMFPlayerTest and DataClient class, which can retrieve data from an external source. SMFPlayerTest.Web. You reference this assembly if you want to download and use data The final step is to reference the Smooth Streaming Player external to the player.Development Kit and SMF assemblies from your newly createdThe SMF player includes the robust Microsoft.Silverlight- project. Copy the output SMF assemblies and Smooth Streaming MediaFramework.Logging framework that uses a callback-stylePlayer Development Kit from the SMF solutions Debug folder and paradigm in which writing to the logging infrastructure raises paste them into your new project as shown in Figure 3. Your new events. You register your own callback methods with the loggingsolution now includes all the assembly references required to take system, and these callbacks carry out additional operations once full advantage of the SMF. invokedsuch as posting information to a Web service or displaying information to a text box. You reference this assembly if youDisplaying the Player wish to use the built-in logging facilities of SMF.To begin using the SMF, include the SMF players namespaceThe Microsoft.SilverlightMediaFramework.Player assembly within your MainPage.xaml page. This ensures that all references implements the player itself. It also provides a number of controlsresolve properly: the player relies on, such as a scrubber, volume control and timelinexmlns:p="clr-namespace:Microsoft.SilverlightMediaFramework.Player;assembly=Microsoft.SilverlightMediaFramework.Player" markers. The default SMF player is sleek and clean, a great starting point for any project requiring a Silverlight player. However, Now insert players XAML within the pages LayoutRoot Grid central to all controls defined within SMF is the notion of controlcontrol. templating, so each control can be themed by using tools such as Expression Blend or Visual Studio. Pressing F5 will launch the project and bring up the SMF Building and Referencing SMFplayer. However, because the player hasnt been told what to play, SMF downloads as a single .zip file in which youll find a solutionit does nothing. All you get is a player with no content to play. file, a project for each output library, and test projects for running and verifying the player itself.SMF relies on the Smooth Streaming Player Development Kit. To reference the kit, move the Smooth Streaming assembly (Microsoft.Web.Media.SmoothStreaming.dll) into the Lib folder of the SMF project.Next, open the SMF solution in Visual Studio and build it, creating all the assemblies needed to leverage the framework. To verify that everything executes as expected, press F5 to begin debugging. The solution will build and the Microsoft.SilverlightMediaFramework. Test.Web target will execute, presenting you with the default SMF player streaming a Big Buck Bunny video (see Figure 2). Note how complete the default player already is, with a position element for scrubbing, play/stop/pause buttons, volume controls, full screen controls and so forth. Figure 2 The SMF Player and the Big Buck Bunny Video msdnmagazine.comMay 2010 31 23. SMF uses SmoothStreamingMediaElement (from the SmoothStreaming Player Development Kit) to play video. From Smooth-StreamingMediaElement, SMF inherits its own player, calledCoreSmoothStreamingMediaElement. This object is required ifyou want the player to stream content. Be sure to set the Smooth-StreamingSource property to a valid smooth streaming media URL:As mentioned earlier, Microsoft provides the Big Buck Bunnysample video stream, which developers can use to test Silverlightprojects. To use this test stream, set the SmoothStreamingSourceproperty on the CoreSmoothStreamingMediaElement to:http://video3.smoothhd.com.edgesuite.net/ondemand/Big%20Buck%20Bunny%20Adaptive.ism/Manifest Once again, press F5 to build and run the project. The browser Figure 3 Referencing the Required Assemblieswill execute with the same player as before, but this time the BigBuck Bunny video will begin streaming moments after the player object of type System.String that holds the text for the logging event.has fully loaded. If your task was to create a basic Silverlight player TimeStamp simply holds the date and time at which the loggingto stream content, youve done it.object was first instantiated. The SimpleEventArgs object passed However, the SMF offers quite a bit more than weve seen thusas the second parameter to your event handler holds a reference tofar. Lets add some basic logging.the Log object through its Result property. To raise a log event, all thats required is to instantiate a type thatLogging in the Player inherits from the Log base class, then pass this type to the staticallyLogging in SMF is simplewhenever an event is logged, it raises a Log-defined Log method on the Logger type. The framework suppliesReceived event. You register an event handler for this event, and thereby a DebugLog class that already inherits from the Log base type.receive a notification for each logging event as its raised. What you do Whats special about the DebugLog type, however, is that if thewith the notification is up to you; you can display it in a new windowlibraries being referenced by your Silverlight project were createdwithin the player, filter the events and notify a Web service whenever aunder a Debug build of the SMF, passing a DebugLog type to thecertain event gets raised, or do whatever is necessary for your scenario. SMF logging framework will raise a corresponding logging event The LogReceived event is statically defined on the Logger(and therefore invoke your event handlers). On the other hand, aclass itself (defined within Microsoft.SilverlightMediaFramework.Logg-Release build of the SMF will ignore any call to the Log methoding.dll), so its possible to register for logging events anywhere within that gets passed the DebugLog class. In short, if you have debuggingthe project. Heres an example of registering for and defining the eventstatements you only want to use Debug builds, with the Debug-handler within the MainPage.xaml file of the SMFPlayerTest project: Log object as the log event argument; otherwise you will need topublic partial class MainPage : UserControl { construct your own type that inherits from the abstract Log type.public MainPage() {Heres an example that raises a Listening event through the SMFInitializeComponent();event system by instantiating a DebugLog object and passing it toLogger.LogReceived += the Loggers static Log method (be sure your Smooth Streamingnew EventHandler>(Logger_LogReceived);Player Development Kit files were built under Debug settings):} public MainPage() {InitializeComponent();void Logger_LogReceived(object sender,Microsoft.SilverlightMediaFramework.SimpleEventArgs e) { Logger.LogReceived +=throw new NotImplementedException();new EventHandler>(} Logger_LogReceived);}Logger.Log(new DebugLog {SMF raises quite a few events out of the box. To see them, create Message = "Listening!", Sender = this });a breakpoint within the Logger_LogReceived method and run }the player once again in Debug mode. Almost immediately yourbreakpoint will get hit, allowing you to step through the methodsInheriting from the Player Classparameters and see the information passed to it.Although logging is a central feature of the player, the SMF play-Log event data is packaged within a special messaging object whoseback features are only accessible when you inherit from and begintype must inherit from an abstract class named Log. This abstract extending the SMF Player type itself.Log type has three properties: Sender, Message and TimeStamp. To see how this works, you need to create a new class called SMF-Sender references the object that raised the event. Message is an Player that inherits from the Player type. 32 msdn magazine Now Playing 24. The new SMFPlayer class looks like this: layer of SMF uses this infrastructure to reach out and download anamespace SMFPlayerTest {specially formatted XML settings file hosted on a Web server. Oncepublic class SMFPlayer : Player {public override void OnApplyTemplate() { the settings data has been successfully downloaded and read, thebase.OnApplyTemplate();SMF settings layer encapsulates it with a SettingsBase object whose}}methods are then used to retrieve the settings values.} The SettingsBase class, as the name suggests, serves as a base Every FrameworkElement type (such as Player in SMF) has anfor a more specific class that can provide strongly typed access toOnApplyTemplate method that is called whenever the Apply-your settings values. Heres an example of a class that inherits fromTemplate event is raised. This method often serves as a useful SettingsBase. It has two properties, one for retrieving a video playerstarting point when initializing a FrameworkElement type.source URL and another for retrieving a Boolean value that In this case, I override the default OnApplyTemplate method indicates whether the video player should start automatically orfrom within the new SMFPlayer class. To demonstrate that the wait for the viewer to press the play button:new SMFPlayer type is executed instead of the default Player type, namespace SMFPlayerTest { public class SMFPlayerTestSettings : SettingsBase {you can set a breakpoint within the override. When you debug the public Uri VideoPlayerSource {player in Visual Studio, this breakpoint will be enountered when get { return new Uri( GetParameterValue("videoSource")); }Silverlight executes the SMFPlayer.}Built into the SMF player is a public bool? AutoStartVideo { get { return GetParameterBoolean( "autoStart"); } robust logging framework. } } }The property methods use functions implemented by the Now update the MainPage.xaml file to use the new player class.SettingsBase class to inspect the underlying collection of settingsFirst, include the players namespace in the list of namespacesname/value pairs loaded into the type (through a mechanismalready referenced (just as you did the player namespace earlier): discussed shortly). This provides a type-safe and IntelliSense-xmlns:smf="clr-namespace:SMFPlayerTest"friendly method of retrieving settings information.Then simply update the Player tags within the XAML to use Now create a new XML file in the SMFPlayerTest.Web project,SMFPlayer instead of Player: name it SMFPlayerSettings.xml, and add the following to it: AutoPlay="true" Name="videoSource" Value="http://video3.smoothhd.com.edgesuite.net/ondemand/Big%20Buck%20Bunny%20Adaptive.ism/Manifest"/> Next, instantiate a DebugLog class and pass it to the Log methodas shown earlier. Doing so will fire the event for which you previouslyregistered an event handler:Next, create a SettingsClient object into which youll load the settingspublic override void OnApplyTemplate() { XML. SettingsClient takes a URI pointing to the settings file:Logger.Log(new DebugLog {Message = "Hello from OnApplyTemplate!", m_settingsGetter = new SettingsClient(Sender = thisnew Uri("http://localhost:10205/SMFPlayerSettings.xml"));});The process of retrieving the settings data is asynchronous, sobase.OnApplyTemplate();a callback method must be assigned to the RequestCompleted}method on SettingsClient:To listen specifically for this event from within the event handler, m_settingsGetter.RequestCompleted += new EventHandler>filter the Message property of the DebugLog object itself. In this (m_settingsGetter_RequestCompleted);example, look for any message that contains OnApplyTemplate: The last step is to invoke the parameterless Fetch method onvoid Logger_LogReceived(object sender, SimpleEventArgs e) { the SettingsClient object. When the data is retrieved, the settings-if (e.Result.Message.Contains("OnApplyTemplate")) {Getter_RequestCompleted event handler will be invoked and areturn;}SettingsBase object will be passed to it:}void m_settingsGetter_RequestCompleted( object sender, SimpleEventArgs e) {Using Settings DataSettingsBase settingsBase = e.Result; return;A mature framework for dealing with settings is crucial to most large- }scale software projects. The code for handling settings in SMF is builtThe SettingsBase object passed to the settingsGetter_Request-on the Microsoft.SilverlightMediaFramework.Data.dll assembly,Completed method is loaded with the name/value pairs parsed forwhich allows you to download generic, external data. The settingsyou by the underlying framework from the file SMFPlayerSettings.xml.34 msdn magazineNow Playing 25. /update/2010/05www.componentsource.com BEST SELLER BEST SELLER TX Text Control .NET and .NET Server from $499.59Word processing components for Visual Studio .NET. BEST SELLER FusionCharts from $195.02Interactive and animated charts for ASP and ASP.NET apps. BEST SELLERNEW RELEASE LEADTOOLS Recognition SDK from $3,595.50 Add robust 32/64 bit document imaging & recognition functionality into your applications. BEST SELLER ContourCube from $900.00 OLAP component for interactive reporting and data analysis.We accept purchase orders. 1996-2010 ComponentSource. All Rights Reserved. All prices correct at the time of press. Online prices may vary from those shown due to daily fluctuations & online discounts. Contact us to apply for a credit account. US HeadquartersEuropean HeadquartersAsia / Pacific Headquarters ComponentSourceComponentSourceComponentSourceSales Hotline - US & Canada: 650 Claremore Prof Way 30 Greyfriars Road 3F Kojimachi Square Bldg Suite 100 Woodstock GA 30188-5188ReadingBerkshireRG1 1PE 3-3 Kojimachi Chiyoda-ku Tokyo Japan(888) 850-9911 USAUnited Kingdom 102-0083www.componentsource.com 26. In order to load this data into your icon in the Tools window for eachSMFPlayerTestSettings object, youbutton you want to add. Three but-simply call the Merge method, whichtons should now be visible in the treemerges settings information from of controls that make up the playerone SettingsBase-derived object with template (see Figure 4).that of another:Select all three buttons in the tree, go SettingsBase settingsBase = e.Result; to the properties window for the con- m_settings.Merge(settingsBase); trols and set the horizontal and vertical this.mediaElement.SmoothStreamingSource = alignment to be centered (see Figure 5), m_settings.VideoPlayerSource; this.mediaElement.AutoPlay =thus aligning the buttons down the (bool)m_settings.AutoStartVideo;center and middle of the video player. return; Figure 4 Button Controls Added to the Control TreeThe buttons are the default size and You no longer have to hard- lie on top of each other. Set the widthcode the AutoPlay and Smooth-of each button to 400, and the heightStreamingSource properties on theto 75. Next, adjust the margins so thatCoreSmoothStreamingMediaElementone button has a 175-pixel offset fromwithin the page XAML, because thethe bottom, another 175-pixel off-player settings are being downloaded set from the top and the last has nofrom within the OnApplyTemplatemargin offsets at all. The end resultmethod. This is all you need for the will look like Figure 6.player XAML:To verify the buttons have been Figure 5 Setting Button Control Alignment properly placed on the player, save all open files in Expression Blend and return to Visual Studio. Visual Studio may prompt you to reload documents that were changed by Expression Blend. If so, click OK. When you run the player, all the settings data will load, the call- From within Visual Studio, press F5 to relaunch the SMF playerback will load the values into the players media element, and the in Debug mode. The player should now appear with three buttonsvideo will begin to stream just as it did before. aligned down the center of the video screen as shown in Figure 7. Hooking up Event HandlersExtending the SMF PlayerEvent handlers must now be associated with the buttons. To referenceOn many popular video sites, when video playback has completed, the buttons from code, you need to assign names to them, whichyou see a list of similar or recommended videos. To illustrate how easy you do via the Name text box in the Properties tab. For simplicity,it is to extend the SMF player, lets walk through the steps to build a name the buttons Button1, Button2 and Button3. When youresimilar suggested-viewing feature into the SMFPlayerTest project. done, the Objects and Timeline window should update and displayStart by adding an x:Name attribute to the Player element in thethe button names adjacent to the button icons in the visual tree.MainPage.xaml file: Within the Properties tab for each button youll find an Events button thats used to assign event handlers for a visual component.Select one of the buttons, click the Event button within the Properties tab, and double-click the Click text box to auto-generate an event This makes it easier to refer to the SMFPlayer object by namehandler within the MainPage.xaml.cs. The properties window forwithin both Visual Studio and Expression Blend. each button will now have an event handler assigned to its Click Now, right-click on the MainPage.xaml file in Solution Explorerevent (see Figure 8), and the MainPage.xaml.cs file will have eventand select Open in Expression Blend. Expression Blend 3 will launch handlers assigned to each buttons Click event.and display a design interface to the SMF player. In the Objects andYou can now debug the player. Clicking any of the buttons onTimeline section, youll find a myPlayer node in the tree of visual the screen will raise a Click event, which is now handled by theobjects that corresponds to the name given to the SMFPlayer objectauto-generated methods within MainPage.xaml.cs.previously. The goal is to create a template for SMFPlayer, then toadd three Suggestion buttons to the template. By using a template Suggested Videosin Expression Blend, you can add, edit or remove controls built Now lets use these buttons to enable the suggested video feature.into the player itself. The following XML will represent the suggestions: To create a template, right-click myPlayer in the Objects andTimeline window and select Edit Template | Edit a Copy. A Create Style Resource dialog will be displayed, click OK. To insert the three buttons on top of the video player, double-click the button 36 msdn magazineNow Playing 27. I KNOW A PLACE THATSDIFFERENT, BUT FAMILIAR Code in the cloud with the development technologies you already know With Windows AzureTMYou can code in the language you choose. You have the freedom to focus. Youre already equipped for the cloud. Find out more.www.windowsazure.com/msdn 28. Heres a more complete implementation of OnRequestCompleted: protected override void OnRequestCompleted( object sender, SimpleEventArgs e) {XDocument doc = XDocument.Parse(e.Result); List suggestions = new List(); foreach (XElement element in doc.Descendants("Suggestion")) {