Search and Find
Service
Title Page
Title Page
Copyright Page
Copyright Page
Contents at a Glance
4
Table of Contents
Table of Contents
About the Author
24
About the Technical Reviewer
25
Acknowledgments
26
Contributors
26
Introduction
27
…But We Will Give You All This!
27
Code Examples
27
Danger—Work in Progress!
28
Chapter 1: Introduction
29
Versions
29
What Is .NET 4.0 and VS2010 All About?
30
Efficiency
30
Maturation of Existing Technologies
30
Extensibility
31
Influence of Current Trends
31
Multicore Shift
31
Unit Testing and Test-Driven Development
31
Cloud Computing
31
What Do Others Think About .NET 4.0?
32
Mike Ormond (Microsoft Evangelist)
32
Eric Nelson (Microsoft Evangelist)
32
Craig Murphy (MVP and developer community organizer)
32
Phil Whinstanley (ASP.NET MVP and author)
33
Dave Sussman (MVP and author)
33
Matt Lacey (Devevening.co.uk organizer)
34
Alex Mackey (Author of this book and MVP)
34
Future Trends
34
My Own Subjective Opinion
35
Summary
35
Chapter 2: Visual Studio IDE and MEF
36
General Improvements
36
Improved Multitargeting Support
37
Intellisense
39
Add References
39
Web Development (Code-Optimized Profile)
39
Zoom
40
Highlight References
41
Navigate To
41
Box Selection
42
Call Hierarchy
43
Code Generation
44
Consume First Mode
46
Breakpoints
46
Toolbox
47
Code Snippets
47
Loading the Snippet into Visual Studio
49
Using Snippets
50
Creating Custom Start Pages
50
T4 (Text Template Transformation Toolkit) Files
51
VS2010 Premium and Ultimate
51
Generate Sequence Diagram
51
Historical Debugging (Team System Edition Only)
52
Static Analysis of Code Contracts
52
Customization of IDE
52
MEF (Managed Extensibility Framework)
53
Why Use MEF?
53
Hello MEF
54
How Did This Example Work?
56
MEF Catalogs
57
Metadata
59
What’s This All Got to Do with Visual Studio Extensibility?
60
Visual Studio Extensibility
60
Editor Margin
61
Distributing Extensions
62
Extension Gallery
62
Visual Studio Shell
63
Dotfuscator Changes
64
Conclusion
64
Chapter 3: Language and Dynamic Changes
65
Future Co-evolution of VB and C#
65
C# Enhancements
65
Named and Optional Parameters
66
Rules (Non-Optional)
67
VB.NET Changes
67
Line Continuation
67
Inferred Line Continuation Rules
67
Anonymous Method Support
68
Auto-Implemented Properties
68
Collection Initializes/From Keyword
68
Array Literals
69
New Syntax for Creating Jagged Arrays
69
Nullable Optional Parameters
69
Easier COM Interoperability
69
We’re Out of PIA
71
Variance
71
The Long Version for Everyone Else
72
Bad Arrays of Animals and Elephants
72
So, What’s the Problem?
73
Out
74
Contravariance
74
Example of Contravariance
75
Further Reading
77
Dynamic Enhancements
77
Can’t We Do This Kind of Thing Already in .NET?
77
Static Languages
77
Dynamic Languages
78
Dynamic Dangers
78
Type Dynamic
78
Is dynamic the Same as Var?
78
Why Type Variables as Dynamic?
79
System.Dynamic.ExpandoObject
79
System.Dynamic.DynamicObject
80
IDynamicMetaObjectProvider
81
Dynamic Limitations
81
Dynamic IL
81
Dynamic Language Runtime (DLR)
84
Expression/Abstract Syntax Trees (AST)
84
Dynamic Dispatch
84
Binders
84
IDynamicObject
85
Callsite Caching
85
IronPython
85
Embedding Dynamic Languages
85
Calling IronPython from .NET
85
Red Gate Reflector Add-In
86
ResolverOne
86
Michael Foord
87
F#
89
Jon Skeet
90
Future of C#
91
Chapter 4: CLR and BCL Changes
92
New CLR
92
ASP.NET
93
What Version of the CLR Does My Application Use?
93
Specifying the Framework to Use
93
VB.NET Command-Line Compiler
94
Improved Client Profile
94
In-Process Side-by-Side Execution
95
Garbage Collection
96
Garbage Collection Prior to .NET 4.0
96
Garbage Collection in .NET 4.0
97
GC.RegisterForFullGCNotification()
97
Threading
97
Globalization
97
Globalization Changes in .NET 4.0
98
TimeSpan Globalized Formatting and Parsing
98
Security
99
Transparency Model
99
Safe Critical Code
99
Critical Code
99
Safe Critical Gatekeeper
99
Why Does It Matter?
99
Security Changes
100
SecAnnotate
100
APTCA and Evidence
101
Monitoring and Profiling
101
Native Image Generator (NGen)
101
Native Code Enhancements
102
Exception Handling
102
New Types
103
BigInteger
103
Lazy
104
Memory Mapping Files
104
SortedSet
105
ISet
Interface 105
Tuple
105
System.Numerics.Complex
106
System.IntPtr and System.UIntPtr
106
Tail Recursion
106
Changes to Existing Functionality
106
Action and Func Delegates
106
Compression Improvements
106
File IO
107
Path.Combine()
107
Isolated Storage
107
Registry Access Changes
107
Stream.CopyTo()
108
Guid.TryParse(), Version.TryParse(), and Enum.TryParse
() 108
Enum.HasFlag()
108
String.Concat() and String.Join() support IEnumerable
109
String.IsNullOrWhiteSpace()
109
StringBuilder.Clear
109
Environment.SpecialFolder Enum Additions
109
Environment.Is64BitProcess and Environment.Is64BitOperatingSystem
109
Stopwatch.Restart()
109
ServiceProcessInstaller.DelayedAutoStart
110
Observable collection refactoring
110
IObservable
110
Network Class Libraries (NCLs)
110
Windows 7 Only
112
System.Device.Location
112
ExtendedProtection
112
Deprecated APIs
112
System.Data.OracleClient
112
Global Static Hosting Functions
112
Code Contracts
113
Hello Code Contracts
113
Installing Code Contracts
114
Example Code Contract
114
Enabling Code Contract Static Verification (Premium/Ultimate Edition Only)
116
Contract Inheritance
116
Architecture
117
Conditions
117
Preconditions
117
Post Conditions
118
Object Invariants
118
Code Contract Values
119
Contract.Result
119
Contract.OldValue
119
Pure
119
Interface Contracts
120
PEX
120
Conclusion
120
Further Reading
121
Chapter 5: Parallelization and Threading Enhancements
122
Parallelization Overview
122
Important Concepts
123
Why Do I Need These Enhancements?
123
Concurrent!= Parallel
123
Warning: Threading and Parallelism Will Increase Your Application's Complexity
124
Crap Code Running in Parallel is Just Parallelized Crap Code
125
What Applications Benefit from Parallelism?
125
I Have Only a Single Core Machine; Can I Run These Examples?
125
Can the Parallelization Features Slow Me Down?
125
Performance
125
Parallel Loops
126
Parallel.For()
126
An Unrealistic Example?
126
ParallelOptions
130
Parallel.ForEach()
130
Warning: Parallelization Can Hurt Performance
130
Parallel.Invoke()
130
Tasks
131
Task Scheduler
131
Creating a New Task
132
Task.Wait() and Task.WaitAll()
133
Task.WaitAny()
133
IsCompleted
134
ContinueWith()
134
Do Parallel Loops Create a Thread for Each Iteration?
134
Returning Values from Tasks
134
What if the Task Does Not Yet Have a Result?
135
Task Creation Options
135
Task Status
135
Overriding TaskScheduler
135
Scheduling on UI thread
136
Parallel Debugging Enhancements
136
Parallel Task Window
136
Parallel Stacks Window
138
PLINQ (Parallel LINQ)
140
Why Not Parallelize All LINQ Queries Automatically?
140
Hello PLINQ
140
Ordering Results
141
ForAll Operator()
141
AsSequential()
141
WithMergeOptions
141
PLINQ performance
142
Cancelling a PLINQ Query
142
Exceptions and Parallel LINQ
142
Coordination Data Structures (CDS) and Threading Enhancements
143
Thread Pool Enhancements
143
Thread.Yield()
143
Monitor.Enter()
143
Concurrent Collections
144
ConcurrentStack
144
ConcurrentQueue
144
ConcurrentDictionary
144
ConcurrentBag
144
BlockingCollection
144
Synchronization Primitives
146
Barrier
146
Cancellation Tokens
147
CountDownEvent
148
ManualResetEventSlim and SemaphoreSlim
149
SpinLock
149
ThreadLocal
149
Future Considerations
150
Danny Shih Interview
150
Phil Whinstanley
151
Conclusion
151
Further Reading
151
Chapter 6: Windows Workflow Foundation 4
152
Why Use WF?
152
What Can Windows Workflow Do for Me?
155
What Is Windows Workflow Foundation?
156
Workflow Instance/Runtime
156
Activities
156
Workflow Designer
157
Existing WF3 Users
158
Statemachine Workflow Has Gone
158
Upgrade White Papers
158
WF3 Runtime
158
Interop Activity
158
Is It Worth the Upgrade?
158
All Change
158
Hello WF 4
159
Hello WF
159
Arguments and Variables
160
Creating an Argument
160
WriteLine
162
Creating Another Sequence Activity
163
Checking Number of Tickets with an If Activity
164
Booking Unsuccessful and Assign activity
165
Booking Succssful and Parallel Activity
165
Displaying the Output of the Booking
166
Supplying Arguments to a Workflow
166
Creating Your Own Activities
167
Creating an Activity Composed of Other Activities
167
Creating Activities Purely in Code
168
Pure XAML Workflows
169
Invoking Workflows
170
Flowchart
171
WCF/Messaging Improvements
174
Correlation
174
WCF Workflow Service Applications
174
Activities
176
WF3 Activity Replacements
177
New Activities
177
Misc Improvements
181
John Mcloughlin
182
Summary
183
Chapter 7: Windows Communication Foundation
184
Configless WCF
184
Default Binding, behavior, and Endpoints
186
Default Binding and Behaviors
186
Standard Endpoints
187
No svc File
187
Router Service
188
Routing Example
188
Routing Filters
190
Multicast Support
190
Bridging Protocols
191
Redundancy
191
WS-Discovery
191
Managed Mode
191
Adhoc Mode
191
Service Announcement Events
194
WCF Starter Kit Integration
195
Help Pages
195
HTTP Caching
197
Misc Changes
197
Improved Integration with WF
197
Default Performance-Related Settings Changed
197
Low Memory
197
Other changes
198
Dublin/Windows Application Server
198
Further reading
198
Chapter 8: Entity Framework
199
EF and LINQ to SQL
199
Is LINQ to SQL Dead?
199
LINQ to SQL changes
200
Why Use EF?
200
Abstraction
200
Code Generation
200
Support for Different Databases
201
Design Time Support
201
Utilize LINQ
201
N-Tier Application Development
201
Where is EF Used?
201
EF 101
202
Entity Data Model
202
Creating an EDM
202
EdmGen.exe
203
Creating an Entity Data Model in Visual Studio
203
Navigating the EF model
207
Viewing How Entities Are Mapped
207
What Happens If My Database Structure Changes?
209
Querying Data
209
LINQ to Entities
209
ObjectQuery
211
Entity SQL
211
CRUD Operations in EF
211
Creating
211
Updating
212
Deleting
212
EFv1 Criticisms
213
Entity Framework 4
213
EDM Designer Changes
214
Performance
215
Pluralization
215
Deferred/Lazy Loading
215
Eager Loading
215
Complex Type Designer Support
215
Complex Types from Stored Procedures
217
Model Defined Functions
218
Model First Generation
219
Foreign Keys
225
Code Only/POCO
226
POCO in EF4
226
Code Generation Templates
227
Julie Lerman (Author of Programming Entity Framework and MVP)
228
Dane Morgridge
229
Conclusion
230
References/Further reading
230
Chapter 9: WCF Data Services
231
Hello WCF Data Services
231
Entity Framework
232
Creating a Data Service
235
IE Content Settings
236
Hello WDS
237
Querying WCF Data Services
237
Security in WCF Data Services
239
Query Interceptors
240
Returning Results in Different Formats
240
Using JSON with JavaScript
240
Using JSON with C#
241
WDS Proxy Classes
242
Retrieving Items with Proxy Classes
242
Adding a New Item with Proxy Classes
243
Update an Item
243
Delete an Item
244
WDS 1.5
244
RowCount and Server-Driven Paging
244
$count
244
$inlinecount=allpages
245
Limiting Number of Results Returned
245
Projections
245
Friendly Feeds
246
Miscellaneous Improvements
246
What’s the Relationship Between WDS and WCF RIA Services?
246
Conclusion
247
Further Reading
247
Chapter 10: ASP.NET
248
Project Templates
248
Web.config
249
IDE Changes
250
Code Snippets
251
ASP.NET Code Snippets
251
Using Snippets
251
Deployment
254
Web.config Transformation
254
Creating a New Deployment Configuration
255
Transforming Web.config from the Command Line
256
Web.config Transformation Options
256
Web Packages
257
One-Click Publishing
260
ViewState
261
ClientIDMode
262
Response.RedirectPermanent()
262
Meta-tags
263
URL Routing
263
HTML Encoding
264
HtmlString
264
Custom Request Validation
264
Custom Encoders
264
URL and Query String Length
265
Valid URL Characters
265
Accessibility and Standards
265
controlRenderingCompatibilityVersion
265
RenderOuterTable
266
CheckBoxList and RadioButtonList
266
ASP.NET Menu control
266
Browser Capability Files
266
Further Control Enhancements
267
Wizard Control
267
ListView Enhancements
267
GridView
267
CompareValidator
267
Query Extender
268
Browser capability files
268
Auto-Start Web Applications
268
Compress Session State
269
Caching
269
Velocity
269
System.Runtime.Caching
269
Resource Monitoring
270
Charting Controls
271
Dynamic Data Framework
272
Conclusion
272
Further Reading
272
Chapter 11: Microsoft AJAX Library
273
Architecture Changes
273
Compatibility
273
A pageLoad Problem Fixed
274
Installation
274
Adding Microsoft AJAX Libraries to Your Project
274
Client Script Loader
275
Referencing jQuery Scripts
275
Specifying Script Directories
276
Loading Custom Scripts
276
Lazy Loading
277
AJAX Libraries Now Hosted by Microsoft
277
ScriptManager EnableCDN
277
AJAX Toolkit Integration
277
Controls Now Exposed as jQuery Plug-ins
278
DataView
278
XHTML-Compliant?
278
Hello, Microsoft AJAX
278
sys-template CSS rule
279
DataView Binding
279
Declarative Binding
279
Programmatic Binding
281
A Cleaner Programmatic Binding
281
Master Detail Binding
282
Binding to External Services
284
WebService (.asmx)
284
WCF Binding
285
JSONP
286
Advanced Binding
286
Conditional Rendering
287
sys:if
287
$dataItem
287
$index
287
sys:codebefore and sys:codeafter
287
sys:innertext and sys:innerhtml
288
Binding Converters
288
Two-way Binding
288
Sys.Observer
290
WCF Data Services Data Context
290
Conclusion
292
Further Reading
292
Chapter 12: jQuery
293
jQuery or Microsoft AJAX libraries?
293
jQuery Overview
294
Downloading jQuery
294
IntelliSense
295
Script Hosting
295
Hello jQuery
296
How Does It All Work?
297
Selecting Elements
297
CSS Selectors
298
jQuery Selectors
299
Working with Sets
299
.each() method
300
Working with Attribute Values and CSS
300
Writing Elements Dynamically
301
Running a Script on Page Load
301
Adding Functions
302
Animation/Effects
302
Effect Overloads
302
Core Library Effects
303
Additional Effects
304
Glimmer
304
jQuery Tools
304
Chaining Events
305
Customizing jQuery
305
AJAX Methods
305
Load and Run JavaScript File
305
Submitting Data
306
Getting the Latest Version of a Page
306
Retrieving a JSON Object
307
A Better Way
307
Utility Methods
308
jQuery Additions
308
Summary
309
Further Reading
309
Chapter 13: ASP.NET MVC
310
MVC History
310
So Why MVC?
311
An Existing MVC application
311
What a State
313
Type Initialization
313
Installing MVC
314
Creating the MVC Application
314
Project Structure
314
Changing the Layout of MVC Pages
315
Creating the Model
316
Creating EF Entities
316
Repository Pattern
316
Creating Validation for Data Model
318
Creating a Controller
319
Adding a View
320
Running the application
321
A Closer Look at Routing
322
Returning Views
323
ViewData and TempData
323
Displaying a List of Data
323
Have We Gone Back to 1998?
325
Creating a Detail Page
325
HtmlHelper Methods
327
Strongly Typed Views
328
Creating a Strongly Typed View
328
Creating an Add New and Delete Functionality
331
Accepting Data from Users
332
Specify individual properties
332
Form Collection
332
Bind Attributes
332
Attributes
333
AcceptVerbs
333
OutputCache
333
Authorization
333
ASP.NET MVC and JavaScript
333
Custom Routing
336
ASP.NET MVC and Security
337
Extending MVC
338
Extension Methods
338
Filters
339
Testing
339
Creating a Fake Film Repository
339
Creating a Test
340
Modify Film Controller
342
Running Tests
342
ASP.NET MVC V2
343
ASP.NET MVC in the real world
343
What’s Next?
344
ASP.NET MVC Highlights
345
Considerations
345
Summary
346
Further Reading
346
Chapter 14: Silverlight Introduction
347
Silverlight versus Flash
347
Silverlight in the Real World
348
WPF
350
XAML
350
Silverlight Requirements and Installation
350
Expression Blend
350
Creating a New Silverlight Project
351
Project Structure
352
Hi Yo, Silver!
353
Understanding the Basics
353
Adding Content
354
Adding Silverlight to your Application
354
Object Tag
354
Pages in Silverlight
355
Creating a Silverlight User Control
356
App.xaml
357
Styles
357
Positioning Elements
358
Attached and Dependency Properties
359
Layout Controls
360
Canvas
360
Stack Panel
360
Grid
363
Simple Animation
365
Creating Animation Programmatically
365
Responding to User Events
366
Declarative Animation
367
HTML Integration
368
Calling a JavaScript Function from Silverlight
369
Changing DOM Element Values from Silverlight
369
Calling a Silverlight Function from JavaScript
369
Passing Parameters into Silverlight
371
InitParams
371
Query String
371
Embedding Content in a Silverlight application
371
Loading XAML Dynamically
372
Media
373
Additional Controls
375
Data Binding
375
DataBinding Modes
379
Data Binding and Dependency Properties
379
Two-Way Binding
380
Binding ListBox
380
DataTemplates
381
DataGrid
381
Network Communications
383
Summary
383
Further Reading
384
Chapter 15: WPF 4.0 and Silverlight 3.0
385
IDE Enhancements
385
VS2010 WPF/Silverlight Designer
385
Sort by Property Source
385
Property Icons
386
Style
386
Brushes
387
Binding Window
389
Design Time Data Binding
390
New Image Picker
390
Improved Grid Designer
390
Improved Error Handling for User Controls
391
Static Resource and Designer Fix
392
Drag-and-Drop Data Binding
392
Improved XAML Intellisense
396
New Controls
397
Ribbon Control and Bag O’Tricks
398
Windows 7 Integration
398
Jump Lists
398
Task Bar
399
Multitouch Functionality
400
Binding Changes
401
Run.text
401
Dynamic Binding Support
401
Input Bindings Now Support Bindings
402
Text-Rendering Improvements
402
TextOptions.TextFormattingMode
402
TextOptions.TextRenderingMode
403
RenderOptions.ClearTypeHint
404
East Asian Bitmap font support
404
Layout Rounding
404
Cached Composition
404
Animation Easing
405
Pixel Shader 3.0 Support
406
Visual State Manager Integration
406
HTML-XBAP Script Interop
406
Full-Trust XBAP Deployment
406
Client Profile
406
Miscellaneous Changes
406
Silverlight 3.0
407
Upgrading from Silverlight 2
407
Offline Applications
407
Creating an Offline Application
407
Uninstalling Offline Silverlight Applications
410
Detaching Manually
410
Retrieving Attachment State
410
Detecting Connection Status
411
Autoupdate
411
Deep Linking and Browser History
411
Navigation Application
411
Local Connections
412
Styles
414
Applying Styles Dynamically
414
Style Inheritance
415
Merge Dictionary Support
415
Save File Dialog
415
Filtering Files in SaveDialog
416
Element to Element Binding
416
Effects and Transformations
416
Plane Projection
416
Easing Effects
419
Pixel Shaders
419
Creating Your Own Pixel Shaders
421
Media
422
New Formats
422
Silverlight DRM
422
Performance
423
Binary XML Support
423
Enhanced Deep Zoom performance
423
Improved XAP Compression
423
Silverlight.js
423
Assembly Caching
423
GPU Acceleration
424
Miscellaneous Enhancements
425
Controls
425
Listbox
425
TextBox Cursor Styling
425
Accessibility
425
Browser Zoom Support
425
Slsvcutil.exe
426
WCF RIA Services
426
Blend 3/SketchFlow
426
Silverlight 4.0
427
Silverlight in the Real World
427
Rusty Johnson and Andy Britcliffe, SharpCloud
427
Summary
429
Further Reading
429
Chapter 16: Windows Azure
431
Azure Overview
432
Architecture
432
Will I Be Able to Install My Own Version of Windows Azure?
433
Before You Begin
433
Installation
434
Web Roles
434
Hello Azure
434
Chapter16.WebRole
435
Chapter16.HelloAzure
435
Azure and Configuration Settings
436
Logging and Debugging
438
Testing Azure Applications
438
Creating Development Storage
438
Service Details Node
440
Chapter16.HelloAzure Node
440
Chapter16.WebRole Node
440
Green Globes
441
Viewing Azure Logs
441
Deployment
442
Deploying Hello Azure Application
442
Application Package Section
445
Configuration Settings Section
445
Staging
447
Production URLs
448
Analytical Data
448
Local Storage
449
Worker Roles
449
Storage in Azure
450
Azure Storage
451
Working with Azure Storage
451
Azure API or REST Requests?
451
Let's REST for a Minute
452
Azure Storage Names
452
Blobs (Binary Large Object)
452
Blob Example
453
Accessing REST API Directly
455
How Do We Work with the REST API?
455
Working with Azure Storage with Raw HTTP Requests
456
Queues
458
Table Storage
461
Other Azure Services
463
Microsoft.NET Services
463
Windows Live Services
463
Pricing and SLA
464
Real World Azure
465
Ray Booysen
465
Rusty Johnson and Andy Britcliffe, SharpCloud
466
Advantages
467
Disadvantages
467
Conclusion
468
Further Reading
468
Index
469
All prices incl. VAT