322 Creating Events Without Custom Data.... CONTENTS Using the StringBuilder Class ...502 Creating a StringBuilder Object .... 1053 Using Windows Forms Data Binding...1053 Creating t
Trang 2Introducing Visual C# 2010
Adam Freeman
Trang 3
Introducing Visual C# 2010
Copyright © 2010 by Adam Freeman
All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher
ISBN-13 (pbk): 978-1-4302-3171-4
ISBN-13 (electronic): 978-1-4302-3172-1
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject
to proprietary rights
President and Publisher: Paul Manning
Lead Editor: Ewan Buckingham
Technical Reviewer: Damien Foggon
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Anne Collett and Kelly Moritz
Copy Editor: Kim Wimpsett and Mary Behr
Compositor: Bytheway Publishing Services
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-
ny@springer-sbm.com, or visit www.springeronline.com
For information on translations, please e-mail rights@apress.com, or visit www.apress.com
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales
The information in this book is distributed on an “as is” basis, without warranty Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work
The source code for this book is available to readers at www.apress.com
Trang 4Contents at a Glance
About the Author xxxii
About the Technical Reviewer xxxiii
Acknowledgments xxxiv
PART 1 Getting Started 1
Chapter 1: Introduction 3
Chapter 2: Getting Ready 7
Chapter 3: Understanding C# and the NET Framework 17
PART 2 The C# Language 31
Chapter 4: C# Fundamentals and Keyword Reference 33
Chapter 5: Numeric and Boolean Types 91
Chapter 6: Classes and Objects 131
Chapter 7: Fields 183
Chapter 8: Properties, Indexers, and Operators 203
Chapter 9: Methods 229
Chapter 10: Delegates, Events, and Anonymous Methods 305
Chapter 11: Namespaces 337
Chapter 12: Interfaces, Structs, and Enums 355
Chapter 13: Arrays 385
Chapter 14: Exceptions 419
Chapter 15: Generic and Anonymous Types 453
Chapter 16: Strings and Characters 481
Trang 5 CONTENTS AT A GLANCE
Chapter 17: Attributes 519
Chapter 18: Garbage Collection 539
PART 3 The NET Class Library 549
Chapter 19: Collections 551
Chapter 20: Files, Streams, and IO 621
Chapter 21: Networking & WCF 675
Chapter 22: Time & Dates 711
Chapter 23: Serialization 735
Chapter 24: Serialization 735
Chapter 25: Asynchronous Methods and Parallel Loops 815
Chapter 26: Other Useful Features and Classes 833
PART 4 Data and Databases 861
Chapter 27: LINQ to Objects 863
Chapter 28: Parallel LINQ 915
Chapter 29: LINQ to XML 925
Chapter 30: LINQ to Entities 965
Chapter 31: LINQ to DataSet 1001
PART 5 User Interfaces 1031
Chapter 32: Windows Forms 1033
Chapter 33: Windows Presentation Foundation 1069
Chapter 34: ASP.NET 1099
Chapter 35: Silverlight 1125
PART 6 Advanced Topics 1159
Chapter 36: Windows Integration 1161
Chapter 37: Cryptography and Security 1185
Chapter 38: Testing and Debugging 1201
Index 1231
Trang 6Contents
About the Authors xxxii
About the Technical Reviewers xxxiii
Acknowledgments xxxiv
PART 1 Getting Started 1
Chapter 1: Introduction 3
Who Should Read This Book? 3
What Is Covered in This Book? 3
What Do You Need to Read This Book? 4
What Is the Structure of This Book? 4
What Is in Each Chapter? 4
Getting the Example Code 5
Finding More Information 6
The MSDN C# Programming Guide 6
Online Forums 6
Other Books 6
Summary 6
Chapter 2: Getting Ready 7
Installing the Software 7
Installing Visual Studio 2010 7
Installing SQL Server 2008 9
Installing the Silverlight Tools 10
Downloading the Sample Code and Data 10
Trang 7 CONTENTS
Creating Your First C# Project 10
Creating the Project 11
Editing the Code 13
Compiling and Running the Program 14
Features That I Use Before Explaining Them 14
The using statements 14
The namespace statement 15
The class statement 15
The Main method 15
The Code Comments 16
The Console.WriteLine and Console.ReadLine methods 16
Summary 16
Chapter 3: Understanding C# and the NET Framework 17
C# and the NET Framework at a Glance 17
Introducing C# 17
Introducing the NET Framework 18
The Relationship between C# and the NET Framework 19
Understanding Assemblies 20
The Key Features of C# and the NET Framework 22
Understanding Object-Orientation 22
Understanding Type Safety 22
Understanding Automatic Memory Management 23
Understanding the Just-In-Time Compiler 23
Understanding Parallel Processing 23
Understanding Unmanaged/Native Code Support 24
Understanding the NET Technology Spectrum 24
Understanding NET Cross-Platform Support 29
Summary 30
Trang 8PART 2 The C# Language 31
Chapter 4: C# Fundamentals and Keyword Reference 33
Language Fundamentals 33
A Simple C# Program 33
C# Syntax 34
Types 41
Common Programming Tasks 46
Assigning Values 46
Making Comparisons 47
Performing Selections 49
Iterating Data Items 53
Keyword and Operator Reference 60
Type Keywords 61
Modifiers 69
Selection Keywords 75
Iterator Keywords 75
Jump Keywords 76
Exception Handling Keywords 77
Arithmetic Overflow Keywords 78
Synchronization Keywords 79
Parameter Keywords 79
Namespace Keywords 81
Literal Keywords 82
Object Keywords 83
LINQ Keywords 84
Other Keywords 84
Operators 87
Summary 89
Trang 9 CONTENTS
Chapter 5: Numeric and Boolean Types 91
Numeric Types 92
Using Numeric Literals 93
Implicit and Explicit Numeric Type Conversions 98
Using Overflow Checking 101
Using Struct Members 103
Using Numeric Operators 109
Arithmetic Operators 109
Unary Operators 113
Relational Operators 116
Logical Operators 118
Assignment Operators 122
Working with Very Large Integer Values 126
The Boolean Type 127
Using Boolean Literals 127
Using Boolean Results 128
Using Struct Members 129
Summary 130
Chapter 6: Classes and Objects 131
Creating a Basic Class 132
Adding Features to a Class 133
Creating Objects from Classes 136
Using Objects 139
Class Inheritance 150
Understanding Inheritance 153
Understanding Encapsulation 159
Understanding Polymorphism 160
Trang 10Casting Objects and Type Checking 165
Implicit vs Explicit Casting 165
Type Conversion Exceptions 169
Avoiding Explicit Cast Exceptions 170
Boxing and Unboxing 173
Using Nested Classes 175
Using Class Modifiers 176
Creating Static Classes 176
Creating Abstract Classes 178
Creating Sealed Classes 179
Creating Partial Classes 179
Using Access Modifiers 180
Summary 181
Chapter 7: Fields 183
Defining and Using Fields 184
Defining Fields 184
Initializing Fields 184
Reading and Updating Fields 186
The Fourth Stage of the Life Cycle 193
Applying Field Modifiers 193
Creating Static Fields 194
Creating Read-Only Fields 196
Applying Access Modifiers 199
Hiding Base Class Fields 199
Using the volatile Keyword 201
Summary 201
Trang 11 CONTENTS
Chapter 8: Properties, Indexers, and Operators 203
Creating a Property 204
Creating a Field-Backed Property 204
Using a Property 207
Creating an Automatically Implemented Property 208
Creating an Asymmetric Property 209
Creating a Computed Property 209
Mapping a Property Type to a Field Type 210
Using Access Modifiers 210
Using Other Modifiers 211
Creating an Indexer 215
Using Multiple Indexers 216
Creating a Validating Indexer 217
Creating an Indexer with Multiple Arguments 218
Creating Custom Operators 219
Creating Custom Unary Operators 219
Creating Custom Binary Operators 221
Creating Custom Conversion Operators 225
Summary 227
Chapter 9: Methods 229
Creating and Using a Simple Method 231
Defining the Method Name 232
Defining the Result Type 232
Defining the Parameters 233
Defining the Modifiers 234
Defining the Method Body 237
Using the Methods 238
Trang 12Understanding Parameters 239
Using Value Parameters 239
Using Reference Parameters 243
Using Output Parameters 245
Using Parameter Arrays 247
Using Optional Parameters 249
Using Named Parameters 250
Understanding Method Bodies 251
Using Local Variables 251
Using Method Results 256
Understanding Method Modifiers 257
Using Access Modifiers 257
Creating Static Methods 257
Creating Virtual Methods 258
Creating Sealed Methods 258
Creating Abstract Methods 259
Overloading Methods 259
Hiding and Overriding Methods 262
Hiding Methods 263
Overriding Methods 265
Sealing Methods 267
Understanding Method Specialization 268
Special Methods 269
The Main Method 269
Constructors 272
Destructors 290
Iterator Blocks 291
Partial Methods 296
Abstract Methods 299
Trang 13 CONTENTS
Extension Methods 301
Summary 304
Chapter 10: Delegates, Events, and Anonymous Methods 305
Using Delegates 306
Using Delegates for Callbacks 308
Multicasting with Delegates 310
Delegating Selectively 312
Interrogating Delegates 313
Using Events 315
Defining and Publishing EventHandler Pattern Events 317
Creating Nongeneric Events 322
Creating Events Without Custom Data 323
Applying Modifiers to Events 325
Using Action and Func Delegates 326
Using Action Delegates 326
Using Func Delegates 328
Anonymous Methods 329
Capturing Outer Variables 331
Lambda Expressions 334
Summary 336
Chapter 11: Namespaces 337
Consuming Namespaces 337
Using Fully Qualified Names 338
Importing Namespaces 339
Creating Namespaces 340
Nesting Namespaces 342
Logically Nesting Namespaces 343
Spreading Namespaces Across Files 344
Trang 14Adding Types to Existing Namespaces 346
Disambiguating Namespaces and Types 347
Disambiguation with Fully Qualified Names 349
Disambiguating with Aliases 349
Aliasing Namespaces 350
Resolving Type or Namespace Hiding 351
Summary 353
Chapter 12: Interfaces, Structs, and Enums 355
Using Interfaces 356
Defining and Using a Simple Interface 356
Specifying Interface Members 358
Deriving Interfaces 362
Defining a Partial Interface 365
Implementing Interfaces 365
Using Structs 371
Defining and Instantiating a Struct 371
Differences Between Structs and Classes 374
Copying a Struct 376
Using an Enum 380
Defining an Enum 380
Using an Enum 381
Using Underlying Types and Numeric Values 382
Combining Enum Values 383
Summary 384
Chapter 13: Arrays 385
Defining and Initializing Arrays 387
Getting and Setting Array Values 389
Using Array Initializers 391
Trang 15 CONTENTS
Enumerating Arrays 393
Enumerating with a for Loop 393
Enumerating with a foreach Loop 395
Enumerating Using IEnumerator and IEnumerator<T> 396
Breaking from Enumerations 398
Using System.Array Members 400
Sorting Arrays 400
Processing All of the Elements in an Array 401
Resizing and Copying an Array 402
Finding Items in an Array 406
Using Arrays with LINQ 408
Using Arrays as Collections 409
Using Multidimensional Arrays 409
Using Rectangular Arrays 410
Using Jagged Arrays 415
Summary 418
Chapter 14: Exceptions 419
Handling Exceptions 420
Using try Statements and catch Clauses 421
Handling Different Exception Types 424
Nesting try Statements 427
Using Exception Members 427
Using finally Clauses 430
Throwing Exceptions 432
Rethrowing Exceptions 436
Creating and Throwing Custom Exceptions 438
Throwing Meaningful Exceptions 441
Summary 451
Trang 16 Chapter 15: Generic and Anonymous Types 453
Using Generic Types 454
Defining a Generic Class 456
Creating Objects from Generic Classes 456
Implementing and Using Generic Class Members 457
Defining Multiple Parameter Types 460
Casting from Parameterized Types 461
Constraining Parameterized Types 462
Defining a Method-Specific Parameterized Type 465
Deriving from a Generic Base Class 467
Creating Generic Interfaces 471
Creating Generic Structs 472
Type Variance 472
Using the default Keyword 477
Using Anonymous Types 478
Summary 480
Chapter 16: Strings and Characters 481
Working with Characters 482
Expressing Characters Using Literals 482
Performing Operations on Characters 483
Using Struct Members 484
Using Strings 486
Expressing Strings Using String Literals 486
Performing Operations on Strings 488
Using Regular Expressions 495
Using Class Members 496
Trang 17 CONTENTS
Using the StringBuilder Class 502
Creating a StringBuilder Object 502
Using a StringBuilder Object 502
Formatting Strings 507
Using Composite Formatting 507
Formatting Types 511
Creating String Representations of Custom Types 514
Performing Custom Composite Formatting 516
Summary 518
Chapter 17: Attributes 519
Using Attributes 519
Applying Attributes with Parameters 521
Testing for an Attribute 522
Testing for an Attribute Applied to a Class 522
Testing for an Attribute Applied to a Field 525
Testing for an Attribute Applied to a Property 528
Testing for an Attribute Applied to a Method 530
Creating a Custom Attribute 532
Using a Custom Attribute 533
Defining Properties in a Custom Attribute 535
Controlling How a Custom Attribute Can Be Used 535
Controlling Attribute Inheritance 537
Summary 538
Chapter 18: Garbage Collection 539
Explicitly Running the Garbage Collector 540
Implementing a Destructor 541
Destructors vs Finalizers 542
Problems with Destructors 543
Trang 18Using Disposal 544
Using Weak References 546
Summary 547
PART 3 The NET Class Library 549
Chapter 19: Collections 551
The ICollection<T> Interface 553
Generic Lists 554
The IList<T> Interface 555
The List<T> Collection 556
The LinkedList<T> Collection 575
The SortedList<TKey, TVal> Collection 581
Generic Dictionaries 585
The IDictionary<TKey, TVal> Interface 586
The KeyValuePair<TKey, TVal> Structure 588
The Dictionary<TKey, TVal> Collection 589
The SortedDictionary<TKey, TVal> Collection 593
Generic Sets 595
The ISet<T> Interface 595
The HashSet<T> Collection 597
The SortedSet<T> Collection 599
Generic Queues and Stacks 602
The Queue<T> Collection 602
The Stack<T> Collection 604
Other Generic Collection Interfaces 606
The IComparer<T> Interface 606
The IEqualityComparer<T> Interface 608
Treating Arrays as Collections 609
Trang 19 CONTENTS
Creating Constrained Collections 613
Read-Only Lists 613
Other Read-Only Collections 614
Legacy Collections 617
Summary 619
Chapter 20: Files, Streams, and IO 621
Working with Files and Directories 622
Using the System.IO.Directory Class 622
Using the FileInfo and DirectoryInfo Classes 630
Using the System.IO.File Class 639
Using the System.IO.Path Class 643
Monitoring for Changes 645
Working with Streams, Readers, and Writers 650
Using Streams 650
Using Readers and Writers 666
Summary 673
Chapter 21: Networking & WCF 675
Requesting Data 675
Using WebClient Members to Configure a Request 677
Using WebClient Members to Retrieve Data 679
Using WebClient Events 682
Programming with Sockets 684
Creating a Simple TCP Client & Server 684
Writing a Parallel Server 691
The Windows Communication Foundation 693
Creating the WCF Server 694
Creating the WCF Client 697
Trang 20Other Useful Network Classes 700
Writing a Simple Web Server 700
Using Connectionless Networking 704
Using the Domain Name System 707
Summary 709
Chapter 22: Time & Dates 711
Measuring Small Amounts of Time 712
Working with Periods of Time 715
Creating and Using TimeSpan Values 715
Performing Operations on TimeSpan Values 719
Formatting TimeSpan Strings 720
Working with Particular Dates and Times 723
Creating and Using DateTime Values 724
Performing Operations on DateTime Values 727
Formatting DateTime Strings 730
Summary 733
Chapter 23: Serialization 735
Using Binary Serialization 736
Serializing Graphs of Objects 739
Serializing Multiple Objects to a Single Stream 741
Selectively Serializing Fields 744
Using Serialization Callbacks 745
Version Tolerance 748
Using SOAP Serialization 752
Version Tolerance 754
Serializing Generic Objects 755
Using XML Serialization 755
Selectively Serializing Fields 757
Trang 21 CONTENTS
Mapping Members to Elements and Attributes 758
Changing the Name for Attributes and Elements 759
Using Data Contract Serialization 760
Preparing a Class for Data Contract Serialization 760
Generating Portable XML 761
Generating NET-specific XML 762
Generating JSON 764
Summary 765
Chapter 24: Serialization 735
Understanding Single- and Multi-Threaded Execution 768
Getting Started with Tasks 772
Creating a Task 772
Starting a Task 773
Waiting for a Task 774
Getting Results from Tasks 776
Passing Parameters to a Task 778
Getting the Status of a Task 780
Using the Status Properties 782
Canceling Tasks 782
Checking and Throwing in a Single Statement 784
Cancelling Multiple Tasks 786
Handling Task Exceptions 787
Handling an Exception in a Task Body 787
Handling an Exception from a Trigger Method 789
Dealing with Exceptions using Task Properties 792
Using a Custom Exception Escalation Policy 794
Chaining Tasks Together 796
Creating a Simple Continuation 796
Trang 22Getting Details of the Antecedent 797 Providing a Continuation Result 798 Creating Chains of Continuations 800 Creating Selective Continuations 801
Sharing Data between Tasks 803
Understanding a Critical Region 806 Creating a Critical Region 806 Avoiding Synchronization 808
Using Concurrent Collections 809 Summary 813
Chapter 25: Asynchronous Methods and Parallel Loops 815
Using Asynchronous Methods 816
Using Pre-Built Asynchronous Methods 816 Asynchronously Calling Any Method 819 Waiting for an Asynchronous Method to Complete 820 Mixing Asynchronous Methods and Tasks 823
Using Parallel Loops 824
Creating a Parallel ForEach Loop 824 Creating a Parallel For Loop 826 Breaking and Stopping Parallel Loops 827
Summary 831
Chapter 26: Other Useful Features and Classes 833
Converting Between Types 834 Returning Multiple Results from Methods Using Tuples 836 Aliasing Generic Types 839 Using Nullable Types 841
Using the Null-Coalescing Operator 842
Trang 23 CONTENTS
Working with the Console 843
Reading from and Writing to the Console 843 Making the Console Beep 846 Modifying the Appearance of the Console 846
Generating Random Numbers 848 Converting Strings to and from Bytes 849 Getting Environment Information 850 Performing Math Operations 852 Using Conditional Compilation 853
Using Visual Studio to Define Symbols 855 Conditionally Compiling Methods 856
Checking Network Connectivity 857
Listening for Connectivity Changes 859
Summary 860
PART 4 Data and Databases 861
Chapter 27: LINQ to Objects 863
Performing a Simple LINQ Query 864
Understanding LINQ to Objects Data Sources 866 Understanding Query Results 867 Understanding Query Types 870
Performing LINQ Operations 874
Filtering Data 874 Projecting Data 876 Ordering Data 881 Grouping Data 885
Using Method Syntax 891 Understanding Deferred Execution 895
Reusing Queries 895
Trang 24Referring to Variables 896 Forcing Immediate Execution 897
Converting Query Results 899 Using Legacy Collections as LINQ Data Sources 902
Explicitly Specifying the Range Variable Type 902 Using Cast and OfType Extension Methods 903
Performing Advanced LINQ Operations 905
Aggregating Data 905 Joining Data 907 Creating Combinations of Data 910 Creating Additional Range Variables 911
Summary 913
Chapter 28: Parallel LINQ 915
Performing a Parallel LINQ Query 915 Understanding PLINQ Result Ordering 918
Preserving Order in a PLINQ query 920
Forcing Parallel Execution 921 Performing Queries without Results 922 Summary 923
Chapter 29: LINQ to XML 925
Using the LINQ XML Classes 926
Creating XML Declaratively 926 Populating an XElement or XDocument with an IEnumerable 933 Reading and Writing XML Files 934 Processing XML Declaratively 936 Modifying XML 940
Using LINQ to XML Queries 944
Querying XML for Data 945
Trang 25 CONTENTS
Creating XML from LINQ Queries 946 Create Objects from XML 949 Modifying and Transforming XML Data 950 Sorting XML 957 Grouping XML 958 Using Parallel LINQ to Process XML 960
Using LINQ to Entities 973
Using the Data Model Context 974 Using Table Properties and Row Objects 975 Understanding the IQueryable<T> Interface 977 Enumerating the Results 978
Navigating Using Foreign Key Relationships 979
Querying Using Navigation Properties 982 Using Navigation Data Efficiently 983
Performing Common Database Operations 985
Querying Data 985 Inserting Data into the Database 993 Updating Data in the Database 996 Deleting Data 998
Enabling Concurrency Checking 999 Summary 1000
Chapter 31: LINQ to DataSet 1001
Connecting to and Querying a Database 1002
Trang 26Setting Up the Database 1002 Creating a Connection to the Database 1004 Executing a SQL Query 1010
Understanding the DataSet Class 1012
Enumerating Results with DataTable and DataRow Objects 1014
Querying DataSets with LINQ 1016
Perform Joins on a DataSet 1018 Comparing Data 1021
Performing Database Operations Using Cached Data 1024
Inserting Data 1024 Modifying Data 1027 Deleting Data 1029
Summary 1030
PART 5 User Interfaces 1031
Chapter 32: Windows Forms 1033
Building a Stand-Alone Window Forms Program 1033
Creating the Project 1034 Adding the Controls 1036 Setting the Control Properties 1038 Adding the MenuStrip and StatusStrip 1041 Setting the Control Names 1043 Setting the Tab Order 1045 Wiring the Controls 1045 Setting the Icon 1053 Testing the Program 1053
Using Windows Forms Data Binding 1053
Creating the Project and Creating the Data Model 1053 Creating and Using the Object Data Source 1054
Trang 27 CONTENTS
Formatting the Grid Control 1056 Loading the Data 1058 Wiring the Save Button 1058 Testing the Program 1059 Two Program Variations 1060
Windows 7 UI Integration 1063
Using Aero Glass 1063
Summary 1066
Chapter 33: Windows Presentation Foundation 1069
Building a Stand-Alone WPF Program 1069
Creating the Project 1069 Adding the Controls 1072 Setting the Control Properties 1074 Adding the StatusBar Item 1076 Adding the Menu Item 1077 Setting the Tab Order 1077 Wiring the Controls 1078 Managing the Focus 1081 Setting the Program Icon and Window Name 1082 Testing the Program 1082
Using WPF Data Binding 1083
Formatting the DataGrid Control 1084 Loading the Data 1085 Wiring the Button 1085 Testing the Program 1086
Using WPF-Specific Features 1086
Using WPF Animations 1086 Using WPF Commands 1090
Trang 28Summary 1098
Chapter 34: ASP.NET 1099
Building a Web Forms Program 1099
Creating the Project 1099 Adding the Controls 1102 Setting the Control Properties 1104 Setting the Tab Order 1106 Wiring the Button Control 1107 Setting the Focus 1107 Testing the Program 1108
Using Web Forms Data Binding 1108
Create the Project and the Entity Data Model 1109 Adding the Web Form 1109 Creating the Web Forms Data Source 1109 Adding the GridView Control 1111 Testing the Program 1112
Using ASP.NET Dynamic Data 1113
Creating the Project 1113 Creating the Entity Data Model 1114 Registering the Data Model 1114 Testing the Program 1114 Customizing a Dynamic Data Application 1116
Summary 1124
Chapter 35: Silverlight 1125
Creating the Swimming Calculator 1126
Creating the Project 1126 Defining the Layout 1128 Adding the TextBox Controls 1131
Trang 29 CONTENTS
Adding the Label Controls 1132 Adding the TextBlock Control 1133 Adding the Button Control 1134 Adjusting the Layout 1135 Wiring the Button 1136 Adding a Child Window 1137
Using a WCF RIA Service 1140
Creating the Project 1141 Creating the Data Model 1141 Creating the Domain Service Class 1142 Creating the Silverlight Client 1144 Testing the Application 1149
Using Silverlight Out-of-Browser Support 1149
Configuring the Out-of-Browser Support 1150
Using a Silverlight Program Out-of-Browser 1152
Making Installation Part of the Interface 1153 Using Other Out-of-Browser Features 1157
Summary 1157
PART 6 Advanced Topics 1159
Chapter 36: Windows Integration 1161
Using the Windows Event Log 1161
Reading an Event Log 1162 Writing to an Event Log 1165
Using Elevated Privileges 1167 Creating a Windows Service 1169
Creating the Service Class 1170 Adding the Service Functionality 1172 Adding the Service Installer 1174
Trang 30Add the MSI Installer 1175 Installing the Service 1177 Creating the Client 1179
Using the Windows Registry 1179
Searching the Registry 1179 Reading and Modifying the Registry 1182
Summary 1183
Chapter 37: Cryptography and Security 1185
Encrypting and Decrypting Data 1186
Creating and Using Encryption Keys 1186 Encrypting Data 1189 Decrypting Data 1190 Using the Windows Data Protection API 1191
Using Hash Codes 1193
Generating a Hash Code 1194 Verifying a Hash Code 1196
Generating Secure Random Numbers 1197 Working Securely with Strings 1198 Summary 1200
Chapter 38: Testing and Debugging 1201
Using the Debug and Trace Classes 1202
Using the Debug Class 1202 Using the Trace Class 1212
Using Static Code Analysis 1214
Selecting the Code Analysis Rules 1214 Performing Static Analysis 1215 Dealing with a Rule Violation 1216
Trang 31 CONTENTS
Using Code Contracts 1221
Installing and Enabling Code Contract Support 1221 Writing Code Contracts 1222 Using the Static Checker 1226 Using the Runtime Checker 1229
Summary 1230
Index 1231
Trang 32 Adam Freeman is an experienced IT professional who has held senior
positions in a range of companies, most recently as chief technology officer and chief operating officer of a global bank Now retired, he spends his time writing and training for his first competitive triathlon This is his tenth book on programming and his eighth on NET
Trang 33About the Technical Reviewer
Damien Foggon is a developer, writer, and technical reviewer in cutting-edge technologies and has
contributed to more than 50 books on NET, C#, Visual Basic and ASP.NET He is the co-founder of the
Newcastle based user-group NEBytes (online at http://www.nebytes.net), is a multiple MCPD in NET 2.0 and NET 3.5 and can be found online at http://blog.littlepond.co.uk
Trang 36
Introduction
I started programming in C# when version 1.0 was the current release and NET was being billed as a
Java-killer In fact, the first C# book that I wrote was a guide to the language for Java programmers
It’s seven years later, and C# hasn’t killed Java, but it has established itself as one of the most useful and expressive programming languages in use today—and one of the most widely used C# has
developed its own identity, and each new version of the language has further reinforced that identity
The current version of C#/.NET, version 4, is mature, complete, flexible, and feature rich The
development tools are good, the integration with Windows is excellent, and there is a thriving
community of developers providing enhancements and add-on libraries
I like programming in C#, and I hope you will come to like it too I am not a language evangelist; I
believe that the best language to solve a problem is usually the one that you already know But I find
myself turning to C# more and more I find the development tools to be solid and flexible, I like the
integration with Windows, and there are, for me, two killer features The first is the excellent parallel
programming features that let a program do more than one thing at a time (these features are discussed
in Chapter 24 of this book) The second is the indescribably brilliant data-processing LINQ feature
(covered in Chapters 27–31)
In this book, I will take you on a tour through C#, starting with the language itself, and then onto the rich APIs that are included with the NET Framework My main tool of instruction will be code—lots and lots of code I don’t discuss the abstractions of object-oriented programming, for example I explain it
through code samples and illustrations so that you know how it affects your programming and how to
get the best results As we go from chapter to chapter, you’ll learn everything you need to know in order
to write effective C# programs to solve the problems that you will face most often
Who Should Read This Book?
This book was written for programmers who have no experience with C# and/or little to no experience with object-oriented programming I have tried to explain every term and concept as it arises, but this is
a book that teaches C# programming, rather than programming in general
What Is Covered in This Book?
This book covers the C# language and the major NET APIs and features In each chapter you will find an explanation of what a feature is for and what it does, as well as all the information you need to get started using that feature effectively There are lots of code examples, and each technique is carefully explained There is only so much content that you can fit into a book, and so, since this is an introduction to
C#, I have focused on the features that are most commonly used and are the easiest to use As C# has
evolved, duplicate features have emerged There are several different APIs available for processing XML
Trang 37CHAPTER 1 INTRODUCTION
data, for example In these cases, I have included the most recent or most widely used and have omitted the others As a new C# programmer, you don’t need to know the historic value of this API or that language feature; at this stage, you just need to know how to get something done quickly, cleanly, and effectively Once you have the basics of C# and an understanding of the current features, you can use this knowledge to work on legacy code if the need arises
What Do You Need to Read This Book?
You could just sit and read this book, but to get the most benefit, you should be able to follow along with the examples on your own computer, which means that you will need a Windows computer Aside from Windows, basic versions of all the software you will need are available from Microsoft free of charge Chapter 2 tells you what you need, explains where to get it from, and shows you how to install it and get
it ready for use
What Is the Structure of This Book?
There are five parts to this book The first part helps you get ready to use C# and to understand the building blocks of the NET Framework At the end of these chapters, you will have all the software you need installed and configured and be able to tell an assembly from a code file
Part II introduces the C# language and object-oriented programming You will learn how C#
represents different kinds of data and how to create and use your own representations C# includes some built-in data types that you will use in every program that you write, and these are covered in depth At the end of these chapters, you will be able to write C# programs that can do useful, but basic, things
Part III introduces some of the major APIs This is where the complexity and utility of the programs you will be able to write really starts to take off You will learn how to write network programs, deal with sets of data in useful ways, work with files, make your data persistent, and even how to use the C# parallel programming features At the end of these chapters, you’ll start to have some serious C# chops and be able to take on most programming problems using C#
Part IV focuses on data and databases, which have some excellent support in C# Most of the chapters in this part of the book relate to a feature called Language Integrated Query (LINQ) By the end
of these chapters, you will be able to query and modify object data, XML data, and SQL data
Part V covers the different feature sets that support user interfaces, which range from traditional Windows client applications to web UIs C# has some great features for UI design and implementation, and you may be surprised how simple it can be to get some great results with very little effort
Part VI describes some more advanced topics You can skip these chapters and still end up with a great grasp of C# and be able to write useful and elegant programs But at some point, you’ll face a problem that can be solved only by using one of these advanced features, so I have included this information for when that happens
What Is in Each Chapter?
The format differs slightly from chapter to chapter to best suit the topic at hand, but there are some things that are common to most of them There are a lot of code listings in every chapter, so I have included a summary table at the start of each one to make it easier when you are looking for something specific Table 1-1 shows part of the table from Chapter 6
Trang 39CHAPTER 1 INTRODUCTION
Getting the Example Code
All the code samples are available for download from http://apress.com/book/sourcecode Each codeexample is self-contained I am not a fan of building a program up over several chapters, preferring todemonstrate just the feature being described This means that some of the examples I present arearbitrary in nature, but each one can be compiled and used on its own, and you can see exactly how touse the feature being discussed
Finding More Information
By the time you have finished reading this book, you’ll know everything you need to be an effective C#programmer—how to use the language and how to use the major API features, such as networking, dataaccess, and user interfaces, and so on But there is always more to learn, especially in a language with therich library support that C# enjoys When you are looking for more advanced information, I recommendthe following sources
The MSDN C# Programming Guide
The MSDN Library includes a useful tour of different C# features; the authors assume you are already familiarwith C#, so it is not comprehensive in coverage, but it can be helpful if you want just a little more depth than Iprovide in this book You can find the guide at http://msdn.microsoft.com/en-us/library
Online Forums
Numerous web sites discuss C# and NET The one that seems to have the most knowledgeable
participants and the lowest amount of useless noise is http://stackoverflow.com This site is not specific
to C#, but there is a very active C# community, and when you get stuck, chances are that someone hashad the same problem and has asked for help
Other Books
Introductory books—like this one—aim for breadth of coverage, introducing you to as many features aspossible to get you up and running quickly At key points in this book, I suggest other books that are entirelydedicated to a topic that I have covered in a single chapter The information I give you will get you going for 90percent of the problems you will face, but you’ll need to dig further into the detail for the other 10 percent.Some of the books I suggest are my own, and many of them are published by Apress, but all of them providegood in-depth detail to help you build your expertise in a specific language feature
Summary
It should be clear that I am enthusiastic about C# I think it is a super language that can be used to greateffect It is my hope that as you read through this book you will not only learn how to program in C# butalso gain your own enthusiasm There is a lot to like about C#, and our journey through the language andits features begins here
Trang 40
Getting Ready
You need to prepare yourselves before you can start to learn C# In this chapter, you’ll install the
development tools you need: Visual Studio 2010 and SQL Server, both of which are available as paid-for and free editions You will use Visual Studio 2010 throughout this book and SQL Server in Parts IV and V
of this book when you look at data and databases and user interfaces You’ll also install the latest version
of the Silverlight tools, which you’ll need for Chapter 35
Once the tools are installed, I’ll show you how to create the traditional Hello World application to
demonstrate how to create, compile, and execute a simple project with Visual Studio
Installing the Software
Before you can start exploring C# and the NET Framework, you need to get set up You’ll need a PC
running Windows—and it needs to be Windows 7 if you want to follow some of the Windows integration examples in Chapter 36 However, for the other chapters, older versions of Windows will be fine
Installing Visual Studio 2010
The most important tool you will need is Visual Studio 2010, Microsoft’s development environment for the NET Framework There are different editions of Visual Studio: Professional, Premium, and Ultimate The Ultimate edition is the most comprehensive with all sorts of bells and whistles It also has a
significant price tag; at the time of writing, the Ultimate edition costs over $10,000 In all fairness to
Microsoft, very few people will end up paying that price because of discount schemes, but nonetheless Visual Studio can be an expensive tool
Don’t worry if your budget doesn’t stretch to a high sticker price; you can get everything you need for this book for free Microsoft’s entry level development tool is Visual Studio 2010 Express and is
available without charge from microsoft.com/express The Express editions lack some of the
convenience features, but are still very capable There are several editions available; for most of this
book, you’ll need the Visual C# 2010 Express edition, and for the ASP.NET section, you will need the
Visual Web Developer 2010 edition